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/RecursiveASTVisitor.h"
28 #include "clang/AST/TypeLoc.h"
29 #include "clang/Basic/Builtins.h"
30 #include "clang/Basic/FixedPoint.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->getDeclName();
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   auto *DMD = dyn_cast<OMPDeclareMapperDecl>(CurContext);
343   if (LangOpts.OpenMP && DMD && !CurContext->containsDecl(D) &&
344       isa<VarDecl>(D)) {
345     Diag(Loc, diag::err_omp_declare_mapper_wrong_var)
346         << DMD->getVarName().getAsString();
347     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
348     return true;
349   }
350 
351   DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,
352                              AvoidPartialAvailabilityChecks, ClassReceiver);
353 
354   DiagnoseUnusedOfDecl(*this, D, Loc);
355 
356   diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
357 
358   if (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)) {
359     if (const auto *VD = dyn_cast<ValueDecl>(D))
360       checkDeviceDecl(VD, Loc);
361 
362     if (!Context.getTargetInfo().isTLSSupported())
363       if (const auto *VD = dyn_cast<VarDecl>(D))
364         if (VD->getTLSKind() != VarDecl::TLS_None)
365           targetDiag(*Locs.begin(), diag::err_thread_unsupported);
366   }
367 
368   if (isa<ParmVarDecl>(D) && isa<RequiresExprBodyDecl>(D->getDeclContext()) &&
369       !isUnevaluatedContext()) {
370     // C++ [expr.prim.req.nested] p3
371     //   A local parameter shall only appear as an unevaluated operand
372     //   (Clause 8) within the constraint-expression.
373     Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context)
374         << D;
375     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
376     return true;
377   }
378 
379   return false;
380 }
381 
382 /// DiagnoseSentinelCalls - This routine checks whether a call or
383 /// message-send is to a declaration with the sentinel attribute, and
384 /// if so, it checks that the requirements of the sentinel are
385 /// satisfied.
386 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
387                                  ArrayRef<Expr *> Args) {
388   const SentinelAttr *attr = D->getAttr<SentinelAttr>();
389   if (!attr)
390     return;
391 
392   // The number of formal parameters of the declaration.
393   unsigned numFormalParams;
394 
395   // The kind of declaration.  This is also an index into a %select in
396   // the diagnostic.
397   enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
398 
399   if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
400     numFormalParams = MD->param_size();
401     calleeType = CT_Method;
402   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
403     numFormalParams = FD->param_size();
404     calleeType = CT_Function;
405   } else if (isa<VarDecl>(D)) {
406     QualType type = cast<ValueDecl>(D)->getType();
407     const FunctionType *fn = nullptr;
408     if (const PointerType *ptr = type->getAs<PointerType>()) {
409       fn = ptr->getPointeeType()->getAs<FunctionType>();
410       if (!fn) return;
411       calleeType = CT_Function;
412     } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
413       fn = ptr->getPointeeType()->castAs<FunctionType>();
414       calleeType = CT_Block;
415     } else {
416       return;
417     }
418 
419     if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
420       numFormalParams = proto->getNumParams();
421     } else {
422       numFormalParams = 0;
423     }
424   } else {
425     return;
426   }
427 
428   // "nullPos" is the number of formal parameters at the end which
429   // effectively count as part of the variadic arguments.  This is
430   // useful if you would prefer to not have *any* formal parameters,
431   // but the language forces you to have at least one.
432   unsigned nullPos = attr->getNullPos();
433   assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
434   numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
435 
436   // The number of arguments which should follow the sentinel.
437   unsigned numArgsAfterSentinel = attr->getSentinel();
438 
439   // If there aren't enough arguments for all the formal parameters,
440   // the sentinel, and the args after the sentinel, complain.
441   if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
442     Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
443     Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
444     return;
445   }
446 
447   // Otherwise, find the sentinel expression.
448   Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
449   if (!sentinelExpr) return;
450   if (sentinelExpr->isValueDependent()) return;
451   if (Context.isSentinelNullExpr(sentinelExpr)) return;
452 
453   // Pick a reasonable string to insert.  Optimistically use 'nil', 'nullptr',
454   // or 'NULL' if those are actually defined in the context.  Only use
455   // 'nil' for ObjC methods, where it's much more likely that the
456   // variadic arguments form a list of object pointers.
457   SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc());
458   std::string NullValue;
459   if (calleeType == CT_Method && PP.isMacroDefined("nil"))
460     NullValue = "nil";
461   else if (getLangOpts().CPlusPlus11)
462     NullValue = "nullptr";
463   else if (PP.isMacroDefined("NULL"))
464     NullValue = "NULL";
465   else
466     NullValue = "(void*) 0";
467 
468   if (MissingNilLoc.isInvalid())
469     Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
470   else
471     Diag(MissingNilLoc, diag::warn_missing_sentinel)
472       << int(calleeType)
473       << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
474   Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
475 }
476 
477 SourceRange Sema::getExprRange(Expr *E) const {
478   return E ? E->getSourceRange() : SourceRange();
479 }
480 
481 //===----------------------------------------------------------------------===//
482 //  Standard Promotions and Conversions
483 //===----------------------------------------------------------------------===//
484 
485 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
486 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
487   // Handle any placeholder expressions which made it here.
488   if (E->getType()->isPlaceholderType()) {
489     ExprResult result = CheckPlaceholderExpr(E);
490     if (result.isInvalid()) return ExprError();
491     E = result.get();
492   }
493 
494   QualType Ty = E->getType();
495   assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
496 
497   if (Ty->isFunctionType()) {
498     if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
499       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
500         if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
501           return ExprError();
502 
503     E = ImpCastExprToType(E, Context.getPointerType(Ty),
504                           CK_FunctionToPointerDecay).get();
505   } else if (Ty->isArrayType()) {
506     // In C90 mode, arrays only promote to pointers if the array expression is
507     // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
508     // type 'array of type' is converted to an expression that has type 'pointer
509     // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
510     // that has type 'array of type' ...".  The relevant change is "an lvalue"
511     // (C90) to "an expression" (C99).
512     //
513     // C++ 4.2p1:
514     // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
515     // T" can be converted to an rvalue of type "pointer to T".
516     //
517     if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
518       E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
519                             CK_ArrayToPointerDecay).get();
520   }
521   return E;
522 }
523 
524 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
525   // Check to see if we are dereferencing a null pointer.  If so,
526   // and if not volatile-qualified, this is undefined behavior that the
527   // optimizer will delete, so warn about it.  People sometimes try to use this
528   // to get a deterministic trap and are surprised by clang's behavior.  This
529   // only handles the pattern "*null", which is a very syntactic check.
530   const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts());
531   if (UO && UO->getOpcode() == UO_Deref &&
532       UO->getSubExpr()->getType()->isPointerType()) {
533     const LangAS AS =
534         UO->getSubExpr()->getType()->getPointeeType().getAddressSpace();
535     if ((!isTargetAddressSpace(AS) ||
536          (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) &&
537         UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant(
538             S.Context, Expr::NPC_ValueDependentIsNotNull) &&
539         !UO->getType().isVolatileQualified()) {
540       S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
541                             S.PDiag(diag::warn_indirection_through_null)
542                                 << UO->getSubExpr()->getSourceRange());
543       S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
544                             S.PDiag(diag::note_indirection_through_null));
545     }
546   }
547 }
548 
549 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
550                                     SourceLocation AssignLoc,
551                                     const Expr* RHS) {
552   const ObjCIvarDecl *IV = OIRE->getDecl();
553   if (!IV)
554     return;
555 
556   DeclarationName MemberName = IV->getDeclName();
557   IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
558   if (!Member || !Member->isStr("isa"))
559     return;
560 
561   const Expr *Base = OIRE->getBase();
562   QualType BaseType = Base->getType();
563   if (OIRE->isArrow())
564     BaseType = BaseType->getPointeeType();
565   if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
566     if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
567       ObjCInterfaceDecl *ClassDeclared = nullptr;
568       ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
569       if (!ClassDeclared->getSuperClass()
570           && (*ClassDeclared->ivar_begin()) == IV) {
571         if (RHS) {
572           NamedDecl *ObjectSetClass =
573             S.LookupSingleName(S.TUScope,
574                                &S.Context.Idents.get("object_setClass"),
575                                SourceLocation(), S.LookupOrdinaryName);
576           if (ObjectSetClass) {
577             SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc());
578             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign)
579                 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
580                                               "object_setClass(")
581                 << FixItHint::CreateReplacement(
582                        SourceRange(OIRE->getOpLoc(), AssignLoc), ",")
583                 << FixItHint::CreateInsertion(RHSLocEnd, ")");
584           }
585           else
586             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
587         } else {
588           NamedDecl *ObjectGetClass =
589             S.LookupSingleName(S.TUScope,
590                                &S.Context.Idents.get("object_getClass"),
591                                SourceLocation(), S.LookupOrdinaryName);
592           if (ObjectGetClass)
593             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use)
594                 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
595                                               "object_getClass(")
596                 << FixItHint::CreateReplacement(
597                        SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")");
598           else
599             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
600         }
601         S.Diag(IV->getLocation(), diag::note_ivar_decl);
602       }
603     }
604 }
605 
606 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
607   // Handle any placeholder expressions which made it here.
608   if (E->getType()->isPlaceholderType()) {
609     ExprResult result = CheckPlaceholderExpr(E);
610     if (result.isInvalid()) return ExprError();
611     E = result.get();
612   }
613 
614   // C++ [conv.lval]p1:
615   //   A glvalue of a non-function, non-array type T can be
616   //   converted to a prvalue.
617   if (!E->isGLValue()) return E;
618 
619   QualType T = E->getType();
620   assert(!T.isNull() && "r-value conversion on typeless expression?");
621 
622   // lvalue-to-rvalue conversion cannot be applied to function or array types.
623   if (T->isFunctionType() || T->isArrayType())
624     return E;
625 
626   // We don't want to throw lvalue-to-rvalue casts on top of
627   // expressions of certain types in C++.
628   if (getLangOpts().CPlusPlus &&
629       (E->getType() == Context.OverloadTy ||
630        T->isDependentType() ||
631        T->isRecordType()))
632     return E;
633 
634   // The C standard is actually really unclear on this point, and
635   // DR106 tells us what the result should be but not why.  It's
636   // generally best to say that void types just doesn't undergo
637   // lvalue-to-rvalue at all.  Note that expressions of unqualified
638   // 'void' type are never l-values, but qualified void can be.
639   if (T->isVoidType())
640     return E;
641 
642   // OpenCL usually rejects direct accesses to values of 'half' type.
643   if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
644       T->isHalfType()) {
645     Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
646       << 0 << T;
647     return ExprError();
648   }
649 
650   CheckForNullPointerDereference(*this, E);
651   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
652     NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
653                                      &Context.Idents.get("object_getClass"),
654                                      SourceLocation(), LookupOrdinaryName);
655     if (ObjectGetClass)
656       Diag(E->getExprLoc(), diag::warn_objc_isa_use)
657           << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(")
658           << FixItHint::CreateReplacement(
659                  SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
660     else
661       Diag(E->getExprLoc(), diag::warn_objc_isa_use);
662   }
663   else if (const ObjCIvarRefExpr *OIRE =
664             dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
665     DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
666 
667   // C++ [conv.lval]p1:
668   //   [...] If T is a non-class type, the type of the prvalue is the
669   //   cv-unqualified version of T. Otherwise, the type of the
670   //   rvalue is T.
671   //
672   // C99 6.3.2.1p2:
673   //   If the lvalue has qualified type, the value has the unqualified
674   //   version of the type of the lvalue; otherwise, the value has the
675   //   type of the lvalue.
676   if (T.hasQualifiers())
677     T = T.getUnqualifiedType();
678 
679   // Under the MS ABI, lock down the inheritance model now.
680   if (T->isMemberPointerType() &&
681       Context.getTargetInfo().getCXXABI().isMicrosoft())
682     (void)isCompleteType(E->getExprLoc(), T);
683 
684   ExprResult Res = CheckLValueToRValueConversionOperand(E);
685   if (Res.isInvalid())
686     return Res;
687   E = Res.get();
688 
689   // Loading a __weak object implicitly retains the value, so we need a cleanup to
690   // balance that.
691   if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
692     Cleanup.setExprNeedsCleanups(true);
693 
694   if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
695     Cleanup.setExprNeedsCleanups(true);
696 
697   // C++ [conv.lval]p3:
698   //   If T is cv std::nullptr_t, the result is a null pointer constant.
699   CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue;
700   Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_RValue);
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);
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   E = ExprRes.get();
968 
969   // Diagnostics regarding non-POD argument types are
970   // emitted along with format string checking in Sema::CheckFunctionCall().
971   if (isValidVarArgType(E->getType()) == VAK_Undefined) {
972     // Turn this into a trap.
973     CXXScopeSpec SS;
974     SourceLocation TemplateKWLoc;
975     UnqualifiedId Name;
976     Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
977                        E->getBeginLoc());
978     ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name,
979                                           /*HasTrailingLParen=*/true,
980                                           /*IsAddressOfOperand=*/false);
981     if (TrapFn.isInvalid())
982       return ExprError();
983 
984     ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(),
985                                     None, E->getEndLoc());
986     if (Call.isInvalid())
987       return ExprError();
988 
989     ExprResult Comma =
990         ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E);
991     if (Comma.isInvalid())
992       return ExprError();
993     return Comma.get();
994   }
995 
996   if (!getLangOpts().CPlusPlus &&
997       RequireCompleteType(E->getExprLoc(), E->getType(),
998                           diag::err_call_incomplete_argument))
999     return ExprError();
1000 
1001   return E;
1002 }
1003 
1004 /// Converts an integer to complex float type.  Helper function of
1005 /// UsualArithmeticConversions()
1006 ///
1007 /// \return false if the integer expression is an integer type and is
1008 /// successfully converted to the complex type.
1009 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
1010                                                   ExprResult &ComplexExpr,
1011                                                   QualType IntTy,
1012                                                   QualType ComplexTy,
1013                                                   bool SkipCast) {
1014   if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
1015   if (SkipCast) return false;
1016   if (IntTy->isIntegerType()) {
1017     QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
1018     IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
1019     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1020                                   CK_FloatingRealToComplex);
1021   } else {
1022     assert(IntTy->isComplexIntegerType());
1023     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1024                                   CK_IntegralComplexToFloatingComplex);
1025   }
1026   return false;
1027 }
1028 
1029 /// Handle arithmetic conversion with complex types.  Helper function of
1030 /// UsualArithmeticConversions()
1031 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
1032                                              ExprResult &RHS, QualType LHSType,
1033                                              QualType RHSType,
1034                                              bool IsCompAssign) {
1035   // if we have an integer operand, the result is the complex type.
1036   if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
1037                                              /*skipCast*/false))
1038     return LHSType;
1039   if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
1040                                              /*skipCast*/IsCompAssign))
1041     return RHSType;
1042 
1043   // This handles complex/complex, complex/float, or float/complex.
1044   // When both operands are complex, the shorter operand is converted to the
1045   // type of the longer, and that is the type of the result. This corresponds
1046   // to what is done when combining two real floating-point operands.
1047   // The fun begins when size promotion occur across type domains.
1048   // From H&S 6.3.4: When one operand is complex and the other is a real
1049   // floating-point type, the less precise type is converted, within it's
1050   // real or complex domain, to the precision of the other type. For example,
1051   // when combining a "long double" with a "double _Complex", the
1052   // "double _Complex" is promoted to "long double _Complex".
1053 
1054   // Compute the rank of the two types, regardless of whether they are complex.
1055   int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1056 
1057   auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
1058   auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
1059   QualType LHSElementType =
1060       LHSComplexType ? LHSComplexType->getElementType() : LHSType;
1061   QualType RHSElementType =
1062       RHSComplexType ? RHSComplexType->getElementType() : RHSType;
1063 
1064   QualType ResultType = S.Context.getComplexType(LHSElementType);
1065   if (Order < 0) {
1066     // Promote the precision of the LHS if not an assignment.
1067     ResultType = S.Context.getComplexType(RHSElementType);
1068     if (!IsCompAssign) {
1069       if (LHSComplexType)
1070         LHS =
1071             S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
1072       else
1073         LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
1074     }
1075   } else if (Order > 0) {
1076     // Promote the precision of the RHS.
1077     if (RHSComplexType)
1078       RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
1079     else
1080       RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
1081   }
1082   return ResultType;
1083 }
1084 
1085 /// Handle arithmetic conversion from integer to float.  Helper function
1086 /// of UsualArithmeticConversions()
1087 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1088                                            ExprResult &IntExpr,
1089                                            QualType FloatTy, QualType IntTy,
1090                                            bool ConvertFloat, bool ConvertInt) {
1091   if (IntTy->isIntegerType()) {
1092     if (ConvertInt)
1093       // Convert intExpr to the lhs floating point type.
1094       IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1095                                     CK_IntegralToFloating);
1096     return FloatTy;
1097   }
1098 
1099   // Convert both sides to the appropriate complex float.
1100   assert(IntTy->isComplexIntegerType());
1101   QualType result = S.Context.getComplexType(FloatTy);
1102 
1103   // _Complex int -> _Complex float
1104   if (ConvertInt)
1105     IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1106                                   CK_IntegralComplexToFloatingComplex);
1107 
1108   // float -> _Complex float
1109   if (ConvertFloat)
1110     FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1111                                     CK_FloatingRealToComplex);
1112 
1113   return result;
1114 }
1115 
1116 /// Handle arithmethic conversion with floating point types.  Helper
1117 /// function of UsualArithmeticConversions()
1118 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1119                                       ExprResult &RHS, QualType LHSType,
1120                                       QualType RHSType, bool IsCompAssign) {
1121   bool LHSFloat = LHSType->isRealFloatingType();
1122   bool RHSFloat = RHSType->isRealFloatingType();
1123 
1124   // If we have two real floating types, convert the smaller operand
1125   // to the bigger result.
1126   if (LHSFloat && RHSFloat) {
1127     int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1128     if (order > 0) {
1129       RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1130       return LHSType;
1131     }
1132 
1133     assert(order < 0 && "illegal float comparison");
1134     if (!IsCompAssign)
1135       LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1136     return RHSType;
1137   }
1138 
1139   if (LHSFloat) {
1140     // Half FP has to be promoted to float unless it is natively supported
1141     if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1142       LHSType = S.Context.FloatTy;
1143 
1144     return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1145                                       /*ConvertFloat=*/!IsCompAssign,
1146                                       /*ConvertInt=*/ true);
1147   }
1148   assert(RHSFloat);
1149   return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1150                                     /*convertInt=*/ true,
1151                                     /*convertFloat=*/!IsCompAssign);
1152 }
1153 
1154 /// Diagnose attempts to convert between __float128 and long double if
1155 /// there is no support for such conversion. Helper function of
1156 /// UsualArithmeticConversions().
1157 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1158                                       QualType RHSType) {
1159   /*  No issue converting if at least one of the types is not a floating point
1160       type or the two types have the same rank.
1161   */
1162   if (!LHSType->isFloatingType() || !RHSType->isFloatingType() ||
1163       S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0)
1164     return false;
1165 
1166   assert(LHSType->isFloatingType() && RHSType->isFloatingType() &&
1167          "The remaining types must be floating point types.");
1168 
1169   auto *LHSComplex = LHSType->getAs<ComplexType>();
1170   auto *RHSComplex = RHSType->getAs<ComplexType>();
1171 
1172   QualType LHSElemType = LHSComplex ?
1173     LHSComplex->getElementType() : LHSType;
1174   QualType RHSElemType = RHSComplex ?
1175     RHSComplex->getElementType() : RHSType;
1176 
1177   // No issue if the two types have the same representation
1178   if (&S.Context.getFloatTypeSemantics(LHSElemType) ==
1179       &S.Context.getFloatTypeSemantics(RHSElemType))
1180     return false;
1181 
1182   bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty &&
1183                                 RHSElemType == S.Context.LongDoubleTy);
1184   Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy &&
1185                             RHSElemType == S.Context.Float128Ty);
1186 
1187   // We've handled the situation where __float128 and long double have the same
1188   // representation. We allow all conversions for all possible long double types
1189   // except PPC's double double.
1190   return Float128AndLongDouble &&
1191     (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) ==
1192      &llvm::APFloat::PPCDoubleDouble());
1193 }
1194 
1195 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1196 
1197 namespace {
1198 /// These helper callbacks are placed in an anonymous namespace to
1199 /// permit their use as function template parameters.
1200 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1201   return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1202 }
1203 
1204 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1205   return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1206                              CK_IntegralComplexCast);
1207 }
1208 }
1209 
1210 /// Handle integer arithmetic conversions.  Helper function of
1211 /// UsualArithmeticConversions()
1212 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1213 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1214                                         ExprResult &RHS, QualType LHSType,
1215                                         QualType RHSType, bool IsCompAssign) {
1216   // The rules for this case are in C99 6.3.1.8
1217   int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1218   bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1219   bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1220   if (LHSSigned == RHSSigned) {
1221     // Same signedness; use the higher-ranked type
1222     if (order >= 0) {
1223       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1224       return LHSType;
1225     } else if (!IsCompAssign)
1226       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1227     return RHSType;
1228   } else if (order != (LHSSigned ? 1 : -1)) {
1229     // The unsigned type has greater than or equal rank to the
1230     // signed type, so use the unsigned type
1231     if (RHSSigned) {
1232       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1233       return LHSType;
1234     } else if (!IsCompAssign)
1235       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1236     return RHSType;
1237   } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1238     // The two types are different widths; if we are here, that
1239     // means the signed type is larger than the unsigned type, so
1240     // use the signed type.
1241     if (LHSSigned) {
1242       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1243       return LHSType;
1244     } else if (!IsCompAssign)
1245       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1246     return RHSType;
1247   } else {
1248     // The signed type is higher-ranked than the unsigned type,
1249     // but isn't actually any bigger (like unsigned int and long
1250     // on most 32-bit systems).  Use the unsigned type corresponding
1251     // to the signed type.
1252     QualType result =
1253       S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1254     RHS = (*doRHSCast)(S, RHS.get(), result);
1255     if (!IsCompAssign)
1256       LHS = (*doLHSCast)(S, LHS.get(), result);
1257     return result;
1258   }
1259 }
1260 
1261 /// Handle conversions with GCC complex int extension.  Helper function
1262 /// of UsualArithmeticConversions()
1263 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1264                                            ExprResult &RHS, QualType LHSType,
1265                                            QualType RHSType,
1266                                            bool IsCompAssign) {
1267   const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1268   const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1269 
1270   if (LHSComplexInt && RHSComplexInt) {
1271     QualType LHSEltType = LHSComplexInt->getElementType();
1272     QualType RHSEltType = RHSComplexInt->getElementType();
1273     QualType ScalarType =
1274       handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1275         (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1276 
1277     return S.Context.getComplexType(ScalarType);
1278   }
1279 
1280   if (LHSComplexInt) {
1281     QualType LHSEltType = LHSComplexInt->getElementType();
1282     QualType ScalarType =
1283       handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1284         (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1285     QualType ComplexType = S.Context.getComplexType(ScalarType);
1286     RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1287                               CK_IntegralRealToComplex);
1288 
1289     return ComplexType;
1290   }
1291 
1292   assert(RHSComplexInt);
1293 
1294   QualType RHSEltType = RHSComplexInt->getElementType();
1295   QualType ScalarType =
1296     handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1297       (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1298   QualType ComplexType = S.Context.getComplexType(ScalarType);
1299 
1300   if (!IsCompAssign)
1301     LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1302                               CK_IntegralRealToComplex);
1303   return ComplexType;
1304 }
1305 
1306 /// Return the rank of a given fixed point or integer type. The value itself
1307 /// doesn't matter, but the values must be increasing with proper increasing
1308 /// rank as described in N1169 4.1.1.
1309 static unsigned GetFixedPointRank(QualType Ty) {
1310   const auto *BTy = Ty->getAs<BuiltinType>();
1311   assert(BTy && "Expected a builtin type.");
1312 
1313   switch (BTy->getKind()) {
1314   case BuiltinType::ShortFract:
1315   case BuiltinType::UShortFract:
1316   case BuiltinType::SatShortFract:
1317   case BuiltinType::SatUShortFract:
1318     return 1;
1319   case BuiltinType::Fract:
1320   case BuiltinType::UFract:
1321   case BuiltinType::SatFract:
1322   case BuiltinType::SatUFract:
1323     return 2;
1324   case BuiltinType::LongFract:
1325   case BuiltinType::ULongFract:
1326   case BuiltinType::SatLongFract:
1327   case BuiltinType::SatULongFract:
1328     return 3;
1329   case BuiltinType::ShortAccum:
1330   case BuiltinType::UShortAccum:
1331   case BuiltinType::SatShortAccum:
1332   case BuiltinType::SatUShortAccum:
1333     return 4;
1334   case BuiltinType::Accum:
1335   case BuiltinType::UAccum:
1336   case BuiltinType::SatAccum:
1337   case BuiltinType::SatUAccum:
1338     return 5;
1339   case BuiltinType::LongAccum:
1340   case BuiltinType::ULongAccum:
1341   case BuiltinType::SatLongAccum:
1342   case BuiltinType::SatULongAccum:
1343     return 6;
1344   default:
1345     if (BTy->isInteger())
1346       return 0;
1347     llvm_unreachable("Unexpected fixed point or integer type");
1348   }
1349 }
1350 
1351 /// handleFixedPointConversion - Fixed point operations between fixed
1352 /// point types and integers or other fixed point types do not fall under
1353 /// usual arithmetic conversion since these conversions could result in loss
1354 /// of precsision (N1169 4.1.4). These operations should be calculated with
1355 /// the full precision of their result type (N1169 4.1.6.2.1).
1356 static QualType handleFixedPointConversion(Sema &S, QualType LHSTy,
1357                                            QualType RHSTy) {
1358   assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) &&
1359          "Expected at least one of the operands to be a fixed point type");
1360   assert((LHSTy->isFixedPointOrIntegerType() ||
1361           RHSTy->isFixedPointOrIntegerType()) &&
1362          "Special fixed point arithmetic operation conversions are only "
1363          "applied to ints or other fixed point types");
1364 
1365   // If one operand has signed fixed-point type and the other operand has
1366   // unsigned fixed-point type, then the unsigned fixed-point operand is
1367   // converted to its corresponding signed fixed-point type and the resulting
1368   // type is the type of the converted operand.
1369   if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType())
1370     LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy);
1371   else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType())
1372     RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy);
1373 
1374   // The result type is the type with the highest rank, whereby a fixed-point
1375   // conversion rank is always greater than an integer conversion rank; if the
1376   // type of either of the operands is a saturating fixedpoint type, the result
1377   // type shall be the saturating fixed-point type corresponding to the type
1378   // with the highest rank; the resulting value is converted (taking into
1379   // account rounding and overflow) to the precision of the resulting type.
1380   // Same ranks between signed and unsigned types are resolved earlier, so both
1381   // types are either signed or both unsigned at this point.
1382   unsigned LHSTyRank = GetFixedPointRank(LHSTy);
1383   unsigned RHSTyRank = GetFixedPointRank(RHSTy);
1384 
1385   QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy;
1386 
1387   if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType())
1388     ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy);
1389 
1390   return ResultTy;
1391 }
1392 
1393 /// Check that the usual arithmetic conversions can be performed on this pair of
1394 /// expressions that might be of enumeration type.
1395 static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS,
1396                                            SourceLocation Loc,
1397                                            Sema::ArithConvKind ACK) {
1398   // C++2a [expr.arith.conv]p1:
1399   //   If one operand is of enumeration type and the other operand is of a
1400   //   different enumeration type or a floating-point type, this behavior is
1401   //   deprecated ([depr.arith.conv.enum]).
1402   //
1403   // Warn on this in all language modes. Produce a deprecation warning in C++20.
1404   // Eventually we will presumably reject these cases (in C++23 onwards?).
1405   QualType L = LHS->getType(), R = RHS->getType();
1406   bool LEnum = L->isUnscopedEnumerationType(),
1407        REnum = R->isUnscopedEnumerationType();
1408   bool IsCompAssign = ACK == Sema::ACK_CompAssign;
1409   if ((!IsCompAssign && LEnum && R->isFloatingType()) ||
1410       (REnum && L->isFloatingType())) {
1411     S.Diag(Loc, S.getLangOpts().CPlusPlus20
1412                     ? diag::warn_arith_conv_enum_float_cxx20
1413                     : diag::warn_arith_conv_enum_float)
1414         << LHS->getSourceRange() << RHS->getSourceRange()
1415         << (int)ACK << LEnum << L << R;
1416   } else if (!IsCompAssign && LEnum && REnum &&
1417              !S.Context.hasSameUnqualifiedType(L, R)) {
1418     unsigned DiagID;
1419     if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() ||
1420         !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) {
1421       // If either enumeration type is unnamed, it's less likely that the
1422       // user cares about this, but this situation is still deprecated in
1423       // C++2a. Use a different warning group.
1424       DiagID = S.getLangOpts().CPlusPlus20
1425                     ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20
1426                     : diag::warn_arith_conv_mixed_anon_enum_types;
1427     } else if (ACK == Sema::ACK_Conditional) {
1428       // Conditional expressions are separated out because they have
1429       // historically had a different warning flag.
1430       DiagID = S.getLangOpts().CPlusPlus20
1431                    ? diag::warn_conditional_mixed_enum_types_cxx20
1432                    : diag::warn_conditional_mixed_enum_types;
1433     } else if (ACK == Sema::ACK_Comparison) {
1434       // Comparison expressions are separated out because they have
1435       // historically had a different warning flag.
1436       DiagID = S.getLangOpts().CPlusPlus20
1437                    ? diag::warn_comparison_mixed_enum_types_cxx20
1438                    : diag::warn_comparison_mixed_enum_types;
1439     } else {
1440       DiagID = S.getLangOpts().CPlusPlus20
1441                    ? diag::warn_arith_conv_mixed_enum_types_cxx20
1442                    : diag::warn_arith_conv_mixed_enum_types;
1443     }
1444     S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
1445                         << (int)ACK << L << R;
1446   }
1447 }
1448 
1449 /// UsualArithmeticConversions - Performs various conversions that are common to
1450 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1451 /// routine returns the first non-arithmetic type found. The client is
1452 /// responsible for emitting appropriate error diagnostics.
1453 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1454                                           SourceLocation Loc,
1455                                           ArithConvKind ACK) {
1456   checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK);
1457 
1458   if (ACK != ACK_CompAssign) {
1459     LHS = UsualUnaryConversions(LHS.get());
1460     if (LHS.isInvalid())
1461       return QualType();
1462   }
1463 
1464   RHS = UsualUnaryConversions(RHS.get());
1465   if (RHS.isInvalid())
1466     return QualType();
1467 
1468   // For conversion purposes, we ignore any qualifiers.
1469   // For example, "const float" and "float" are equivalent.
1470   QualType LHSType =
1471     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1472   QualType RHSType =
1473     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1474 
1475   // For conversion purposes, we ignore any atomic qualifier on the LHS.
1476   if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1477     LHSType = AtomicLHS->getValueType();
1478 
1479   // If both types are identical, no conversion is needed.
1480   if (LHSType == RHSType)
1481     return LHSType;
1482 
1483   // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1484   // The caller can deal with this (e.g. pointer + int).
1485   if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1486     return QualType();
1487 
1488   // Apply unary and bitfield promotions to the LHS's type.
1489   QualType LHSUnpromotedType = LHSType;
1490   if (LHSType->isPromotableIntegerType())
1491     LHSType = Context.getPromotedIntegerType(LHSType);
1492   QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1493   if (!LHSBitfieldPromoteTy.isNull())
1494     LHSType = LHSBitfieldPromoteTy;
1495   if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign)
1496     LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1497 
1498   // If both types are identical, no conversion is needed.
1499   if (LHSType == RHSType)
1500     return LHSType;
1501 
1502   // ExtInt types aren't subject to conversions between them or normal integers,
1503   // so this fails.
1504   if(LHSType->isExtIntType() || RHSType->isExtIntType())
1505     return QualType();
1506 
1507   // At this point, we have two different arithmetic types.
1508 
1509   // Diagnose attempts to convert between __float128 and long double where
1510   // such conversions currently can't be handled.
1511   if (unsupportedTypeConversion(*this, LHSType, RHSType))
1512     return QualType();
1513 
1514   // Handle complex types first (C99 6.3.1.8p1).
1515   if (LHSType->isComplexType() || RHSType->isComplexType())
1516     return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1517                                         ACK == ACK_CompAssign);
1518 
1519   // Now handle "real" floating types (i.e. float, double, long double).
1520   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1521     return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1522                                  ACK == ACK_CompAssign);
1523 
1524   // Handle GCC complex int extension.
1525   if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1526     return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1527                                       ACK == ACK_CompAssign);
1528 
1529   if (LHSType->isFixedPointType() || RHSType->isFixedPointType())
1530     return handleFixedPointConversion(*this, LHSType, RHSType);
1531 
1532   // Finally, we have two differing integer types.
1533   return handleIntegerConversion<doIntegralCast, doIntegralCast>
1534            (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign);
1535 }
1536 
1537 //===----------------------------------------------------------------------===//
1538 //  Semantic Analysis for various Expression Types
1539 //===----------------------------------------------------------------------===//
1540 
1541 
1542 ExprResult
1543 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1544                                 SourceLocation DefaultLoc,
1545                                 SourceLocation RParenLoc,
1546                                 Expr *ControllingExpr,
1547                                 ArrayRef<ParsedType> ArgTypes,
1548                                 ArrayRef<Expr *> ArgExprs) {
1549   unsigned NumAssocs = ArgTypes.size();
1550   assert(NumAssocs == ArgExprs.size());
1551 
1552   TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1553   for (unsigned i = 0; i < NumAssocs; ++i) {
1554     if (ArgTypes[i])
1555       (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1556     else
1557       Types[i] = nullptr;
1558   }
1559 
1560   ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1561                                              ControllingExpr,
1562                                              llvm::makeArrayRef(Types, NumAssocs),
1563                                              ArgExprs);
1564   delete [] Types;
1565   return ER;
1566 }
1567 
1568 ExprResult
1569 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1570                                  SourceLocation DefaultLoc,
1571                                  SourceLocation RParenLoc,
1572                                  Expr *ControllingExpr,
1573                                  ArrayRef<TypeSourceInfo *> Types,
1574                                  ArrayRef<Expr *> Exprs) {
1575   unsigned NumAssocs = Types.size();
1576   assert(NumAssocs == Exprs.size());
1577 
1578   // Decay and strip qualifiers for the controlling expression type, and handle
1579   // placeholder type replacement. See committee discussion from WG14 DR423.
1580   {
1581     EnterExpressionEvaluationContext Unevaluated(
1582         *this, Sema::ExpressionEvaluationContext::Unevaluated);
1583     ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
1584     if (R.isInvalid())
1585       return ExprError();
1586     ControllingExpr = R.get();
1587   }
1588 
1589   // The controlling expression is an unevaluated operand, so side effects are
1590   // likely unintended.
1591   if (!inTemplateInstantiation() &&
1592       ControllingExpr->HasSideEffects(Context, false))
1593     Diag(ControllingExpr->getExprLoc(),
1594          diag::warn_side_effects_unevaluated_context);
1595 
1596   bool TypeErrorFound = false,
1597        IsResultDependent = ControllingExpr->isTypeDependent(),
1598        ContainsUnexpandedParameterPack
1599          = ControllingExpr->containsUnexpandedParameterPack();
1600 
1601   for (unsigned i = 0; i < NumAssocs; ++i) {
1602     if (Exprs[i]->containsUnexpandedParameterPack())
1603       ContainsUnexpandedParameterPack = true;
1604 
1605     if (Types[i]) {
1606       if (Types[i]->getType()->containsUnexpandedParameterPack())
1607         ContainsUnexpandedParameterPack = true;
1608 
1609       if (Types[i]->getType()->isDependentType()) {
1610         IsResultDependent = true;
1611       } else {
1612         // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1613         // complete object type other than a variably modified type."
1614         unsigned D = 0;
1615         if (Types[i]->getType()->isIncompleteType())
1616           D = diag::err_assoc_type_incomplete;
1617         else if (!Types[i]->getType()->isObjectType())
1618           D = diag::err_assoc_type_nonobject;
1619         else if (Types[i]->getType()->isVariablyModifiedType())
1620           D = diag::err_assoc_type_variably_modified;
1621 
1622         if (D != 0) {
1623           Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1624             << Types[i]->getTypeLoc().getSourceRange()
1625             << Types[i]->getType();
1626           TypeErrorFound = true;
1627         }
1628 
1629         // C11 6.5.1.1p2 "No two generic associations in the same generic
1630         // selection shall specify compatible types."
1631         for (unsigned j = i+1; j < NumAssocs; ++j)
1632           if (Types[j] && !Types[j]->getType()->isDependentType() &&
1633               Context.typesAreCompatible(Types[i]->getType(),
1634                                          Types[j]->getType())) {
1635             Diag(Types[j]->getTypeLoc().getBeginLoc(),
1636                  diag::err_assoc_compatible_types)
1637               << Types[j]->getTypeLoc().getSourceRange()
1638               << Types[j]->getType()
1639               << Types[i]->getType();
1640             Diag(Types[i]->getTypeLoc().getBeginLoc(),
1641                  diag::note_compat_assoc)
1642               << Types[i]->getTypeLoc().getSourceRange()
1643               << Types[i]->getType();
1644             TypeErrorFound = true;
1645           }
1646       }
1647     }
1648   }
1649   if (TypeErrorFound)
1650     return ExprError();
1651 
1652   // If we determined that the generic selection is result-dependent, don't
1653   // try to compute the result expression.
1654   if (IsResultDependent)
1655     return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types,
1656                                         Exprs, DefaultLoc, RParenLoc,
1657                                         ContainsUnexpandedParameterPack);
1658 
1659   SmallVector<unsigned, 1> CompatIndices;
1660   unsigned DefaultIndex = -1U;
1661   for (unsigned i = 0; i < NumAssocs; ++i) {
1662     if (!Types[i])
1663       DefaultIndex = i;
1664     else if (Context.typesAreCompatible(ControllingExpr->getType(),
1665                                         Types[i]->getType()))
1666       CompatIndices.push_back(i);
1667   }
1668 
1669   // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1670   // type compatible with at most one of the types named in its generic
1671   // association list."
1672   if (CompatIndices.size() > 1) {
1673     // We strip parens here because the controlling expression is typically
1674     // parenthesized in macro definitions.
1675     ControllingExpr = ControllingExpr->IgnoreParens();
1676     Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match)
1677         << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1678         << (unsigned)CompatIndices.size();
1679     for (unsigned I : CompatIndices) {
1680       Diag(Types[I]->getTypeLoc().getBeginLoc(),
1681            diag::note_compat_assoc)
1682         << Types[I]->getTypeLoc().getSourceRange()
1683         << Types[I]->getType();
1684     }
1685     return ExprError();
1686   }
1687 
1688   // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1689   // its controlling expression shall have type compatible with exactly one of
1690   // the types named in its generic association list."
1691   if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1692     // We strip parens here because the controlling expression is typically
1693     // parenthesized in macro definitions.
1694     ControllingExpr = ControllingExpr->IgnoreParens();
1695     Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match)
1696         << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1697     return ExprError();
1698   }
1699 
1700   // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1701   // type name that is compatible with the type of the controlling expression,
1702   // then the result expression of the generic selection is the expression
1703   // in that generic association. Otherwise, the result expression of the
1704   // generic selection is the expression in the default generic association."
1705   unsigned ResultIndex =
1706     CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1707 
1708   return GenericSelectionExpr::Create(
1709       Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1710       ContainsUnexpandedParameterPack, ResultIndex);
1711 }
1712 
1713 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1714 /// location of the token and the offset of the ud-suffix within it.
1715 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1716                                      unsigned Offset) {
1717   return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1718                                         S.getLangOpts());
1719 }
1720 
1721 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1722 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
1723 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1724                                                  IdentifierInfo *UDSuffix,
1725                                                  SourceLocation UDSuffixLoc,
1726                                                  ArrayRef<Expr*> Args,
1727                                                  SourceLocation LitEndLoc) {
1728   assert(Args.size() <= 2 && "too many arguments for literal operator");
1729 
1730   QualType ArgTy[2];
1731   for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1732     ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1733     if (ArgTy[ArgIdx]->isArrayType())
1734       ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1735   }
1736 
1737   DeclarationName OpName =
1738     S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1739   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1740   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1741 
1742   LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1743   if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1744                               /*AllowRaw*/ false, /*AllowTemplate*/ false,
1745                               /*AllowStringTemplate*/ false,
1746                               /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
1747     return ExprError();
1748 
1749   return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1750 }
1751 
1752 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1753 /// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
1754 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1755 /// multiple tokens.  However, the common case is that StringToks points to one
1756 /// string.
1757 ///
1758 ExprResult
1759 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
1760   assert(!StringToks.empty() && "Must have at least one string!");
1761 
1762   StringLiteralParser Literal(StringToks, PP);
1763   if (Literal.hadError)
1764     return ExprError();
1765 
1766   SmallVector<SourceLocation, 4> StringTokLocs;
1767   for (const Token &Tok : StringToks)
1768     StringTokLocs.push_back(Tok.getLocation());
1769 
1770   QualType CharTy = Context.CharTy;
1771   StringLiteral::StringKind Kind = StringLiteral::Ascii;
1772   if (Literal.isWide()) {
1773     CharTy = Context.getWideCharType();
1774     Kind = StringLiteral::Wide;
1775   } else if (Literal.isUTF8()) {
1776     if (getLangOpts().Char8)
1777       CharTy = Context.Char8Ty;
1778     Kind = StringLiteral::UTF8;
1779   } else if (Literal.isUTF16()) {
1780     CharTy = Context.Char16Ty;
1781     Kind = StringLiteral::UTF16;
1782   } else if (Literal.isUTF32()) {
1783     CharTy = Context.Char32Ty;
1784     Kind = StringLiteral::UTF32;
1785   } else if (Literal.isPascal()) {
1786     CharTy = Context.UnsignedCharTy;
1787   }
1788 
1789   // Warn on initializing an array of char from a u8 string literal; this
1790   // becomes ill-formed in C++2a.
1791   if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus20 &&
1792       !getLangOpts().Char8 && Kind == StringLiteral::UTF8) {
1793     Diag(StringTokLocs.front(), diag::warn_cxx20_compat_utf8_string);
1794 
1795     // Create removals for all 'u8' prefixes in the string literal(s). This
1796     // ensures C++2a compatibility (but may change the program behavior when
1797     // built by non-Clang compilers for which the execution character set is
1798     // not always UTF-8).
1799     auto RemovalDiag = PDiag(diag::note_cxx20_compat_utf8_string_remove_u8);
1800     SourceLocation RemovalDiagLoc;
1801     for (const Token &Tok : StringToks) {
1802       if (Tok.getKind() == tok::utf8_string_literal) {
1803         if (RemovalDiagLoc.isInvalid())
1804           RemovalDiagLoc = Tok.getLocation();
1805         RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange(
1806             Tok.getLocation(),
1807             Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2,
1808                                            getSourceManager(), getLangOpts())));
1809       }
1810     }
1811     Diag(RemovalDiagLoc, RemovalDiag);
1812   }
1813 
1814   QualType StrTy =
1815       Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars());
1816 
1817   // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1818   StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1819                                              Kind, Literal.Pascal, StrTy,
1820                                              &StringTokLocs[0],
1821                                              StringTokLocs.size());
1822   if (Literal.getUDSuffix().empty())
1823     return Lit;
1824 
1825   // We're building a user-defined literal.
1826   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1827   SourceLocation UDSuffixLoc =
1828     getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1829                    Literal.getUDSuffixOffset());
1830 
1831   // Make sure we're allowed user-defined literals here.
1832   if (!UDLScope)
1833     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1834 
1835   // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1836   //   operator "" X (str, len)
1837   QualType SizeType = Context.getSizeType();
1838 
1839   DeclarationName OpName =
1840     Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1841   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1842   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1843 
1844   QualType ArgTy[] = {
1845     Context.getArrayDecayedType(StrTy), SizeType
1846   };
1847 
1848   LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1849   switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1850                                 /*AllowRaw*/ false, /*AllowTemplate*/ false,
1851                                 /*AllowStringTemplate*/ true,
1852                                 /*DiagnoseMissing*/ true)) {
1853 
1854   case LOLR_Cooked: {
1855     llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1856     IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1857                                                     StringTokLocs[0]);
1858     Expr *Args[] = { Lit, LenArg };
1859 
1860     return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1861   }
1862 
1863   case LOLR_StringTemplate: {
1864     TemplateArgumentListInfo ExplicitArgs;
1865 
1866     unsigned CharBits = Context.getIntWidth(CharTy);
1867     bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1868     llvm::APSInt Value(CharBits, CharIsUnsigned);
1869 
1870     TemplateArgument TypeArg(CharTy);
1871     TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1872     ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1873 
1874     for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1875       Value = Lit->getCodeUnit(I);
1876       TemplateArgument Arg(Context, Value, CharTy);
1877       TemplateArgumentLocInfo ArgInfo;
1878       ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1879     }
1880     return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1881                                     &ExplicitArgs);
1882   }
1883   case LOLR_Raw:
1884   case LOLR_Template:
1885   case LOLR_ErrorNoDiagnostic:
1886     llvm_unreachable("unexpected literal operator lookup result");
1887   case LOLR_Error:
1888     return ExprError();
1889   }
1890   llvm_unreachable("unexpected literal operator lookup result");
1891 }
1892 
1893 DeclRefExpr *
1894 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1895                        SourceLocation Loc,
1896                        const CXXScopeSpec *SS) {
1897   DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1898   return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1899 }
1900 
1901 DeclRefExpr *
1902 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1903                        const DeclarationNameInfo &NameInfo,
1904                        const CXXScopeSpec *SS, NamedDecl *FoundD,
1905                        SourceLocation TemplateKWLoc,
1906                        const TemplateArgumentListInfo *TemplateArgs) {
1907   NestedNameSpecifierLoc NNS =
1908       SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc();
1909   return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc,
1910                           TemplateArgs);
1911 }
1912 
1913 NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) {
1914   // A declaration named in an unevaluated operand never constitutes an odr-use.
1915   if (isUnevaluatedContext())
1916     return NOUR_Unevaluated;
1917 
1918   // C++2a [basic.def.odr]p4:
1919   //   A variable x whose name appears as a potentially-evaluated expression e
1920   //   is odr-used by e unless [...] x is a reference that is usable in
1921   //   constant expressions.
1922   if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
1923     if (VD->getType()->isReferenceType() &&
1924         !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) &&
1925         VD->isUsableInConstantExpressions(Context))
1926       return NOUR_Constant;
1927   }
1928 
1929   // All remaining non-variable cases constitute an odr-use. For variables, we
1930   // need to wait and see how the expression is used.
1931   return NOUR_None;
1932 }
1933 
1934 /// BuildDeclRefExpr - Build an expression that references a
1935 /// declaration that does not require a closure capture.
1936 DeclRefExpr *
1937 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1938                        const DeclarationNameInfo &NameInfo,
1939                        NestedNameSpecifierLoc NNS, NamedDecl *FoundD,
1940                        SourceLocation TemplateKWLoc,
1941                        const TemplateArgumentListInfo *TemplateArgs) {
1942   bool RefersToCapturedVariable =
1943       isa<VarDecl>(D) &&
1944       NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
1945 
1946   DeclRefExpr *E = DeclRefExpr::Create(
1947       Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty,
1948       VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D));
1949   MarkDeclRefReferenced(E);
1950 
1951   // C++ [except.spec]p17:
1952   //   An exception-specification is considered to be needed when:
1953   //   - in an expression, the function is the unique lookup result or
1954   //     the selected member of a set of overloaded functions.
1955   //
1956   // We delay doing this until after we've built the function reference and
1957   // marked it as used so that:
1958   //  a) if the function is defaulted, we get errors from defining it before /
1959   //     instead of errors from computing its exception specification, and
1960   //  b) if the function is a defaulted comparison, we can use the body we
1961   //     build when defining it as input to the exception specification
1962   //     computation rather than computing a new body.
1963   if (auto *FPT = Ty->getAs<FunctionProtoType>()) {
1964     if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
1965       if (auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT))
1966         E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers()));
1967     }
1968   }
1969 
1970   if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
1971       Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() &&
1972       !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc()))
1973     getCurFunction()->recordUseOfWeak(E);
1974 
1975   FieldDecl *FD = dyn_cast<FieldDecl>(D);
1976   if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
1977     FD = IFD->getAnonField();
1978   if (FD) {
1979     UnusedPrivateFields.remove(FD);
1980     // Just in case we're building an illegal pointer-to-member.
1981     if (FD->isBitField())
1982       E->setObjectKind(OK_BitField);
1983   }
1984 
1985   // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
1986   // designates a bit-field.
1987   if (auto *BD = dyn_cast<BindingDecl>(D))
1988     if (auto *BE = BD->getBinding())
1989       E->setObjectKind(BE->getObjectKind());
1990 
1991   return E;
1992 }
1993 
1994 /// Decomposes the given name into a DeclarationNameInfo, its location, and
1995 /// possibly a list of template arguments.
1996 ///
1997 /// If this produces template arguments, it is permitted to call
1998 /// DecomposeTemplateName.
1999 ///
2000 /// This actually loses a lot of source location information for
2001 /// non-standard name kinds; we should consider preserving that in
2002 /// some way.
2003 void
2004 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
2005                              TemplateArgumentListInfo &Buffer,
2006                              DeclarationNameInfo &NameInfo,
2007                              const TemplateArgumentListInfo *&TemplateArgs) {
2008   if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) {
2009     Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
2010     Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
2011 
2012     ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
2013                                        Id.TemplateId->NumArgs);
2014     translateTemplateArguments(TemplateArgsPtr, Buffer);
2015 
2016     TemplateName TName = Id.TemplateId->Template.get();
2017     SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
2018     NameInfo = Context.getNameForTemplate(TName, TNameLoc);
2019     TemplateArgs = &Buffer;
2020   } else {
2021     NameInfo = GetNameFromUnqualifiedId(Id);
2022     TemplateArgs = nullptr;
2023   }
2024 }
2025 
2026 static void emitEmptyLookupTypoDiagnostic(
2027     const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
2028     DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
2029     unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
2030   DeclContext *Ctx =
2031       SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
2032   if (!TC) {
2033     // Emit a special diagnostic for failed member lookups.
2034     // FIXME: computing the declaration context might fail here (?)
2035     if (Ctx)
2036       SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
2037                                                  << SS.getRange();
2038     else
2039       SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
2040     return;
2041   }
2042 
2043   std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
2044   bool DroppedSpecifier =
2045       TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
2046   unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
2047                         ? diag::note_implicit_param_decl
2048                         : diag::note_previous_decl;
2049   if (!Ctx)
2050     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
2051                          SemaRef.PDiag(NoteID));
2052   else
2053     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
2054                                  << Typo << Ctx << DroppedSpecifier
2055                                  << SS.getRange(),
2056                          SemaRef.PDiag(NoteID));
2057 }
2058 
2059 /// Diagnose an empty lookup.
2060 ///
2061 /// \return false if new lookup candidates were found
2062 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
2063                                CorrectionCandidateCallback &CCC,
2064                                TemplateArgumentListInfo *ExplicitTemplateArgs,
2065                                ArrayRef<Expr *> Args, TypoExpr **Out) {
2066   DeclarationName Name = R.getLookupName();
2067 
2068   unsigned diagnostic = diag::err_undeclared_var_use;
2069   unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
2070   if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
2071       Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
2072       Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
2073     diagnostic = diag::err_undeclared_use;
2074     diagnostic_suggest = diag::err_undeclared_use_suggest;
2075   }
2076 
2077   // If the original lookup was an unqualified lookup, fake an
2078   // unqualified lookup.  This is useful when (for example) the
2079   // original lookup would not have found something because it was a
2080   // dependent name.
2081   DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
2082   while (DC) {
2083     if (isa<CXXRecordDecl>(DC)) {
2084       LookupQualifiedName(R, DC);
2085 
2086       if (!R.empty()) {
2087         // Don't give errors about ambiguities in this lookup.
2088         R.suppressDiagnostics();
2089 
2090         // During a default argument instantiation the CurContext points
2091         // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
2092         // function parameter list, hence add an explicit check.
2093         bool isDefaultArgument =
2094             !CodeSynthesisContexts.empty() &&
2095             CodeSynthesisContexts.back().Kind ==
2096                 CodeSynthesisContext::DefaultFunctionArgumentInstantiation;
2097         CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
2098         bool isInstance = CurMethod &&
2099                           CurMethod->isInstance() &&
2100                           DC == CurMethod->getParent() && !isDefaultArgument;
2101 
2102         // Give a code modification hint to insert 'this->'.
2103         // TODO: fixit for inserting 'Base<T>::' in the other cases.
2104         // Actually quite difficult!
2105         if (getLangOpts().MSVCCompat)
2106           diagnostic = diag::ext_found_via_dependent_bases_lookup;
2107         if (isInstance) {
2108           Diag(R.getNameLoc(), diagnostic) << Name
2109             << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
2110           CheckCXXThisCapture(R.getNameLoc());
2111         } else {
2112           Diag(R.getNameLoc(), diagnostic) << Name;
2113         }
2114 
2115         // Do we really want to note all of these?
2116         for (NamedDecl *D : R)
2117           Diag(D->getLocation(), diag::note_dependent_var_use);
2118 
2119         // Return true if we are inside a default argument instantiation
2120         // and the found name refers to an instance member function, otherwise
2121         // the function calling DiagnoseEmptyLookup will try to create an
2122         // implicit member call and this is wrong for default argument.
2123         if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
2124           Diag(R.getNameLoc(), diag::err_member_call_without_object);
2125           return true;
2126         }
2127 
2128         // Tell the callee to try to recover.
2129         return false;
2130       }
2131 
2132       R.clear();
2133     }
2134 
2135     DC = DC->getLookupParent();
2136   }
2137 
2138   // We didn't find anything, so try to correct for a typo.
2139   TypoCorrection Corrected;
2140   if (S && Out) {
2141     SourceLocation TypoLoc = R.getNameLoc();
2142     assert(!ExplicitTemplateArgs &&
2143            "Diagnosing an empty lookup with explicit template args!");
2144     *Out = CorrectTypoDelayed(
2145         R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
2146         [=](const TypoCorrection &TC) {
2147           emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
2148                                         diagnostic, diagnostic_suggest);
2149         },
2150         nullptr, CTK_ErrorRecovery);
2151     if (*Out)
2152       return true;
2153   } else if (S &&
2154              (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
2155                                       S, &SS, CCC, CTK_ErrorRecovery))) {
2156     std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
2157     bool DroppedSpecifier =
2158         Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
2159     R.setLookupName(Corrected.getCorrection());
2160 
2161     bool AcceptableWithRecovery = false;
2162     bool AcceptableWithoutRecovery = false;
2163     NamedDecl *ND = Corrected.getFoundDecl();
2164     if (ND) {
2165       if (Corrected.isOverloaded()) {
2166         OverloadCandidateSet OCS(R.getNameLoc(),
2167                                  OverloadCandidateSet::CSK_Normal);
2168         OverloadCandidateSet::iterator Best;
2169         for (NamedDecl *CD : Corrected) {
2170           if (FunctionTemplateDecl *FTD =
2171                    dyn_cast<FunctionTemplateDecl>(CD))
2172             AddTemplateOverloadCandidate(
2173                 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
2174                 Args, OCS);
2175           else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
2176             if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
2177               AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
2178                                    Args, OCS);
2179         }
2180         switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
2181         case OR_Success:
2182           ND = Best->FoundDecl;
2183           Corrected.setCorrectionDecl(ND);
2184           break;
2185         default:
2186           // FIXME: Arbitrarily pick the first declaration for the note.
2187           Corrected.setCorrectionDecl(ND);
2188           break;
2189         }
2190       }
2191       R.addDecl(ND);
2192       if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2193         CXXRecordDecl *Record = nullptr;
2194         if (Corrected.getCorrectionSpecifier()) {
2195           const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
2196           Record = Ty->getAsCXXRecordDecl();
2197         }
2198         if (!Record)
2199           Record = cast<CXXRecordDecl>(
2200               ND->getDeclContext()->getRedeclContext());
2201         R.setNamingClass(Record);
2202       }
2203 
2204       auto *UnderlyingND = ND->getUnderlyingDecl();
2205       AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2206                                isa<FunctionTemplateDecl>(UnderlyingND);
2207       // FIXME: If we ended up with a typo for a type name or
2208       // Objective-C class name, we're in trouble because the parser
2209       // is in the wrong place to recover. Suggest the typo
2210       // correction, but don't make it a fix-it since we're not going
2211       // to recover well anyway.
2212       AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) ||
2213                                   getAsTypeTemplateDecl(UnderlyingND) ||
2214                                   isa<ObjCInterfaceDecl>(UnderlyingND);
2215     } else {
2216       // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2217       // because we aren't able to recover.
2218       AcceptableWithoutRecovery = true;
2219     }
2220 
2221     if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2222       unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2223                             ? diag::note_implicit_param_decl
2224                             : diag::note_previous_decl;
2225       if (SS.isEmpty())
2226         diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
2227                      PDiag(NoteID), AcceptableWithRecovery);
2228       else
2229         diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
2230                                   << Name << computeDeclContext(SS, false)
2231                                   << DroppedSpecifier << SS.getRange(),
2232                      PDiag(NoteID), AcceptableWithRecovery);
2233 
2234       // Tell the callee whether to try to recover.
2235       return !AcceptableWithRecovery;
2236     }
2237   }
2238   R.clear();
2239 
2240   // Emit a special diagnostic for failed member lookups.
2241   // FIXME: computing the declaration context might fail here (?)
2242   if (!SS.isEmpty()) {
2243     Diag(R.getNameLoc(), diag::err_no_member)
2244       << Name << computeDeclContext(SS, false)
2245       << SS.getRange();
2246     return true;
2247   }
2248 
2249   // Give up, we can't recover.
2250   Diag(R.getNameLoc(), diagnostic) << Name;
2251   return true;
2252 }
2253 
2254 /// In Microsoft mode, if we are inside a template class whose parent class has
2255 /// dependent base classes, and we can't resolve an unqualified identifier, then
2256 /// assume the identifier is a member of a dependent base class.  We can only
2257 /// recover successfully in static methods, instance methods, and other contexts
2258 /// where 'this' is available.  This doesn't precisely match MSVC's
2259 /// instantiation model, but it's close enough.
2260 static Expr *
2261 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
2262                                DeclarationNameInfo &NameInfo,
2263                                SourceLocation TemplateKWLoc,
2264                                const TemplateArgumentListInfo *TemplateArgs) {
2265   // Only try to recover from lookup into dependent bases in static methods or
2266   // contexts where 'this' is available.
2267   QualType ThisType = S.getCurrentThisType();
2268   const CXXRecordDecl *RD = nullptr;
2269   if (!ThisType.isNull())
2270     RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2271   else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2272     RD = MD->getParent();
2273   if (!RD || !RD->hasAnyDependentBases())
2274     return nullptr;
2275 
2276   // Diagnose this as unqualified lookup into a dependent base class.  If 'this'
2277   // is available, suggest inserting 'this->' as a fixit.
2278   SourceLocation Loc = NameInfo.getLoc();
2279   auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2280   DB << NameInfo.getName() << RD;
2281 
2282   if (!ThisType.isNull()) {
2283     DB << FixItHint::CreateInsertion(Loc, "this->");
2284     return CXXDependentScopeMemberExpr::Create(
2285         Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2286         /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2287         /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
2288   }
2289 
2290   // Synthesize a fake NNS that points to the derived class.  This will
2291   // perform name lookup during template instantiation.
2292   CXXScopeSpec SS;
2293   auto *NNS =
2294       NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2295   SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2296   return DependentScopeDeclRefExpr::Create(
2297       Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2298       TemplateArgs);
2299 }
2300 
2301 ExprResult
2302 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2303                         SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2304                         bool HasTrailingLParen, bool IsAddressOfOperand,
2305                         CorrectionCandidateCallback *CCC,
2306                         bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2307   assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2308          "cannot be direct & operand and have a trailing lparen");
2309   if (SS.isInvalid())
2310     return ExprError();
2311 
2312   TemplateArgumentListInfo TemplateArgsBuffer;
2313 
2314   // Decompose the UnqualifiedId into the following data.
2315   DeclarationNameInfo NameInfo;
2316   const TemplateArgumentListInfo *TemplateArgs;
2317   DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2318 
2319   DeclarationName Name = NameInfo.getName();
2320   IdentifierInfo *II = Name.getAsIdentifierInfo();
2321   SourceLocation NameLoc = NameInfo.getLoc();
2322 
2323   if (II && II->isEditorPlaceholder()) {
2324     // FIXME: When typed placeholders are supported we can create a typed
2325     // placeholder expression node.
2326     return ExprError();
2327   }
2328 
2329   // C++ [temp.dep.expr]p3:
2330   //   An id-expression is type-dependent if it contains:
2331   //     -- an identifier that was declared with a dependent type,
2332   //        (note: handled after lookup)
2333   //     -- a template-id that is dependent,
2334   //        (note: handled in BuildTemplateIdExpr)
2335   //     -- a conversion-function-id that specifies a dependent type,
2336   //     -- a nested-name-specifier that contains a class-name that
2337   //        names a dependent type.
2338   // Determine whether this is a member of an unknown specialization;
2339   // we need to handle these differently.
2340   bool DependentID = false;
2341   if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2342       Name.getCXXNameType()->isDependentType()) {
2343     DependentID = true;
2344   } else if (SS.isSet()) {
2345     if (DeclContext *DC = computeDeclContext(SS, false)) {
2346       if (RequireCompleteDeclContext(SS, DC))
2347         return ExprError();
2348     } else {
2349       DependentID = true;
2350     }
2351   }
2352 
2353   if (DependentID)
2354     return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2355                                       IsAddressOfOperand, TemplateArgs);
2356 
2357   // Perform the required lookup.
2358   LookupResult R(*this, NameInfo,
2359                  (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam)
2360                      ? LookupObjCImplicitSelfParam
2361                      : LookupOrdinaryName);
2362   if (TemplateKWLoc.isValid() || TemplateArgs) {
2363     // Lookup the template name again to correctly establish the context in
2364     // which it was found. This is really unfortunate as we already did the
2365     // lookup to determine that it was a template name in the first place. If
2366     // this becomes a performance hit, we can work harder to preserve those
2367     // results until we get here but it's likely not worth it.
2368     bool MemberOfUnknownSpecialization;
2369     AssumedTemplateKind AssumedTemplate;
2370     if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2371                            MemberOfUnknownSpecialization, TemplateKWLoc,
2372                            &AssumedTemplate))
2373       return ExprError();
2374 
2375     if (MemberOfUnknownSpecialization ||
2376         (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2377       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2378                                         IsAddressOfOperand, TemplateArgs);
2379   } else {
2380     bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2381     LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2382 
2383     // If the result might be in a dependent base class, this is a dependent
2384     // id-expression.
2385     if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2386       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2387                                         IsAddressOfOperand, TemplateArgs);
2388 
2389     // If this reference is in an Objective-C method, then we need to do
2390     // some special Objective-C lookup, too.
2391     if (IvarLookupFollowUp) {
2392       ExprResult E(LookupInObjCMethod(R, S, II, true));
2393       if (E.isInvalid())
2394         return ExprError();
2395 
2396       if (Expr *Ex = E.getAs<Expr>())
2397         return Ex;
2398     }
2399   }
2400 
2401   if (R.isAmbiguous())
2402     return ExprError();
2403 
2404   // This could be an implicitly declared function reference (legal in C90,
2405   // extension in C99, forbidden in C++).
2406   if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2407     NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2408     if (D) R.addDecl(D);
2409   }
2410 
2411   // Determine whether this name might be a candidate for
2412   // argument-dependent lookup.
2413   bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2414 
2415   if (R.empty() && !ADL) {
2416     if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2417       if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2418                                                    TemplateKWLoc, TemplateArgs))
2419         return E;
2420     }
2421 
2422     // Don't diagnose an empty lookup for inline assembly.
2423     if (IsInlineAsmIdentifier)
2424       return ExprError();
2425 
2426     // If this name wasn't predeclared and if this is not a function
2427     // call, diagnose the problem.
2428     TypoExpr *TE = nullptr;
2429     DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep()
2430                                                        : nullptr);
2431     DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;
2432     assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2433            "Typo correction callback misconfigured");
2434     if (CCC) {
2435       // Make sure the callback knows what the typo being diagnosed is.
2436       CCC->setTypoName(II);
2437       if (SS.isValid())
2438         CCC->setTypoNNS(SS.getScopeRep());
2439     }
2440     // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2441     // a template name, but we happen to have always already looked up the name
2442     // before we get here if it must be a template name.
2443     if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr,
2444                             None, &TE)) {
2445       if (TE && KeywordReplacement) {
2446         auto &State = getTypoExprState(TE);
2447         auto BestTC = State.Consumer->getNextCorrection();
2448         if (BestTC.isKeyword()) {
2449           auto *II = BestTC.getCorrectionAsIdentifierInfo();
2450           if (State.DiagHandler)
2451             State.DiagHandler(BestTC);
2452           KeywordReplacement->startToken();
2453           KeywordReplacement->setKind(II->getTokenID());
2454           KeywordReplacement->setIdentifierInfo(II);
2455           KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2456           // Clean up the state associated with the TypoExpr, since it has
2457           // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2458           clearDelayedTypo(TE);
2459           // Signal that a correction to a keyword was performed by returning a
2460           // valid-but-null ExprResult.
2461           return (Expr*)nullptr;
2462         }
2463         State.Consumer->resetCorrectionStream();
2464       }
2465       return TE ? TE : ExprError();
2466     }
2467 
2468     assert(!R.empty() &&
2469            "DiagnoseEmptyLookup returned false but added no results");
2470 
2471     // If we found an Objective-C instance variable, let
2472     // LookupInObjCMethod build the appropriate expression to
2473     // reference the ivar.
2474     if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2475       R.clear();
2476       ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2477       // In a hopelessly buggy code, Objective-C instance variable
2478       // lookup fails and no expression will be built to reference it.
2479       if (!E.isInvalid() && !E.get())
2480         return ExprError();
2481       return E;
2482     }
2483   }
2484 
2485   // This is guaranteed from this point on.
2486   assert(!R.empty() || ADL);
2487 
2488   // Check whether this might be a C++ implicit instance member access.
2489   // C++ [class.mfct.non-static]p3:
2490   //   When an id-expression that is not part of a class member access
2491   //   syntax and not used to form a pointer to member is used in the
2492   //   body of a non-static member function of class X, if name lookup
2493   //   resolves the name in the id-expression to a non-static non-type
2494   //   member of some class C, the id-expression is transformed into a
2495   //   class member access expression using (*this) as the
2496   //   postfix-expression to the left of the . operator.
2497   //
2498   // But we don't actually need to do this for '&' operands if R
2499   // resolved to a function or overloaded function set, because the
2500   // expression is ill-formed if it actually works out to be a
2501   // non-static member function:
2502   //
2503   // C++ [expr.ref]p4:
2504   //   Otherwise, if E1.E2 refers to a non-static member function. . .
2505   //   [t]he expression can be used only as the left-hand operand of a
2506   //   member function call.
2507   //
2508   // There are other safeguards against such uses, but it's important
2509   // to get this right here so that we don't end up making a
2510   // spuriously dependent expression if we're inside a dependent
2511   // instance method.
2512   if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2513     bool MightBeImplicitMember;
2514     if (!IsAddressOfOperand)
2515       MightBeImplicitMember = true;
2516     else if (!SS.isEmpty())
2517       MightBeImplicitMember = false;
2518     else if (R.isOverloadedResult())
2519       MightBeImplicitMember = false;
2520     else if (R.isUnresolvableResult())
2521       MightBeImplicitMember = true;
2522     else
2523       MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2524                               isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2525                               isa<MSPropertyDecl>(R.getFoundDecl());
2526 
2527     if (MightBeImplicitMember)
2528       return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2529                                              R, TemplateArgs, S);
2530   }
2531 
2532   if (TemplateArgs || TemplateKWLoc.isValid()) {
2533 
2534     // In C++1y, if this is a variable template id, then check it
2535     // in BuildTemplateIdExpr().
2536     // The single lookup result must be a variable template declaration.
2537     if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId &&
2538         Id.TemplateId->Kind == TNK_Var_template) {
2539       assert(R.getAsSingle<VarTemplateDecl>() &&
2540              "There should only be one declaration found.");
2541     }
2542 
2543     return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2544   }
2545 
2546   return BuildDeclarationNameExpr(SS, R, ADL);
2547 }
2548 
2549 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2550 /// declaration name, generally during template instantiation.
2551 /// There's a large number of things which don't need to be done along
2552 /// this path.
2553 ExprResult Sema::BuildQualifiedDeclarationNameExpr(
2554     CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2555     bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2556   DeclContext *DC = computeDeclContext(SS, false);
2557   if (!DC)
2558     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2559                                      NameInfo, /*TemplateArgs=*/nullptr);
2560 
2561   if (RequireCompleteDeclContext(SS, DC))
2562     return ExprError();
2563 
2564   LookupResult R(*this, NameInfo, LookupOrdinaryName);
2565   LookupQualifiedName(R, DC);
2566 
2567   if (R.isAmbiguous())
2568     return ExprError();
2569 
2570   if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2571     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2572                                      NameInfo, /*TemplateArgs=*/nullptr);
2573 
2574   if (R.empty()) {
2575     Diag(NameInfo.getLoc(), diag::err_no_member)
2576       << NameInfo.getName() << DC << SS.getRange();
2577     return ExprError();
2578   }
2579 
2580   if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2581     // Diagnose a missing typename if this resolved unambiguously to a type in
2582     // a dependent context.  If we can recover with a type, downgrade this to
2583     // a warning in Microsoft compatibility mode.
2584     unsigned DiagID = diag::err_typename_missing;
2585     if (RecoveryTSI && getLangOpts().MSVCCompat)
2586       DiagID = diag::ext_typename_missing;
2587     SourceLocation Loc = SS.getBeginLoc();
2588     auto D = Diag(Loc, DiagID);
2589     D << SS.getScopeRep() << NameInfo.getName().getAsString()
2590       << SourceRange(Loc, NameInfo.getEndLoc());
2591 
2592     // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2593     // context.
2594     if (!RecoveryTSI)
2595       return ExprError();
2596 
2597     // Only issue the fixit if we're prepared to recover.
2598     D << FixItHint::CreateInsertion(Loc, "typename ");
2599 
2600     // Recover by pretending this was an elaborated type.
2601     QualType Ty = Context.getTypeDeclType(TD);
2602     TypeLocBuilder TLB;
2603     TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2604 
2605     QualType ET = getElaboratedType(ETK_None, SS, Ty);
2606     ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2607     QTL.setElaboratedKeywordLoc(SourceLocation());
2608     QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2609 
2610     *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2611 
2612     return ExprEmpty();
2613   }
2614 
2615   // Defend against this resolving to an implicit member access. We usually
2616   // won't get here if this might be a legitimate a class member (we end up in
2617   // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2618   // a pointer-to-member or in an unevaluated context in C++11.
2619   if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2620     return BuildPossibleImplicitMemberExpr(SS,
2621                                            /*TemplateKWLoc=*/SourceLocation(),
2622                                            R, /*TemplateArgs=*/nullptr, S);
2623 
2624   return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2625 }
2626 
2627 /// The parser has read a name in, and Sema has detected that we're currently
2628 /// inside an ObjC method. Perform some additional checks and determine if we
2629 /// should form a reference to an ivar.
2630 ///
2631 /// Ideally, most of this would be done by lookup, but there's
2632 /// actually quite a lot of extra work involved.
2633 DeclResult Sema::LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S,
2634                                         IdentifierInfo *II) {
2635   SourceLocation Loc = Lookup.getNameLoc();
2636   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2637 
2638   // Check for error condition which is already reported.
2639   if (!CurMethod)
2640     return DeclResult(true);
2641 
2642   // There are two cases to handle here.  1) scoped lookup could have failed,
2643   // in which case we should look for an ivar.  2) scoped lookup could have
2644   // found a decl, but that decl is outside the current instance method (i.e.
2645   // a global variable).  In these two cases, we do a lookup for an ivar with
2646   // this name, if the lookup sucedes, we replace it our current decl.
2647 
2648   // If we're in a class method, we don't normally want to look for
2649   // ivars.  But if we don't find anything else, and there's an
2650   // ivar, that's an error.
2651   bool IsClassMethod = CurMethod->isClassMethod();
2652 
2653   bool LookForIvars;
2654   if (Lookup.empty())
2655     LookForIvars = true;
2656   else if (IsClassMethod)
2657     LookForIvars = false;
2658   else
2659     LookForIvars = (Lookup.isSingleResult() &&
2660                     Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2661   ObjCInterfaceDecl *IFace = nullptr;
2662   if (LookForIvars) {
2663     IFace = CurMethod->getClassInterface();
2664     ObjCInterfaceDecl *ClassDeclared;
2665     ObjCIvarDecl *IV = nullptr;
2666     if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2667       // Diagnose using an ivar in a class method.
2668       if (IsClassMethod) {
2669         Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
2670         return DeclResult(true);
2671       }
2672 
2673       // Diagnose the use of an ivar outside of the declaring class.
2674       if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2675           !declaresSameEntity(ClassDeclared, IFace) &&
2676           !getLangOpts().DebuggerSupport)
2677         Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
2678 
2679       // Success.
2680       return IV;
2681     }
2682   } else if (CurMethod->isInstanceMethod()) {
2683     // We should warn if a local variable hides an ivar.
2684     if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2685       ObjCInterfaceDecl *ClassDeclared;
2686       if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2687         if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2688             declaresSameEntity(IFace, ClassDeclared))
2689           Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2690       }
2691     }
2692   } else if (Lookup.isSingleResult() &&
2693              Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2694     // If accessing a stand-alone ivar in a class method, this is an error.
2695     if (const ObjCIvarDecl *IV =
2696             dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) {
2697       Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
2698       return DeclResult(true);
2699     }
2700   }
2701 
2702   // Didn't encounter an error, didn't find an ivar.
2703   return DeclResult(false);
2704 }
2705 
2706 ExprResult Sema::BuildIvarRefExpr(Scope *S, SourceLocation Loc,
2707                                   ObjCIvarDecl *IV) {
2708   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2709   assert(CurMethod && CurMethod->isInstanceMethod() &&
2710          "should not reference ivar from this context");
2711 
2712   ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
2713   assert(IFace && "should not reference ivar from this context");
2714 
2715   // If we're referencing an invalid decl, just return this as a silent
2716   // error node.  The error diagnostic was already emitted on the decl.
2717   if (IV->isInvalidDecl())
2718     return ExprError();
2719 
2720   // Check if referencing a field with __attribute__((deprecated)).
2721   if (DiagnoseUseOfDecl(IV, Loc))
2722     return ExprError();
2723 
2724   // FIXME: This should use a new expr for a direct reference, don't
2725   // turn this into Self->ivar, just return a BareIVarExpr or something.
2726   IdentifierInfo &II = Context.Idents.get("self");
2727   UnqualifiedId SelfName;
2728   SelfName.setIdentifier(&II, SourceLocation());
2729   SelfName.setKind(UnqualifiedIdKind::IK_ImplicitSelfParam);
2730   CXXScopeSpec SelfScopeSpec;
2731   SourceLocation TemplateKWLoc;
2732   ExprResult SelfExpr =
2733       ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName,
2734                         /*HasTrailingLParen=*/false,
2735                         /*IsAddressOfOperand=*/false);
2736   if (SelfExpr.isInvalid())
2737     return ExprError();
2738 
2739   SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2740   if (SelfExpr.isInvalid())
2741     return ExprError();
2742 
2743   MarkAnyDeclReferenced(Loc, IV, true);
2744 
2745   ObjCMethodFamily MF = CurMethod->getMethodFamily();
2746   if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2747       !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2748     Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2749 
2750   ObjCIvarRefExpr *Result = new (Context)
2751       ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2752                       IV->getLocation(), SelfExpr.get(), true, true);
2753 
2754   if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2755     if (!isUnevaluatedContext() &&
2756         !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2757       getCurFunction()->recordUseOfWeak(Result);
2758   }
2759   if (getLangOpts().ObjCAutoRefCount)
2760     if (const BlockDecl *BD = CurContext->getInnermostBlockDecl())
2761       ImplicitlyRetainedSelfLocs.push_back({Loc, BD});
2762 
2763   return Result;
2764 }
2765 
2766 /// The parser has read a name in, and Sema has detected that we're currently
2767 /// inside an ObjC method. Perform some additional checks and determine if we
2768 /// should form a reference to an ivar. If so, build an expression referencing
2769 /// that ivar.
2770 ExprResult
2771 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2772                          IdentifierInfo *II, bool AllowBuiltinCreation) {
2773   // FIXME: Integrate this lookup step into LookupParsedName.
2774   DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II);
2775   if (Ivar.isInvalid())
2776     return ExprError();
2777   if (Ivar.isUsable())
2778     return BuildIvarRefExpr(S, Lookup.getNameLoc(),
2779                             cast<ObjCIvarDecl>(Ivar.get()));
2780 
2781   if (Lookup.empty() && II && AllowBuiltinCreation)
2782     LookupBuiltin(Lookup);
2783 
2784   // Sentinel value saying that we didn't do anything special.
2785   return ExprResult(false);
2786 }
2787 
2788 /// Cast a base object to a member's actual type.
2789 ///
2790 /// Logically this happens in three phases:
2791 ///
2792 /// * First we cast from the base type to the naming class.
2793 ///   The naming class is the class into which we were looking
2794 ///   when we found the member;  it's the qualifier type if a
2795 ///   qualifier was provided, and otherwise it's the base type.
2796 ///
2797 /// * Next we cast from the naming class to the declaring class.
2798 ///   If the member we found was brought into a class's scope by
2799 ///   a using declaration, this is that class;  otherwise it's
2800 ///   the class declaring the member.
2801 ///
2802 /// * Finally we cast from the declaring class to the "true"
2803 ///   declaring class of the member.  This conversion does not
2804 ///   obey access control.
2805 ExprResult
2806 Sema::PerformObjectMemberConversion(Expr *From,
2807                                     NestedNameSpecifier *Qualifier,
2808                                     NamedDecl *FoundDecl,
2809                                     NamedDecl *Member) {
2810   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2811   if (!RD)
2812     return From;
2813 
2814   QualType DestRecordType;
2815   QualType DestType;
2816   QualType FromRecordType;
2817   QualType FromType = From->getType();
2818   bool PointerConversions = false;
2819   if (isa<FieldDecl>(Member)) {
2820     DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2821     auto FromPtrType = FromType->getAs<PointerType>();
2822     DestRecordType = Context.getAddrSpaceQualType(
2823         DestRecordType, FromPtrType
2824                             ? FromType->getPointeeType().getAddressSpace()
2825                             : FromType.getAddressSpace());
2826 
2827     if (FromPtrType) {
2828       DestType = Context.getPointerType(DestRecordType);
2829       FromRecordType = FromPtrType->getPointeeType();
2830       PointerConversions = true;
2831     } else {
2832       DestType = DestRecordType;
2833       FromRecordType = FromType;
2834     }
2835   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2836     if (Method->isStatic())
2837       return From;
2838 
2839     DestType = Method->getThisType();
2840     DestRecordType = DestType->getPointeeType();
2841 
2842     if (FromType->getAs<PointerType>()) {
2843       FromRecordType = FromType->getPointeeType();
2844       PointerConversions = true;
2845     } else {
2846       FromRecordType = FromType;
2847       DestType = DestRecordType;
2848     }
2849 
2850     LangAS FromAS = FromRecordType.getAddressSpace();
2851     LangAS DestAS = DestRecordType.getAddressSpace();
2852     if (FromAS != DestAS) {
2853       QualType FromRecordTypeWithoutAS =
2854           Context.removeAddrSpaceQualType(FromRecordType);
2855       QualType FromTypeWithDestAS =
2856           Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS);
2857       if (PointerConversions)
2858         FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS);
2859       From = ImpCastExprToType(From, FromTypeWithDestAS,
2860                                CK_AddressSpaceConversion, From->getValueKind())
2861                  .get();
2862     }
2863   } else {
2864     // No conversion necessary.
2865     return From;
2866   }
2867 
2868   if (DestType->isDependentType() || FromType->isDependentType())
2869     return From;
2870 
2871   // If the unqualified types are the same, no conversion is necessary.
2872   if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2873     return From;
2874 
2875   SourceRange FromRange = From->getSourceRange();
2876   SourceLocation FromLoc = FromRange.getBegin();
2877 
2878   ExprValueKind VK = From->getValueKind();
2879 
2880   // C++ [class.member.lookup]p8:
2881   //   [...] Ambiguities can often be resolved by qualifying a name with its
2882   //   class name.
2883   //
2884   // If the member was a qualified name and the qualified referred to a
2885   // specific base subobject type, we'll cast to that intermediate type
2886   // first and then to the object in which the member is declared. That allows
2887   // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2888   //
2889   //   class Base { public: int x; };
2890   //   class Derived1 : public Base { };
2891   //   class Derived2 : public Base { };
2892   //   class VeryDerived : public Derived1, public Derived2 { void f(); };
2893   //
2894   //   void VeryDerived::f() {
2895   //     x = 17; // error: ambiguous base subobjects
2896   //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
2897   //   }
2898   if (Qualifier && Qualifier->getAsType()) {
2899     QualType QType = QualType(Qualifier->getAsType(), 0);
2900     assert(QType->isRecordType() && "lookup done with non-record type");
2901 
2902     QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2903 
2904     // In C++98, the qualifier type doesn't actually have to be a base
2905     // type of the object type, in which case we just ignore it.
2906     // Otherwise build the appropriate casts.
2907     if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
2908       CXXCastPath BasePath;
2909       if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2910                                        FromLoc, FromRange, &BasePath))
2911         return ExprError();
2912 
2913       if (PointerConversions)
2914         QType = Context.getPointerType(QType);
2915       From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2916                                VK, &BasePath).get();
2917 
2918       FromType = QType;
2919       FromRecordType = QRecordType;
2920 
2921       // If the qualifier type was the same as the destination type,
2922       // we're done.
2923       if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2924         return From;
2925     }
2926   }
2927 
2928   bool IgnoreAccess = false;
2929 
2930   // If we actually found the member through a using declaration, cast
2931   // down to the using declaration's type.
2932   //
2933   // Pointer equality is fine here because only one declaration of a
2934   // class ever has member declarations.
2935   if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2936     assert(isa<UsingShadowDecl>(FoundDecl));
2937     QualType URecordType = Context.getTypeDeclType(
2938                            cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2939 
2940     // We only need to do this if the naming-class to declaring-class
2941     // conversion is non-trivial.
2942     if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2943       assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType));
2944       CXXCastPath BasePath;
2945       if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2946                                        FromLoc, FromRange, &BasePath))
2947         return ExprError();
2948 
2949       QualType UType = URecordType;
2950       if (PointerConversions)
2951         UType = Context.getPointerType(UType);
2952       From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2953                                VK, &BasePath).get();
2954       FromType = UType;
2955       FromRecordType = URecordType;
2956     }
2957 
2958     // We don't do access control for the conversion from the
2959     // declaring class to the true declaring class.
2960     IgnoreAccess = true;
2961   }
2962 
2963   CXXCastPath BasePath;
2964   if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2965                                    FromLoc, FromRange, &BasePath,
2966                                    IgnoreAccess))
2967     return ExprError();
2968 
2969   return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2970                            VK, &BasePath);
2971 }
2972 
2973 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2974                                       const LookupResult &R,
2975                                       bool HasTrailingLParen) {
2976   // Only when used directly as the postfix-expression of a call.
2977   if (!HasTrailingLParen)
2978     return false;
2979 
2980   // Never if a scope specifier was provided.
2981   if (SS.isSet())
2982     return false;
2983 
2984   // Only in C++ or ObjC++.
2985   if (!getLangOpts().CPlusPlus)
2986     return false;
2987 
2988   // Turn off ADL when we find certain kinds of declarations during
2989   // normal lookup:
2990   for (NamedDecl *D : R) {
2991     // C++0x [basic.lookup.argdep]p3:
2992     //     -- a declaration of a class member
2993     // Since using decls preserve this property, we check this on the
2994     // original decl.
2995     if (D->isCXXClassMember())
2996       return false;
2997 
2998     // C++0x [basic.lookup.argdep]p3:
2999     //     -- a block-scope function declaration that is not a
3000     //        using-declaration
3001     // NOTE: we also trigger this for function templates (in fact, we
3002     // don't check the decl type at all, since all other decl types
3003     // turn off ADL anyway).
3004     if (isa<UsingShadowDecl>(D))
3005       D = cast<UsingShadowDecl>(D)->getTargetDecl();
3006     else if (D->getLexicalDeclContext()->isFunctionOrMethod())
3007       return false;
3008 
3009     // C++0x [basic.lookup.argdep]p3:
3010     //     -- a declaration that is neither a function or a function
3011     //        template
3012     // And also for builtin functions.
3013     if (isa<FunctionDecl>(D)) {
3014       FunctionDecl *FDecl = cast<FunctionDecl>(D);
3015 
3016       // But also builtin functions.
3017       if (FDecl->getBuiltinID() && FDecl->isImplicit())
3018         return false;
3019     } else if (!isa<FunctionTemplateDecl>(D))
3020       return false;
3021   }
3022 
3023   return true;
3024 }
3025 
3026 
3027 /// Diagnoses obvious problems with the use of the given declaration
3028 /// as an expression.  This is only actually called for lookups that
3029 /// were not overloaded, and it doesn't promise that the declaration
3030 /// will in fact be used.
3031 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
3032   if (D->isInvalidDecl())
3033     return true;
3034 
3035   if (isa<TypedefNameDecl>(D)) {
3036     S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
3037     return true;
3038   }
3039 
3040   if (isa<ObjCInterfaceDecl>(D)) {
3041     S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
3042     return true;
3043   }
3044 
3045   if (isa<NamespaceDecl>(D)) {
3046     S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
3047     return true;
3048   }
3049 
3050   return false;
3051 }
3052 
3053 // Certain multiversion types should be treated as overloaded even when there is
3054 // only one result.
3055 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) {
3056   assert(R.isSingleResult() && "Expected only a single result");
3057   const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
3058   return FD &&
3059          (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
3060 }
3061 
3062 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
3063                                           LookupResult &R, bool NeedsADL,
3064                                           bool AcceptInvalidDecl) {
3065   // If this is a single, fully-resolved result and we don't need ADL,
3066   // just build an ordinary singleton decl ref.
3067   if (!NeedsADL && R.isSingleResult() &&
3068       !R.getAsSingle<FunctionTemplateDecl>() &&
3069       !ShouldLookupResultBeMultiVersionOverload(R))
3070     return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
3071                                     R.getRepresentativeDecl(), nullptr,
3072                                     AcceptInvalidDecl);
3073 
3074   // We only need to check the declaration if there's exactly one
3075   // result, because in the overloaded case the results can only be
3076   // functions and function templates.
3077   if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) &&
3078       CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
3079     return ExprError();
3080 
3081   // Otherwise, just build an unresolved lookup expression.  Suppress
3082   // any lookup-related diagnostics; we'll hash these out later, when
3083   // we've picked a target.
3084   R.suppressDiagnostics();
3085 
3086   UnresolvedLookupExpr *ULE
3087     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
3088                                    SS.getWithLocInContext(Context),
3089                                    R.getLookupNameInfo(),
3090                                    NeedsADL, R.isOverloadedResult(),
3091                                    R.begin(), R.end());
3092 
3093   return ULE;
3094 }
3095 
3096 static void
3097 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
3098                                    ValueDecl *var, DeclContext *DC);
3099 
3100 /// Complete semantic analysis for a reference to the given declaration.
3101 ExprResult Sema::BuildDeclarationNameExpr(
3102     const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
3103     NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
3104     bool AcceptInvalidDecl) {
3105   assert(D && "Cannot refer to a NULL declaration");
3106   assert(!isa<FunctionTemplateDecl>(D) &&
3107          "Cannot refer unambiguously to a function template");
3108 
3109   SourceLocation Loc = NameInfo.getLoc();
3110   if (CheckDeclInExpr(*this, Loc, D))
3111     return ExprError();
3112 
3113   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
3114     // Specifically diagnose references to class templates that are missing
3115     // a template argument list.
3116     diagnoseMissingTemplateArguments(TemplateName(Template), Loc);
3117     return ExprError();
3118   }
3119 
3120   // Make sure that we're referring to a value.
3121   ValueDecl *VD = dyn_cast<ValueDecl>(D);
3122   if (!VD) {
3123     Diag(Loc, diag::err_ref_non_value)
3124       << D << SS.getRange();
3125     Diag(D->getLocation(), diag::note_declared_at);
3126     return ExprError();
3127   }
3128 
3129   // Check whether this declaration can be used. Note that we suppress
3130   // this check when we're going to perform argument-dependent lookup
3131   // on this function name, because this might not be the function
3132   // that overload resolution actually selects.
3133   if (DiagnoseUseOfDecl(VD, Loc))
3134     return ExprError();
3135 
3136   // Only create DeclRefExpr's for valid Decl's.
3137   if (VD->isInvalidDecl() && !AcceptInvalidDecl)
3138     return ExprError();
3139 
3140   // Handle members of anonymous structs and unions.  If we got here,
3141   // and the reference is to a class member indirect field, then this
3142   // must be the subject of a pointer-to-member expression.
3143   if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
3144     if (!indirectField->isCXXClassMember())
3145       return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
3146                                                       indirectField);
3147 
3148   {
3149     QualType type = VD->getType();
3150     if (type.isNull())
3151       return ExprError();
3152     ExprValueKind valueKind = VK_RValue;
3153 
3154     // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of
3155     // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value,
3156     // is expanded by some outer '...' in the context of the use.
3157     type = type.getNonPackExpansionType();
3158 
3159     switch (D->getKind()) {
3160     // Ignore all the non-ValueDecl kinds.
3161 #define ABSTRACT_DECL(kind)
3162 #define VALUE(type, base)
3163 #define DECL(type, base) \
3164     case Decl::type:
3165 #include "clang/AST/DeclNodes.inc"
3166       llvm_unreachable("invalid value decl kind");
3167 
3168     // These shouldn't make it here.
3169     case Decl::ObjCAtDefsField:
3170       llvm_unreachable("forming non-member reference to ivar?");
3171 
3172     // Enum constants are always r-values and never references.
3173     // Unresolved using declarations are dependent.
3174     case Decl::EnumConstant:
3175     case Decl::UnresolvedUsingValue:
3176     case Decl::OMPDeclareReduction:
3177     case Decl::OMPDeclareMapper:
3178       valueKind = VK_RValue;
3179       break;
3180 
3181     // Fields and indirect fields that got here must be for
3182     // pointer-to-member expressions; we just call them l-values for
3183     // internal consistency, because this subexpression doesn't really
3184     // exist in the high-level semantics.
3185     case Decl::Field:
3186     case Decl::IndirectField:
3187     case Decl::ObjCIvar:
3188       assert(getLangOpts().CPlusPlus &&
3189              "building reference to field in C?");
3190 
3191       // These can't have reference type in well-formed programs, but
3192       // for internal consistency we do this anyway.
3193       type = type.getNonReferenceType();
3194       valueKind = VK_LValue;
3195       break;
3196 
3197     // Non-type template parameters are either l-values or r-values
3198     // depending on the type.
3199     case Decl::NonTypeTemplateParm: {
3200       if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
3201         type = reftype->getPointeeType();
3202         valueKind = VK_LValue; // even if the parameter is an r-value reference
3203         break;
3204       }
3205 
3206       // For non-references, we need to strip qualifiers just in case
3207       // the template parameter was declared as 'const int' or whatever.
3208       valueKind = VK_RValue;
3209       type = type.getUnqualifiedType();
3210       break;
3211     }
3212 
3213     case Decl::Var:
3214     case Decl::VarTemplateSpecialization:
3215     case Decl::VarTemplatePartialSpecialization:
3216     case Decl::Decomposition:
3217     case Decl::OMPCapturedExpr:
3218       // In C, "extern void blah;" is valid and is an r-value.
3219       if (!getLangOpts().CPlusPlus &&
3220           !type.hasQualifiers() &&
3221           type->isVoidType()) {
3222         valueKind = VK_RValue;
3223         break;
3224       }
3225       LLVM_FALLTHROUGH;
3226 
3227     case Decl::ImplicitParam:
3228     case Decl::ParmVar: {
3229       // These are always l-values.
3230       valueKind = VK_LValue;
3231       type = type.getNonReferenceType();
3232 
3233       // FIXME: Does the addition of const really only apply in
3234       // potentially-evaluated contexts? Since the variable isn't actually
3235       // captured in an unevaluated context, it seems that the answer is no.
3236       if (!isUnevaluatedContext()) {
3237         QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
3238         if (!CapturedType.isNull())
3239           type = CapturedType;
3240       }
3241 
3242       break;
3243     }
3244 
3245     case Decl::Binding: {
3246       // These are always lvalues.
3247       valueKind = VK_LValue;
3248       type = type.getNonReferenceType();
3249       // FIXME: Support lambda-capture of BindingDecls, once CWG actually
3250       // decides how that's supposed to work.
3251       auto *BD = cast<BindingDecl>(VD);
3252       if (BD->getDeclContext() != CurContext) {
3253         auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl());
3254         if (DD && DD->hasLocalStorage())
3255           diagnoseUncapturableValueReference(*this, Loc, BD, CurContext);
3256       }
3257       break;
3258     }
3259 
3260     case Decl::Function: {
3261       if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
3262         if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
3263           type = Context.BuiltinFnTy;
3264           valueKind = VK_RValue;
3265           break;
3266         }
3267       }
3268 
3269       const FunctionType *fty = type->castAs<FunctionType>();
3270 
3271       // If we're referring to a function with an __unknown_anytype
3272       // result type, make the entire expression __unknown_anytype.
3273       if (fty->getReturnType() == Context.UnknownAnyTy) {
3274         type = Context.UnknownAnyTy;
3275         valueKind = VK_RValue;
3276         break;
3277       }
3278 
3279       // Functions are l-values in C++.
3280       if (getLangOpts().CPlusPlus) {
3281         valueKind = VK_LValue;
3282         break;
3283       }
3284 
3285       // C99 DR 316 says that, if a function type comes from a
3286       // function definition (without a prototype), that type is only
3287       // used for checking compatibility. Therefore, when referencing
3288       // the function, we pretend that we don't have the full function
3289       // type.
3290       if (!cast<FunctionDecl>(VD)->hasPrototype() &&
3291           isa<FunctionProtoType>(fty))
3292         type = Context.getFunctionNoProtoType(fty->getReturnType(),
3293                                               fty->getExtInfo());
3294 
3295       // Functions are r-values in C.
3296       valueKind = VK_RValue;
3297       break;
3298     }
3299 
3300     case Decl::CXXDeductionGuide:
3301       llvm_unreachable("building reference to deduction guide");
3302 
3303     case Decl::MSProperty:
3304     case Decl::MSGuid:
3305       // FIXME: Should MSGuidDecl be subject to capture in OpenMP,
3306       // or duplicated between host and device?
3307       valueKind = VK_LValue;
3308       break;
3309 
3310     case Decl::CXXMethod:
3311       // If we're referring to a method with an __unknown_anytype
3312       // result type, make the entire expression __unknown_anytype.
3313       // This should only be possible with a type written directly.
3314       if (const FunctionProtoType *proto
3315             = dyn_cast<FunctionProtoType>(VD->getType()))
3316         if (proto->getReturnType() == Context.UnknownAnyTy) {
3317           type = Context.UnknownAnyTy;
3318           valueKind = VK_RValue;
3319           break;
3320         }
3321 
3322       // C++ methods are l-values if static, r-values if non-static.
3323       if (cast<CXXMethodDecl>(VD)->isStatic()) {
3324         valueKind = VK_LValue;
3325         break;
3326       }
3327       LLVM_FALLTHROUGH;
3328 
3329     case Decl::CXXConversion:
3330     case Decl::CXXDestructor:
3331     case Decl::CXXConstructor:
3332       valueKind = VK_RValue;
3333       break;
3334     }
3335 
3336     return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3337                             /*FIXME: TemplateKWLoc*/ SourceLocation(),
3338                             TemplateArgs);
3339   }
3340 }
3341 
3342 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3343                                     SmallString<32> &Target) {
3344   Target.resize(CharByteWidth * (Source.size() + 1));
3345   char *ResultPtr = &Target[0];
3346   const llvm::UTF8 *ErrorPtr;
3347   bool success =
3348       llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3349   (void)success;
3350   assert(success);
3351   Target.resize(ResultPtr - &Target[0]);
3352 }
3353 
3354 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3355                                      PredefinedExpr::IdentKind IK) {
3356   // Pick the current block, lambda, captured statement or function.
3357   Decl *currentDecl = nullptr;
3358   if (const BlockScopeInfo *BSI = getCurBlock())
3359     currentDecl = BSI->TheDecl;
3360   else if (const LambdaScopeInfo *LSI = getCurLambda())
3361     currentDecl = LSI->CallOperator;
3362   else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3363     currentDecl = CSI->TheCapturedDecl;
3364   else
3365     currentDecl = getCurFunctionOrMethodDecl();
3366 
3367   if (!currentDecl) {
3368     Diag(Loc, diag::ext_predef_outside_function);
3369     currentDecl = Context.getTranslationUnitDecl();
3370   }
3371 
3372   QualType ResTy;
3373   StringLiteral *SL = nullptr;
3374   if (cast<DeclContext>(currentDecl)->isDependentContext())
3375     ResTy = Context.DependentTy;
3376   else {
3377     // Pre-defined identifiers are of type char[x], where x is the length of
3378     // the string.
3379     auto Str = PredefinedExpr::ComputeName(IK, currentDecl);
3380     unsigned Length = Str.length();
3381 
3382     llvm::APInt LengthI(32, Length + 1);
3383     if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) {
3384       ResTy =
3385           Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst());
3386       SmallString<32> RawChars;
3387       ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3388                               Str, RawChars);
3389       ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3390                                            ArrayType::Normal,
3391                                            /*IndexTypeQuals*/ 0);
3392       SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3393                                  /*Pascal*/ false, ResTy, Loc);
3394     } else {
3395       ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
3396       ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3397                                            ArrayType::Normal,
3398                                            /*IndexTypeQuals*/ 0);
3399       SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3400                                  /*Pascal*/ false, ResTy, Loc);
3401     }
3402   }
3403 
3404   return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL);
3405 }
3406 
3407 static std::pair<QualType, StringLiteral *>
3408 GetUniqueStableNameInfo(ASTContext &Context, QualType OpType,
3409                         SourceLocation OpLoc, PredefinedExpr::IdentKind K) {
3410   std::pair<QualType, StringLiteral*> Result{{}, nullptr};
3411 
3412   if (OpType->isDependentType()) {
3413       Result.first = Context.DependentTy;
3414       return Result;
3415   }
3416 
3417   std::string Str = PredefinedExpr::ComputeName(Context, K, OpType);
3418   llvm::APInt Length(32, Str.length() + 1);
3419   Result.first =
3420       Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
3421   Result.first = Context.getConstantArrayType(
3422       Result.first, Length, nullptr, ArrayType::Normal, /*IndexTypeQuals*/ 0);
3423   Result.second = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3424                                         /*Pascal*/ false, Result.first, OpLoc);
3425   return Result;
3426 }
3427 
3428 ExprResult Sema::BuildUniqueStableName(SourceLocation OpLoc,
3429                                        TypeSourceInfo *Operand) {
3430   QualType ResultTy;
3431   StringLiteral *SL;
3432   std::tie(ResultTy, SL) = GetUniqueStableNameInfo(
3433       Context, Operand->getType(), OpLoc, PredefinedExpr::UniqueStableNameType);
3434 
3435   return PredefinedExpr::Create(Context, OpLoc, ResultTy,
3436                                 PredefinedExpr::UniqueStableNameType, SL,
3437                                 Operand);
3438 }
3439 
3440 ExprResult Sema::BuildUniqueStableName(SourceLocation OpLoc,
3441                                        Expr *E) {
3442   QualType ResultTy;
3443   StringLiteral *SL;
3444   std::tie(ResultTy, SL) = GetUniqueStableNameInfo(
3445       Context, E->getType(), OpLoc, PredefinedExpr::UniqueStableNameExpr);
3446 
3447   return PredefinedExpr::Create(Context, OpLoc, ResultTy,
3448                                 PredefinedExpr::UniqueStableNameExpr, SL, E);
3449 }
3450 
3451 ExprResult Sema::ActOnUniqueStableNameExpr(SourceLocation OpLoc,
3452                                            SourceLocation L, SourceLocation R,
3453                                            ParsedType Ty) {
3454   TypeSourceInfo *TInfo = nullptr;
3455   QualType T = GetTypeFromParser(Ty, &TInfo);
3456 
3457   if (T.isNull())
3458     return ExprError();
3459   if (!TInfo)
3460     TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
3461 
3462   return BuildUniqueStableName(OpLoc, TInfo);
3463 }
3464 
3465 ExprResult Sema::ActOnUniqueStableNameExpr(SourceLocation OpLoc,
3466                                            SourceLocation L, SourceLocation R,
3467                                            Expr *E) {
3468   return BuildUniqueStableName(OpLoc, E);
3469 }
3470 
3471 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3472   PredefinedExpr::IdentKind IK;
3473 
3474   switch (Kind) {
3475   default: llvm_unreachable("Unknown simple primary expr!");
3476   case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3477   case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break;
3478   case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS]
3479   case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS]
3480   case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS]
3481   case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS]
3482   case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break;
3483   }
3484 
3485   return BuildPredefinedExpr(Loc, IK);
3486 }
3487 
3488 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3489   SmallString<16> CharBuffer;
3490   bool Invalid = false;
3491   StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3492   if (Invalid)
3493     return ExprError();
3494 
3495   CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3496                             PP, Tok.getKind());
3497   if (Literal.hadError())
3498     return ExprError();
3499 
3500   QualType Ty;
3501   if (Literal.isWide())
3502     Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3503   else if (Literal.isUTF8() && getLangOpts().Char8)
3504     Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3505   else if (Literal.isUTF16())
3506     Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3507   else if (Literal.isUTF32())
3508     Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3509   else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3510     Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
3511   else
3512     Ty = Context.CharTy;  // 'x' -> char in C++
3513 
3514   CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3515   if (Literal.isWide())
3516     Kind = CharacterLiteral::Wide;
3517   else if (Literal.isUTF16())
3518     Kind = CharacterLiteral::UTF16;
3519   else if (Literal.isUTF32())
3520     Kind = CharacterLiteral::UTF32;
3521   else if (Literal.isUTF8())
3522     Kind = CharacterLiteral::UTF8;
3523 
3524   Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3525                                              Tok.getLocation());
3526 
3527   if (Literal.getUDSuffix().empty())
3528     return Lit;
3529 
3530   // We're building a user-defined literal.
3531   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3532   SourceLocation UDSuffixLoc =
3533     getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3534 
3535   // Make sure we're allowed user-defined literals here.
3536   if (!UDLScope)
3537     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3538 
3539   // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3540   //   operator "" X (ch)
3541   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3542                                         Lit, Tok.getLocation());
3543 }
3544 
3545 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3546   unsigned IntSize = Context.getTargetInfo().getIntWidth();
3547   return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3548                                 Context.IntTy, Loc);
3549 }
3550 
3551 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3552                                   QualType Ty, SourceLocation Loc) {
3553   const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3554 
3555   using llvm::APFloat;
3556   APFloat Val(Format);
3557 
3558   APFloat::opStatus result = Literal.GetFloatValue(Val);
3559 
3560   // Overflow is always an error, but underflow is only an error if
3561   // we underflowed to zero (APFloat reports denormals as underflow).
3562   if ((result & APFloat::opOverflow) ||
3563       ((result & APFloat::opUnderflow) && Val.isZero())) {
3564     unsigned diagnostic;
3565     SmallString<20> buffer;
3566     if (result & APFloat::opOverflow) {
3567       diagnostic = diag::warn_float_overflow;
3568       APFloat::getLargest(Format).toString(buffer);
3569     } else {
3570       diagnostic = diag::warn_float_underflow;
3571       APFloat::getSmallest(Format).toString(buffer);
3572     }
3573 
3574     S.Diag(Loc, diagnostic)
3575       << Ty
3576       << StringRef(buffer.data(), buffer.size());
3577   }
3578 
3579   bool isExact = (result == APFloat::opOK);
3580   return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3581 }
3582 
3583 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3584   assert(E && "Invalid expression");
3585 
3586   if (E->isValueDependent())
3587     return false;
3588 
3589   QualType QT = E->getType();
3590   if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3591     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3592     return true;
3593   }
3594 
3595   llvm::APSInt ValueAPS;
3596   ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3597 
3598   if (R.isInvalid())
3599     return true;
3600 
3601   bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3602   if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3603     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3604         << ValueAPS.toString(10) << ValueIsPositive;
3605     return true;
3606   }
3607 
3608   return false;
3609 }
3610 
3611 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3612   // Fast path for a single digit (which is quite common).  A single digit
3613   // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3614   if (Tok.getLength() == 1) {
3615     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3616     return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3617   }
3618 
3619   SmallString<128> SpellingBuffer;
3620   // NumericLiteralParser wants to overread by one character.  Add padding to
3621   // the buffer in case the token is copied to the buffer.  If getSpelling()
3622   // returns a StringRef to the memory buffer, it should have a null char at
3623   // the EOF, so it is also safe.
3624   SpellingBuffer.resize(Tok.getLength() + 1);
3625 
3626   // Get the spelling of the token, which eliminates trigraphs, etc.
3627   bool Invalid = false;
3628   StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3629   if (Invalid)
3630     return ExprError();
3631 
3632   NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
3633   if (Literal.hadError)
3634     return ExprError();
3635 
3636   if (Literal.hasUDSuffix()) {
3637     // We're building a user-defined literal.
3638     IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3639     SourceLocation UDSuffixLoc =
3640       getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3641 
3642     // Make sure we're allowed user-defined literals here.
3643     if (!UDLScope)
3644       return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3645 
3646     QualType CookedTy;
3647     if (Literal.isFloatingLiteral()) {
3648       // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3649       // long double, the literal is treated as a call of the form
3650       //   operator "" X (f L)
3651       CookedTy = Context.LongDoubleTy;
3652     } else {
3653       // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3654       // unsigned long long, the literal is treated as a call of the form
3655       //   operator "" X (n ULL)
3656       CookedTy = Context.UnsignedLongLongTy;
3657     }
3658 
3659     DeclarationName OpName =
3660       Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3661     DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3662     OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3663 
3664     SourceLocation TokLoc = Tok.getLocation();
3665 
3666     // Perform literal operator lookup to determine if we're building a raw
3667     // literal or a cooked one.
3668     LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3669     switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3670                                   /*AllowRaw*/ true, /*AllowTemplate*/ true,
3671                                   /*AllowStringTemplate*/ false,
3672                                   /*DiagnoseMissing*/ !Literal.isImaginary)) {
3673     case LOLR_ErrorNoDiagnostic:
3674       // Lookup failure for imaginary constants isn't fatal, there's still the
3675       // GNU extension producing _Complex types.
3676       break;
3677     case LOLR_Error:
3678       return ExprError();
3679     case LOLR_Cooked: {
3680       Expr *Lit;
3681       if (Literal.isFloatingLiteral()) {
3682         Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3683       } else {
3684         llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3685         if (Literal.GetIntegerValue(ResultVal))
3686           Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3687               << /* Unsigned */ 1;
3688         Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3689                                      Tok.getLocation());
3690       }
3691       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3692     }
3693 
3694     case LOLR_Raw: {
3695       // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3696       // literal is treated as a call of the form
3697       //   operator "" X ("n")
3698       unsigned Length = Literal.getUDSuffixOffset();
3699       QualType StrTy = Context.getConstantArrayType(
3700           Context.adjustStringLiteralBaseType(Context.CharTy.withConst()),
3701           llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0);
3702       Expr *Lit = StringLiteral::Create(
3703           Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3704           /*Pascal*/false, StrTy, &TokLoc, 1);
3705       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3706     }
3707 
3708     case LOLR_Template: {
3709       // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3710       // template), L is treated as a call fo the form
3711       //   operator "" X <'c1', 'c2', ... 'ck'>()
3712       // where n is the source character sequence c1 c2 ... ck.
3713       TemplateArgumentListInfo ExplicitArgs;
3714       unsigned CharBits = Context.getIntWidth(Context.CharTy);
3715       bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3716       llvm::APSInt Value(CharBits, CharIsUnsigned);
3717       for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3718         Value = TokSpelling[I];
3719         TemplateArgument Arg(Context, Value, Context.CharTy);
3720         TemplateArgumentLocInfo ArgInfo;
3721         ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3722       }
3723       return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3724                                       &ExplicitArgs);
3725     }
3726     case LOLR_StringTemplate:
3727       llvm_unreachable("unexpected literal operator lookup result");
3728     }
3729   }
3730 
3731   Expr *Res;
3732 
3733   if (Literal.isFixedPointLiteral()) {
3734     QualType Ty;
3735 
3736     if (Literal.isAccum) {
3737       if (Literal.isHalf) {
3738         Ty = Context.ShortAccumTy;
3739       } else if (Literal.isLong) {
3740         Ty = Context.LongAccumTy;
3741       } else {
3742         Ty = Context.AccumTy;
3743       }
3744     } else if (Literal.isFract) {
3745       if (Literal.isHalf) {
3746         Ty = Context.ShortFractTy;
3747       } else if (Literal.isLong) {
3748         Ty = Context.LongFractTy;
3749       } else {
3750         Ty = Context.FractTy;
3751       }
3752     }
3753 
3754     if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
3755 
3756     bool isSigned = !Literal.isUnsigned;
3757     unsigned scale = Context.getFixedPointScale(Ty);
3758     unsigned bit_width = Context.getTypeInfo(Ty).Width;
3759 
3760     llvm::APInt Val(bit_width, 0, isSigned);
3761     bool Overflowed = Literal.GetFixedPointValue(Val, scale);
3762     bool ValIsZero = Val.isNullValue() && !Overflowed;
3763 
3764     auto MaxVal = Context.getFixedPointMax(Ty).getValue();
3765     if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
3766       // Clause 6.4.4 - The value of a constant shall be in the range of
3767       // representable values for its type, with exception for constants of a
3768       // fract type with a value of exactly 1; such a constant shall denote
3769       // the maximal value for the type.
3770       --Val;
3771     else if (Val.ugt(MaxVal) || Overflowed)
3772       Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
3773 
3774     Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty,
3775                                               Tok.getLocation(), scale);
3776   } else if (Literal.isFloatingLiteral()) {
3777     QualType Ty;
3778     if (Literal.isHalf){
3779       if (getOpenCLOptions().isEnabled("cl_khr_fp16"))
3780         Ty = Context.HalfTy;
3781       else {
3782         Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3783         return ExprError();
3784       }
3785     } else if (Literal.isFloat)
3786       Ty = Context.FloatTy;
3787     else if (Literal.isLong)
3788       Ty = Context.LongDoubleTy;
3789     else if (Literal.isFloat16)
3790       Ty = Context.Float16Ty;
3791     else if (Literal.isFloat128)
3792       Ty = Context.Float128Ty;
3793     else
3794       Ty = Context.DoubleTy;
3795 
3796     Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3797 
3798     if (Ty == Context.DoubleTy) {
3799       if (getLangOpts().SinglePrecisionConstants) {
3800         const BuiltinType *BTy = Ty->getAs<BuiltinType>();
3801         if (BTy->getKind() != BuiltinType::Float) {
3802           Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3803         }
3804       } else if (getLangOpts().OpenCL &&
3805                  !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
3806         // Impose single-precision float type when cl_khr_fp64 is not enabled.
3807         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
3808         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3809       }
3810     }
3811   } else if (!Literal.isIntegerLiteral()) {
3812     return ExprError();
3813   } else {
3814     QualType Ty;
3815 
3816     // 'long long' is a C99 or C++11 feature.
3817     if (!getLangOpts().C99 && Literal.isLongLong) {
3818       if (getLangOpts().CPlusPlus)
3819         Diag(Tok.getLocation(),
3820              getLangOpts().CPlusPlus11 ?
3821              diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3822       else
3823         Diag(Tok.getLocation(), diag::ext_c99_longlong);
3824     }
3825 
3826     // Get the value in the widest-possible width.
3827     unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3828     llvm::APInt ResultVal(MaxWidth, 0);
3829 
3830     if (Literal.GetIntegerValue(ResultVal)) {
3831       // If this value didn't fit into uintmax_t, error and force to ull.
3832       Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3833           << /* Unsigned */ 1;
3834       Ty = Context.UnsignedLongLongTy;
3835       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3836              "long long is not intmax_t?");
3837     } else {
3838       // If this value fits into a ULL, try to figure out what else it fits into
3839       // according to the rules of C99 6.4.4.1p5.
3840 
3841       // Octal, Hexadecimal, and integers with a U suffix are allowed to
3842       // be an unsigned int.
3843       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3844 
3845       // Check from smallest to largest, picking the smallest type we can.
3846       unsigned Width = 0;
3847 
3848       // Microsoft specific integer suffixes are explicitly sized.
3849       if (Literal.MicrosoftInteger) {
3850         if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3851           Width = 8;
3852           Ty = Context.CharTy;
3853         } else {
3854           Width = Literal.MicrosoftInteger;
3855           Ty = Context.getIntTypeForBitwidth(Width,
3856                                              /*Signed=*/!Literal.isUnsigned);
3857         }
3858       }
3859 
3860       if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
3861         // Are int/unsigned possibilities?
3862         unsigned IntSize = Context.getTargetInfo().getIntWidth();
3863 
3864         // Does it fit in a unsigned int?
3865         if (ResultVal.isIntN(IntSize)) {
3866           // Does it fit in a signed int?
3867           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3868             Ty = Context.IntTy;
3869           else if (AllowUnsigned)
3870             Ty = Context.UnsignedIntTy;
3871           Width = IntSize;
3872         }
3873       }
3874 
3875       // Are long/unsigned long possibilities?
3876       if (Ty.isNull() && !Literal.isLongLong) {
3877         unsigned LongSize = Context.getTargetInfo().getLongWidth();
3878 
3879         // Does it fit in a unsigned long?
3880         if (ResultVal.isIntN(LongSize)) {
3881           // Does it fit in a signed long?
3882           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3883             Ty = Context.LongTy;
3884           else if (AllowUnsigned)
3885             Ty = Context.UnsignedLongTy;
3886           // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
3887           // is compatible.
3888           else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
3889             const unsigned LongLongSize =
3890                 Context.getTargetInfo().getLongLongWidth();
3891             Diag(Tok.getLocation(),
3892                  getLangOpts().CPlusPlus
3893                      ? Literal.isLong
3894                            ? diag::warn_old_implicitly_unsigned_long_cxx
3895                            : /*C++98 UB*/ diag::
3896                                  ext_old_implicitly_unsigned_long_cxx
3897                      : diag::warn_old_implicitly_unsigned_long)
3898                 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
3899                                             : /*will be ill-formed*/ 1);
3900             Ty = Context.UnsignedLongTy;
3901           }
3902           Width = LongSize;
3903         }
3904       }
3905 
3906       // Check long long if needed.
3907       if (Ty.isNull()) {
3908         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3909 
3910         // Does it fit in a unsigned long long?
3911         if (ResultVal.isIntN(LongLongSize)) {
3912           // Does it fit in a signed long long?
3913           // To be compatible with MSVC, hex integer literals ending with the
3914           // LL or i64 suffix are always signed in Microsoft mode.
3915           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3916               (getLangOpts().MSVCCompat && Literal.isLongLong)))
3917             Ty = Context.LongLongTy;
3918           else if (AllowUnsigned)
3919             Ty = Context.UnsignedLongLongTy;
3920           Width = LongLongSize;
3921         }
3922       }
3923 
3924       // If we still couldn't decide a type, we probably have something that
3925       // does not fit in a signed long long, but has no U suffix.
3926       if (Ty.isNull()) {
3927         Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
3928         Ty = Context.UnsignedLongLongTy;
3929         Width = Context.getTargetInfo().getLongLongWidth();
3930       }
3931 
3932       if (ResultVal.getBitWidth() != Width)
3933         ResultVal = ResultVal.trunc(Width);
3934     }
3935     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3936   }
3937 
3938   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3939   if (Literal.isImaginary) {
3940     Res = new (Context) ImaginaryLiteral(Res,
3941                                         Context.getComplexType(Res->getType()));
3942 
3943     Diag(Tok.getLocation(), diag::ext_imaginary_constant);
3944   }
3945   return Res;
3946 }
3947 
3948 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
3949   assert(E && "ActOnParenExpr() missing expr");
3950   return new (Context) ParenExpr(L, R, E);
3951 }
3952 
3953 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3954                                          SourceLocation Loc,
3955                                          SourceRange ArgRange) {
3956   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3957   // scalar or vector data type argument..."
3958   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3959   // type (C99 6.2.5p18) or void.
3960   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3961     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3962       << T << ArgRange;
3963     return true;
3964   }
3965 
3966   assert((T->isVoidType() || !T->isIncompleteType()) &&
3967          "Scalar types should always be complete");
3968   return false;
3969 }
3970 
3971 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3972                                            SourceLocation Loc,
3973                                            SourceRange ArgRange,
3974                                            UnaryExprOrTypeTrait TraitKind) {
3975   // Invalid types must be hard errors for SFINAE in C++.
3976   if (S.LangOpts.CPlusPlus)
3977     return true;
3978 
3979   // C99 6.5.3.4p1:
3980   if (T->isFunctionType() &&
3981       (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
3982        TraitKind == UETT_PreferredAlignOf)) {
3983     // sizeof(function)/alignof(function) is allowed as an extension.
3984     S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3985         << getTraitSpelling(TraitKind) << ArgRange;
3986     return false;
3987   }
3988 
3989   // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
3990   // this is an error (OpenCL v1.1 s6.3.k)
3991   if (T->isVoidType()) {
3992     unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
3993                                         : diag::ext_sizeof_alignof_void_type;
3994     S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange;
3995     return false;
3996   }
3997 
3998   return true;
3999 }
4000 
4001 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
4002                                              SourceLocation Loc,
4003                                              SourceRange ArgRange,
4004                                              UnaryExprOrTypeTrait TraitKind) {
4005   // Reject sizeof(interface) and sizeof(interface<proto>) if the
4006   // runtime doesn't allow it.
4007   if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
4008     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
4009       << T << (TraitKind == UETT_SizeOf)
4010       << ArgRange;
4011     return true;
4012   }
4013 
4014   return false;
4015 }
4016 
4017 /// Check whether E is a pointer from a decayed array type (the decayed
4018 /// pointer type is equal to T) and emit a warning if it is.
4019 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
4020                                      Expr *E) {
4021   // Don't warn if the operation changed the type.
4022   if (T != E->getType())
4023     return;
4024 
4025   // Now look for array decays.
4026   ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
4027   if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
4028     return;
4029 
4030   S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
4031                                              << ICE->getType()
4032                                              << ICE->getSubExpr()->getType();
4033 }
4034 
4035 /// Check the constraints on expression operands to unary type expression
4036 /// and type traits.
4037 ///
4038 /// Completes any types necessary and validates the constraints on the operand
4039 /// expression. The logic mostly mirrors the type-based overload, but may modify
4040 /// the expression as it completes the type for that expression through template
4041 /// instantiation, etc.
4042 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
4043                                             UnaryExprOrTypeTrait ExprKind) {
4044   QualType ExprTy = E->getType();
4045   assert(!ExprTy->isReferenceType());
4046 
4047   bool IsUnevaluatedOperand =
4048       (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf ||
4049        ExprKind == UETT_PreferredAlignOf);
4050   if (IsUnevaluatedOperand) {
4051     ExprResult Result = CheckUnevaluatedOperand(E);
4052     if (Result.isInvalid())
4053       return true;
4054     E = Result.get();
4055   }
4056 
4057   if (ExprKind == UETT_VecStep)
4058     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
4059                                         E->getSourceRange());
4060 
4061   // Whitelist some types as extensions
4062   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
4063                                       E->getSourceRange(), ExprKind))
4064     return false;
4065 
4066   // 'alignof' applied to an expression only requires the base element type of
4067   // the expression to be complete. 'sizeof' requires the expression's type to
4068   // be complete (and will attempt to complete it if it's an array of unknown
4069   // bound).
4070   if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4071     if (RequireCompleteSizedType(
4072             E->getExprLoc(), Context.getBaseElementType(E->getType()),
4073             diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4074             getTraitSpelling(ExprKind), E->getSourceRange()))
4075       return true;
4076   } else {
4077     if (RequireCompleteSizedExprType(
4078             E, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4079             getTraitSpelling(ExprKind), E->getSourceRange()))
4080       return true;
4081   }
4082 
4083   // Completing the expression's type may have changed it.
4084   ExprTy = E->getType();
4085   assert(!ExprTy->isReferenceType());
4086 
4087   if (ExprTy->isFunctionType()) {
4088     Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
4089         << getTraitSpelling(ExprKind) << E->getSourceRange();
4090     return true;
4091   }
4092 
4093   // The operand for sizeof and alignof is in an unevaluated expression context,
4094   // so side effects could result in unintended consequences.
4095   if (IsUnevaluatedOperand && !inTemplateInstantiation() &&
4096       E->HasSideEffects(Context, false))
4097     Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
4098 
4099   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
4100                                        E->getSourceRange(), ExprKind))
4101     return true;
4102 
4103   if (ExprKind == UETT_SizeOf) {
4104     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
4105       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
4106         QualType OType = PVD->getOriginalType();
4107         QualType Type = PVD->getType();
4108         if (Type->isPointerType() && OType->isArrayType()) {
4109           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
4110             << Type << OType;
4111           Diag(PVD->getLocation(), diag::note_declared_at);
4112         }
4113       }
4114     }
4115 
4116     // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
4117     // decays into a pointer and returns an unintended result. This is most
4118     // likely a typo for "sizeof(array) op x".
4119     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
4120       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4121                                BO->getLHS());
4122       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4123                                BO->getRHS());
4124     }
4125   }
4126 
4127   return false;
4128 }
4129 
4130 /// Check the constraints on operands to unary expression and type
4131 /// traits.
4132 ///
4133 /// This will complete any types necessary, and validate the various constraints
4134 /// on those operands.
4135 ///
4136 /// The UsualUnaryConversions() function is *not* called by this routine.
4137 /// C99 6.3.2.1p[2-4] all state:
4138 ///   Except when it is the operand of the sizeof operator ...
4139 ///
4140 /// C++ [expr.sizeof]p4
4141 ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
4142 ///   standard conversions are not applied to the operand of sizeof.
4143 ///
4144 /// This policy is followed for all of the unary trait expressions.
4145 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
4146                                             SourceLocation OpLoc,
4147                                             SourceRange ExprRange,
4148                                             UnaryExprOrTypeTrait ExprKind) {
4149   if (ExprType->isDependentType())
4150     return false;
4151 
4152   // C++ [expr.sizeof]p2:
4153   //     When applied to a reference or a reference type, the result
4154   //     is the size of the referenced type.
4155   // C++11 [expr.alignof]p3:
4156   //     When alignof is applied to a reference type, the result
4157   //     shall be the alignment of the referenced type.
4158   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
4159     ExprType = Ref->getPointeeType();
4160 
4161   // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
4162   //   When alignof or _Alignof is applied to an array type, the result
4163   //   is the alignment of the element type.
4164   if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4165       ExprKind == UETT_OpenMPRequiredSimdAlign)
4166     ExprType = Context.getBaseElementType(ExprType);
4167 
4168   if (ExprKind == UETT_VecStep)
4169     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
4170 
4171   // Whitelist some types as extensions
4172   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
4173                                       ExprKind))
4174     return false;
4175 
4176   if (RequireCompleteSizedType(
4177           OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4178           getTraitSpelling(ExprKind), ExprRange))
4179     return true;
4180 
4181   if (ExprType->isFunctionType()) {
4182     Diag(OpLoc, diag::err_sizeof_alignof_function_type)
4183         << getTraitSpelling(ExprKind) << ExprRange;
4184     return true;
4185   }
4186 
4187   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
4188                                        ExprKind))
4189     return true;
4190 
4191   return false;
4192 }
4193 
4194 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
4195   // Cannot know anything else if the expression is dependent.
4196   if (E->isTypeDependent())
4197     return false;
4198 
4199   if (E->getObjectKind() == OK_BitField) {
4200     S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
4201        << 1 << E->getSourceRange();
4202     return true;
4203   }
4204 
4205   ValueDecl *D = nullptr;
4206   Expr *Inner = E->IgnoreParens();
4207   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) {
4208     D = DRE->getDecl();
4209   } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) {
4210     D = ME->getMemberDecl();
4211   }
4212 
4213   // If it's a field, require the containing struct to have a
4214   // complete definition so that we can compute the layout.
4215   //
4216   // This can happen in C++11 onwards, either by naming the member
4217   // in a way that is not transformed into a member access expression
4218   // (in an unevaluated operand, for instance), or by naming the member
4219   // in a trailing-return-type.
4220   //
4221   // For the record, since __alignof__ on expressions is a GCC
4222   // extension, GCC seems to permit this but always gives the
4223   // nonsensical answer 0.
4224   //
4225   // We don't really need the layout here --- we could instead just
4226   // directly check for all the appropriate alignment-lowing
4227   // attributes --- but that would require duplicating a lot of
4228   // logic that just isn't worth duplicating for such a marginal
4229   // use-case.
4230   if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
4231     // Fast path this check, since we at least know the record has a
4232     // definition if we can find a member of it.
4233     if (!FD->getParent()->isCompleteDefinition()) {
4234       S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
4235         << E->getSourceRange();
4236       return true;
4237     }
4238 
4239     // Otherwise, if it's a field, and the field doesn't have
4240     // reference type, then it must have a complete type (or be a
4241     // flexible array member, which we explicitly want to
4242     // white-list anyway), which makes the following checks trivial.
4243     if (!FD->getType()->isReferenceType())
4244       return false;
4245   }
4246 
4247   return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4248 }
4249 
4250 bool Sema::CheckVecStepExpr(Expr *E) {
4251   E = E->IgnoreParens();
4252 
4253   // Cannot know anything else if the expression is dependent.
4254   if (E->isTypeDependent())
4255     return false;
4256 
4257   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
4258 }
4259 
4260 static void captureVariablyModifiedType(ASTContext &Context, QualType T,
4261                                         CapturingScopeInfo *CSI) {
4262   assert(T->isVariablyModifiedType());
4263   assert(CSI != nullptr);
4264 
4265   // We're going to walk down into the type and look for VLA expressions.
4266   do {
4267     const Type *Ty = T.getTypePtr();
4268     switch (Ty->getTypeClass()) {
4269 #define TYPE(Class, Base)
4270 #define ABSTRACT_TYPE(Class, Base)
4271 #define NON_CANONICAL_TYPE(Class, Base)
4272 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
4273 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4274 #include "clang/AST/TypeNodes.inc"
4275       T = QualType();
4276       break;
4277     // These types are never variably-modified.
4278     case Type::Builtin:
4279     case Type::Complex:
4280     case Type::Vector:
4281     case Type::ExtVector:
4282     case Type::ConstantMatrix:
4283     case Type::Record:
4284     case Type::Enum:
4285     case Type::Elaborated:
4286     case Type::TemplateSpecialization:
4287     case Type::ObjCObject:
4288     case Type::ObjCInterface:
4289     case Type::ObjCObjectPointer:
4290     case Type::ObjCTypeParam:
4291     case Type::Pipe:
4292     case Type::ExtInt:
4293       llvm_unreachable("type class is never variably-modified!");
4294     case Type::Adjusted:
4295       T = cast<AdjustedType>(Ty)->getOriginalType();
4296       break;
4297     case Type::Decayed:
4298       T = cast<DecayedType>(Ty)->getPointeeType();
4299       break;
4300     case Type::Pointer:
4301       T = cast<PointerType>(Ty)->getPointeeType();
4302       break;
4303     case Type::BlockPointer:
4304       T = cast<BlockPointerType>(Ty)->getPointeeType();
4305       break;
4306     case Type::LValueReference:
4307     case Type::RValueReference:
4308       T = cast<ReferenceType>(Ty)->getPointeeType();
4309       break;
4310     case Type::MemberPointer:
4311       T = cast<MemberPointerType>(Ty)->getPointeeType();
4312       break;
4313     case Type::ConstantArray:
4314     case Type::IncompleteArray:
4315       // Losing element qualification here is fine.
4316       T = cast<ArrayType>(Ty)->getElementType();
4317       break;
4318     case Type::VariableArray: {
4319       // Losing element qualification here is fine.
4320       const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
4321 
4322       // Unknown size indication requires no size computation.
4323       // Otherwise, evaluate and record it.
4324       auto Size = VAT->getSizeExpr();
4325       if (Size && !CSI->isVLATypeCaptured(VAT) &&
4326           (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI)))
4327         CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType());
4328 
4329       T = VAT->getElementType();
4330       break;
4331     }
4332     case Type::FunctionProto:
4333     case Type::FunctionNoProto:
4334       T = cast<FunctionType>(Ty)->getReturnType();
4335       break;
4336     case Type::Paren:
4337     case Type::TypeOf:
4338     case Type::UnaryTransform:
4339     case Type::Attributed:
4340     case Type::SubstTemplateTypeParm:
4341     case Type::PackExpansion:
4342     case Type::MacroQualified:
4343       // Keep walking after single level desugaring.
4344       T = T.getSingleStepDesugaredType(Context);
4345       break;
4346     case Type::Typedef:
4347       T = cast<TypedefType>(Ty)->desugar();
4348       break;
4349     case Type::Decltype:
4350       T = cast<DecltypeType>(Ty)->desugar();
4351       break;
4352     case Type::Auto:
4353     case Type::DeducedTemplateSpecialization:
4354       T = cast<DeducedType>(Ty)->getDeducedType();
4355       break;
4356     case Type::TypeOfExpr:
4357       T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
4358       break;
4359     case Type::Atomic:
4360       T = cast<AtomicType>(Ty)->getValueType();
4361       break;
4362     }
4363   } while (!T.isNull() && T->isVariablyModifiedType());
4364 }
4365 
4366 /// Build a sizeof or alignof expression given a type operand.
4367 ExprResult
4368 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4369                                      SourceLocation OpLoc,
4370                                      UnaryExprOrTypeTrait ExprKind,
4371                                      SourceRange R) {
4372   if (!TInfo)
4373     return ExprError();
4374 
4375   QualType T = TInfo->getType();
4376 
4377   if (!T->isDependentType() &&
4378       CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
4379     return ExprError();
4380 
4381   if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4382     if (auto *TT = T->getAs<TypedefType>()) {
4383       for (auto I = FunctionScopes.rbegin(),
4384                 E = std::prev(FunctionScopes.rend());
4385            I != E; ++I) {
4386         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4387         if (CSI == nullptr)
4388           break;
4389         DeclContext *DC = nullptr;
4390         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4391           DC = LSI->CallOperator;
4392         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4393           DC = CRSI->TheCapturedDecl;
4394         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4395           DC = BSI->TheDecl;
4396         if (DC) {
4397           if (DC->containsDecl(TT->getDecl()))
4398             break;
4399           captureVariablyModifiedType(Context, T, CSI);
4400         }
4401       }
4402     }
4403   }
4404 
4405   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4406   return new (Context) UnaryExprOrTypeTraitExpr(
4407       ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4408 }
4409 
4410 /// Build a sizeof or alignof expression given an expression
4411 /// operand.
4412 ExprResult
4413 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4414                                      UnaryExprOrTypeTrait ExprKind) {
4415   ExprResult PE = CheckPlaceholderExpr(E);
4416   if (PE.isInvalid())
4417     return ExprError();
4418 
4419   E = PE.get();
4420 
4421   // Verify that the operand is valid.
4422   bool isInvalid = false;
4423   if (E->isTypeDependent()) {
4424     // Delay type-checking for type-dependent expressions.
4425   } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4426     isInvalid = CheckAlignOfExpr(*this, E, ExprKind);
4427   } else if (ExprKind == UETT_VecStep) {
4428     isInvalid = CheckVecStepExpr(E);
4429   } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4430       Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4431       isInvalid = true;
4432   } else if (E->refersToBitField()) {  // C99 6.5.3.4p1.
4433     Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4434     isInvalid = true;
4435   } else {
4436     isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
4437   }
4438 
4439   if (isInvalid)
4440     return ExprError();
4441 
4442   if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4443     PE = TransformToPotentiallyEvaluated(E);
4444     if (PE.isInvalid()) return ExprError();
4445     E = PE.get();
4446   }
4447 
4448   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4449   return new (Context) UnaryExprOrTypeTraitExpr(
4450       ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4451 }
4452 
4453 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4454 /// expr and the same for @c alignof and @c __alignof
4455 /// Note that the ArgRange is invalid if isType is false.
4456 ExprResult
4457 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4458                                     UnaryExprOrTypeTrait ExprKind, bool IsType,
4459                                     void *TyOrEx, SourceRange ArgRange) {
4460   // If error parsing type, ignore.
4461   if (!TyOrEx) return ExprError();
4462 
4463   if (IsType) {
4464     TypeSourceInfo *TInfo;
4465     (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4466     return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4467   }
4468 
4469   Expr *ArgEx = (Expr *)TyOrEx;
4470   ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4471   return Result;
4472 }
4473 
4474 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4475                                      bool IsReal) {
4476   if (V.get()->isTypeDependent())
4477     return S.Context.DependentTy;
4478 
4479   // _Real and _Imag are only l-values for normal l-values.
4480   if (V.get()->getObjectKind() != OK_Ordinary) {
4481     V = S.DefaultLvalueConversion(V.get());
4482     if (V.isInvalid())
4483       return QualType();
4484   }
4485 
4486   // These operators return the element type of a complex type.
4487   if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4488     return CT->getElementType();
4489 
4490   // Otherwise they pass through real integer and floating point types here.
4491   if (V.get()->getType()->isArithmeticType())
4492     return V.get()->getType();
4493 
4494   // Test for placeholders.
4495   ExprResult PR = S.CheckPlaceholderExpr(V.get());
4496   if (PR.isInvalid()) return QualType();
4497   if (PR.get() != V.get()) {
4498     V = PR;
4499     return CheckRealImagOperand(S, V, Loc, IsReal);
4500   }
4501 
4502   // Reject anything else.
4503   S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4504     << (IsReal ? "__real" : "__imag");
4505   return QualType();
4506 }
4507 
4508 
4509 
4510 ExprResult
4511 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4512                           tok::TokenKind Kind, Expr *Input) {
4513   UnaryOperatorKind Opc;
4514   switch (Kind) {
4515   default: llvm_unreachable("Unknown unary op!");
4516   case tok::plusplus:   Opc = UO_PostInc; break;
4517   case tok::minusminus: Opc = UO_PostDec; break;
4518   }
4519 
4520   // Since this might is a postfix expression, get rid of ParenListExprs.
4521   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4522   if (Result.isInvalid()) return ExprError();
4523   Input = Result.get();
4524 
4525   return BuildUnaryOp(S, OpLoc, Opc, Input);
4526 }
4527 
4528 /// Diagnose if arithmetic on the given ObjC pointer is illegal.
4529 ///
4530 /// \return true on error
4531 static bool checkArithmeticOnObjCPointer(Sema &S,
4532                                          SourceLocation opLoc,
4533                                          Expr *op) {
4534   assert(op->getType()->isObjCObjectPointerType());
4535   if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4536       !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4537     return false;
4538 
4539   S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4540     << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4541     << op->getSourceRange();
4542   return true;
4543 }
4544 
4545 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4546   auto *BaseNoParens = Base->IgnoreParens();
4547   if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4548     return MSProp->getPropertyDecl()->getType()->isArrayType();
4549   return isa<MSPropertySubscriptExpr>(BaseNoParens);
4550 }
4551 
4552 ExprResult
4553 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
4554                               Expr *idx, SourceLocation rbLoc) {
4555   if (base && !base->getType().isNull() &&
4556       base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection))
4557     return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
4558                                     /*Length=*/nullptr, rbLoc);
4559 
4560   // Since this might be a postfix expression, get rid of ParenListExprs.
4561   if (isa<ParenListExpr>(base)) {
4562     ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4563     if (result.isInvalid()) return ExprError();
4564     base = result.get();
4565   }
4566 
4567   // Check if base and idx form a MatrixSubscriptExpr.
4568   //
4569   // Helper to check for comma expressions, which are not allowed as indices for
4570   // matrix subscript expressions.
4571   auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) {
4572     if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) {
4573       Diag(E->getExprLoc(), diag::err_matrix_subscript_comma)
4574           << SourceRange(base->getBeginLoc(), rbLoc);
4575       return true;
4576     }
4577     return false;
4578   };
4579   // The matrix subscript operator ([][])is considered a single operator.
4580   // Separating the index expressions by parenthesis is not allowed.
4581   if (base->getType()->isSpecificPlaceholderType(
4582           BuiltinType::IncompleteMatrixIdx) &&
4583       !isa<MatrixSubscriptExpr>(base)) {
4584     Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index)
4585         << SourceRange(base->getBeginLoc(), rbLoc);
4586     return ExprError();
4587   }
4588   // If the base is either a MatrixSubscriptExpr or a matrix type, try to create
4589   // a new MatrixSubscriptExpr.
4590   auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base);
4591   if (matSubscriptE) {
4592     if (CheckAndReportCommaError(idx))
4593       return ExprError();
4594 
4595     assert(matSubscriptE->isIncomplete() &&
4596            "base has to be an incomplete matrix subscript");
4597     return CreateBuiltinMatrixSubscriptExpr(
4598         matSubscriptE->getBase(), matSubscriptE->getRowIdx(), idx, rbLoc);
4599   }
4600   Expr *matrixBase = base;
4601   bool IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4602   if (!IsMSPropertySubscript) {
4603     ExprResult result = CheckPlaceholderExpr(base);
4604     if (!result.isInvalid())
4605       matrixBase = result.get();
4606   }
4607   if (matrixBase->getType()->isMatrixType()) {
4608     if (CheckAndReportCommaError(idx))
4609       return ExprError();
4610 
4611     return CreateBuiltinMatrixSubscriptExpr(matrixBase, idx, nullptr, rbLoc);
4612   }
4613 
4614   // A comma-expression as the index is deprecated in C++2a onwards.
4615   if (getLangOpts().CPlusPlus20 &&
4616       ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) ||
4617        (isa<CXXOperatorCallExpr>(idx) &&
4618         cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma))) {
4619     Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript)
4620       << SourceRange(base->getBeginLoc(), rbLoc);
4621   }
4622 
4623   // Handle any non-overload placeholder types in the base and index
4624   // expressions.  We can't handle overloads here because the other
4625   // operand might be an overloadable type, in which case the overload
4626   // resolution for the operator overload should get the first crack
4627   // at the overload.
4628   if (base->getType()->isNonOverloadPlaceholderType()) {
4629     IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4630     if (!IsMSPropertySubscript) {
4631       ExprResult result = CheckPlaceholderExpr(base);
4632       if (result.isInvalid())
4633         return ExprError();
4634       base = result.get();
4635     }
4636   }
4637   if (idx->getType()->isNonOverloadPlaceholderType()) {
4638     ExprResult result = CheckPlaceholderExpr(idx);
4639     if (result.isInvalid()) return ExprError();
4640     idx = result.get();
4641   }
4642 
4643   // Build an unanalyzed expression if either operand is type-dependent.
4644   if (getLangOpts().CPlusPlus &&
4645       (base->isTypeDependent() || idx->isTypeDependent())) {
4646     return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
4647                                             VK_LValue, OK_Ordinary, rbLoc);
4648   }
4649 
4650   // MSDN, property (C++)
4651   // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4652   // This attribute can also be used in the declaration of an empty array in a
4653   // class or structure definition. For example:
4654   // __declspec(property(get=GetX, put=PutX)) int x[];
4655   // The above statement indicates that x[] can be used with one or more array
4656   // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4657   // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4658   if (IsMSPropertySubscript) {
4659     // Build MS property subscript expression if base is MS property reference
4660     // or MS property subscript.
4661     return new (Context) MSPropertySubscriptExpr(
4662         base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
4663   }
4664 
4665   // Use C++ overloaded-operator rules if either operand has record
4666   // type.  The spec says to do this if either type is *overloadable*,
4667   // but enum types can't declare subscript operators or conversion
4668   // operators, so there's nothing interesting for overload resolution
4669   // to do if there aren't any record types involved.
4670   //
4671   // ObjC pointers have their own subscripting logic that is not tied
4672   // to overload resolution and so should not take this path.
4673   if (getLangOpts().CPlusPlus &&
4674       (base->getType()->isRecordType() ||
4675        (!base->getType()->isObjCObjectPointerType() &&
4676         idx->getType()->isRecordType()))) {
4677     return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
4678   }
4679 
4680   ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
4681 
4682   if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get()))
4683     CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get()));
4684 
4685   return Res;
4686 }
4687 
4688 ExprResult Sema::tryConvertExprToType(Expr *E, QualType Ty) {
4689   InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty);
4690   InitializationKind Kind =
4691       InitializationKind::CreateCopy(E->getBeginLoc(), SourceLocation());
4692   InitializationSequence InitSeq(*this, Entity, Kind, E);
4693   return InitSeq.Perform(*this, Entity, Kind, E);
4694 }
4695 
4696 ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx,
4697                                                   Expr *ColumnIdx,
4698                                                   SourceLocation RBLoc) {
4699   ExprResult BaseR = CheckPlaceholderExpr(Base);
4700   if (BaseR.isInvalid())
4701     return BaseR;
4702   Base = BaseR.get();
4703 
4704   ExprResult RowR = CheckPlaceholderExpr(RowIdx);
4705   if (RowR.isInvalid())
4706     return RowR;
4707   RowIdx = RowR.get();
4708 
4709   if (!ColumnIdx)
4710     return new (Context) MatrixSubscriptExpr(
4711         Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc);
4712 
4713   // Build an unanalyzed expression if any of the operands is type-dependent.
4714   if (Base->isTypeDependent() || RowIdx->isTypeDependent() ||
4715       ColumnIdx->isTypeDependent())
4716     return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
4717                                              Context.DependentTy, RBLoc);
4718 
4719   ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx);
4720   if (ColumnR.isInvalid())
4721     return ColumnR;
4722   ColumnIdx = ColumnR.get();
4723 
4724   // Check that IndexExpr is an integer expression. If it is a constant
4725   // expression, check that it is less than Dim (= the number of elements in the
4726   // corresponding dimension).
4727   auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim,
4728                           bool IsColumnIdx) -> Expr * {
4729     if (!IndexExpr->getType()->isIntegerType() &&
4730         !IndexExpr->isTypeDependent()) {
4731       Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer)
4732           << IsColumnIdx;
4733       return nullptr;
4734     }
4735 
4736     llvm::APSInt Idx;
4737     if (IndexExpr->isIntegerConstantExpr(Idx, Context) &&
4738         (Idx < 0 || Idx >= Dim)) {
4739       Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range)
4740           << IsColumnIdx << Dim;
4741       return nullptr;
4742     }
4743 
4744     ExprResult ConvExpr =
4745         tryConvertExprToType(IndexExpr, Context.getSizeType());
4746     assert(!ConvExpr.isInvalid() &&
4747            "should be able to convert any integer type to size type");
4748     return ConvExpr.get();
4749   };
4750 
4751   auto *MTy = Base->getType()->getAs<ConstantMatrixType>();
4752   RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false);
4753   ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true);
4754   if (!RowIdx || !ColumnIdx)
4755     return ExprError();
4756 
4757   return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
4758                                            MTy->getElementType(), RBLoc);
4759 }
4760 
4761 void Sema::CheckAddressOfNoDeref(const Expr *E) {
4762   ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4763   const Expr *StrippedExpr = E->IgnoreParenImpCasts();
4764 
4765   // For expressions like `&(*s).b`, the base is recorded and what should be
4766   // checked.
4767   const MemberExpr *Member = nullptr;
4768   while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow())
4769     StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
4770 
4771   LastRecord.PossibleDerefs.erase(StrippedExpr);
4772 }
4773 
4774 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
4775   QualType ResultTy = E->getType();
4776   ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4777 
4778   // Bail if the element is an array since it is not memory access.
4779   if (isa<ArrayType>(ResultTy))
4780     return;
4781 
4782   if (ResultTy->hasAttr(attr::NoDeref)) {
4783     LastRecord.PossibleDerefs.insert(E);
4784     return;
4785   }
4786 
4787   // Check if the base type is a pointer to a member access of a struct
4788   // marked with noderef.
4789   const Expr *Base = E->getBase();
4790   QualType BaseTy = Base->getType();
4791   if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy)))
4792     // Not a pointer access
4793     return;
4794 
4795   const MemberExpr *Member = nullptr;
4796   while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) &&
4797          Member->isArrow())
4798     Base = Member->getBase();
4799 
4800   if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) {
4801     if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))
4802       LastRecord.PossibleDerefs.insert(E);
4803   }
4804 }
4805 
4806 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4807                                           Expr *LowerBound,
4808                                           SourceLocation ColonLoc, Expr *Length,
4809                                           SourceLocation RBLoc) {
4810   if (Base->getType()->isPlaceholderType() &&
4811       !Base->getType()->isSpecificPlaceholderType(
4812           BuiltinType::OMPArraySection)) {
4813     ExprResult Result = CheckPlaceholderExpr(Base);
4814     if (Result.isInvalid())
4815       return ExprError();
4816     Base = Result.get();
4817   }
4818   if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
4819     ExprResult Result = CheckPlaceholderExpr(LowerBound);
4820     if (Result.isInvalid())
4821       return ExprError();
4822     Result = DefaultLvalueConversion(Result.get());
4823     if (Result.isInvalid())
4824       return ExprError();
4825     LowerBound = Result.get();
4826   }
4827   if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
4828     ExprResult Result = CheckPlaceholderExpr(Length);
4829     if (Result.isInvalid())
4830       return ExprError();
4831     Result = DefaultLvalueConversion(Result.get());
4832     if (Result.isInvalid())
4833       return ExprError();
4834     Length = Result.get();
4835   }
4836 
4837   // Build an unanalyzed expression if either operand is type-dependent.
4838   if (Base->isTypeDependent() ||
4839       (LowerBound &&
4840        (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
4841       (Length && (Length->isTypeDependent() || Length->isValueDependent()))) {
4842     return new (Context)
4843         OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy,
4844                             VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4845   }
4846 
4847   // Perform default conversions.
4848   QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
4849   QualType ResultTy;
4850   if (OriginalTy->isAnyPointerType()) {
4851     ResultTy = OriginalTy->getPointeeType();
4852   } else if (OriginalTy->isArrayType()) {
4853     ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
4854   } else {
4855     return ExprError(
4856         Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
4857         << Base->getSourceRange());
4858   }
4859   // C99 6.5.2.1p1
4860   if (LowerBound) {
4861     auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
4862                                                       LowerBound);
4863     if (Res.isInvalid())
4864       return ExprError(Diag(LowerBound->getExprLoc(),
4865                             diag::err_omp_typecheck_section_not_integer)
4866                        << 0 << LowerBound->getSourceRange());
4867     LowerBound = Res.get();
4868 
4869     if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4870         LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4871       Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
4872           << 0 << LowerBound->getSourceRange();
4873   }
4874   if (Length) {
4875     auto Res =
4876         PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
4877     if (Res.isInvalid())
4878       return ExprError(Diag(Length->getExprLoc(),
4879                             diag::err_omp_typecheck_section_not_integer)
4880                        << 1 << Length->getSourceRange());
4881     Length = Res.get();
4882 
4883     if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4884         Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4885       Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
4886           << 1 << Length->getSourceRange();
4887   }
4888 
4889   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4890   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4891   // type. Note that functions are not objects, and that (in C99 parlance)
4892   // incomplete types are not object types.
4893   if (ResultTy->isFunctionType()) {
4894     Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
4895         << ResultTy << Base->getSourceRange();
4896     return ExprError();
4897   }
4898 
4899   if (RequireCompleteType(Base->getExprLoc(), ResultTy,
4900                           diag::err_omp_section_incomplete_type, Base))
4901     return ExprError();
4902 
4903   if (LowerBound && !OriginalTy->isAnyPointerType()) {
4904     Expr::EvalResult Result;
4905     if (LowerBound->EvaluateAsInt(Result, Context)) {
4906       // OpenMP 4.5, [2.4 Array Sections]
4907       // The array section must be a subset of the original array.
4908       llvm::APSInt LowerBoundValue = Result.Val.getInt();
4909       if (LowerBoundValue.isNegative()) {
4910         Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
4911             << LowerBound->getSourceRange();
4912         return ExprError();
4913       }
4914     }
4915   }
4916 
4917   if (Length) {
4918     Expr::EvalResult Result;
4919     if (Length->EvaluateAsInt(Result, Context)) {
4920       // OpenMP 4.5, [2.4 Array Sections]
4921       // The length must evaluate to non-negative integers.
4922       llvm::APSInt LengthValue = Result.Val.getInt();
4923       if (LengthValue.isNegative()) {
4924         Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
4925             << LengthValue.toString(/*Radix=*/10, /*Signed=*/true)
4926             << Length->getSourceRange();
4927         return ExprError();
4928       }
4929     }
4930   } else if (ColonLoc.isValid() &&
4931              (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
4932                                       !OriginalTy->isVariableArrayType()))) {
4933     // OpenMP 4.5, [2.4 Array Sections]
4934     // When the size of the array dimension is not known, the length must be
4935     // specified explicitly.
4936     Diag(ColonLoc, diag::err_omp_section_length_undefined)
4937         << (!OriginalTy.isNull() && OriginalTy->isArrayType());
4938     return ExprError();
4939   }
4940 
4941   if (!Base->getType()->isSpecificPlaceholderType(
4942           BuiltinType::OMPArraySection)) {
4943     ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
4944     if (Result.isInvalid())
4945       return ExprError();
4946     Base = Result.get();
4947   }
4948   return new (Context)
4949       OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy,
4950                           VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4951 }
4952 
4953 ExprResult Sema::ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc,
4954                                           SourceLocation RParenLoc,
4955                                           ArrayRef<Expr *> Dims,
4956                                           ArrayRef<SourceRange> Brackets) {
4957   if (Base->getType()->isPlaceholderType()) {
4958     ExprResult Result = CheckPlaceholderExpr(Base);
4959     if (Result.isInvalid())
4960       return ExprError();
4961     Result = DefaultLvalueConversion(Result.get());
4962     if (Result.isInvalid())
4963       return ExprError();
4964     Base = Result.get();
4965   }
4966   QualType BaseTy = Base->getType();
4967   // Delay analysis of the types/expressions if instantiation/specialization is
4968   // required.
4969   if (!BaseTy->isPointerType() && Base->isTypeDependent())
4970     return OMPArrayShapingExpr::Create(Context, Context.DependentTy, Base,
4971                                        LParenLoc, RParenLoc, Dims, Brackets);
4972   if (!BaseTy->isPointerType() ||
4973       (!Base->isTypeDependent() &&
4974        BaseTy->getPointeeType()->isIncompleteType()))
4975     return ExprError(Diag(Base->getExprLoc(),
4976                           diag::err_omp_non_pointer_type_array_shaping_base)
4977                      << Base->getSourceRange());
4978 
4979   SmallVector<Expr *, 4> NewDims;
4980   bool ErrorFound = false;
4981   for (Expr *Dim : Dims) {
4982     if (Dim->getType()->isPlaceholderType()) {
4983       ExprResult Result = CheckPlaceholderExpr(Dim);
4984       if (Result.isInvalid()) {
4985         ErrorFound = true;
4986         continue;
4987       }
4988       Result = DefaultLvalueConversion(Result.get());
4989       if (Result.isInvalid()) {
4990         ErrorFound = true;
4991         continue;
4992       }
4993       Dim = Result.get();
4994     }
4995     if (!Dim->isTypeDependent()) {
4996       ExprResult Result =
4997           PerformOpenMPImplicitIntegerConversion(Dim->getExprLoc(), Dim);
4998       if (Result.isInvalid()) {
4999         ErrorFound = true;
5000         Diag(Dim->getExprLoc(), diag::err_omp_typecheck_shaping_not_integer)
5001             << Dim->getSourceRange();
5002         continue;
5003       }
5004       Dim = Result.get();
5005       Expr::EvalResult EvResult;
5006       if (!Dim->isValueDependent() && Dim->EvaluateAsInt(EvResult, Context)) {
5007         // OpenMP 5.0, [2.1.4 Array Shaping]
5008         // Each si is an integral type expression that must evaluate to a
5009         // positive integer.
5010         llvm::APSInt Value = EvResult.Val.getInt();
5011         if (!Value.isStrictlyPositive()) {
5012           Diag(Dim->getExprLoc(), diag::err_omp_shaping_dimension_not_positive)
5013               << Value.toString(/*Radix=*/10, /*Signed=*/true)
5014               << Dim->getSourceRange();
5015           ErrorFound = true;
5016           continue;
5017         }
5018       }
5019     }
5020     NewDims.push_back(Dim);
5021   }
5022   if (ErrorFound)
5023     return ExprError();
5024   return OMPArrayShapingExpr::Create(Context, Context.OMPArrayShapingTy, Base,
5025                                      LParenLoc, RParenLoc, NewDims, Brackets);
5026 }
5027 
5028 ExprResult Sema::ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc,
5029                                       SourceLocation LLoc, SourceLocation RLoc,
5030                                       ArrayRef<OMPIteratorData> Data) {
5031   SmallVector<OMPIteratorExpr::IteratorDefinition, 4> ID;
5032   bool IsCorrect = true;
5033   for (const OMPIteratorData &D : Data) {
5034     TypeSourceInfo *TInfo = nullptr;
5035     SourceLocation StartLoc;
5036     QualType DeclTy;
5037     if (!D.Type.getAsOpaquePtr()) {
5038       // OpenMP 5.0, 2.1.6 Iterators
5039       // In an iterator-specifier, if the iterator-type is not specified then
5040       // the type of that iterator is of int type.
5041       DeclTy = Context.IntTy;
5042       StartLoc = D.DeclIdentLoc;
5043     } else {
5044       DeclTy = GetTypeFromParser(D.Type, &TInfo);
5045       StartLoc = TInfo->getTypeLoc().getBeginLoc();
5046     }
5047 
5048     bool IsDeclTyDependent = DeclTy->isDependentType() ||
5049                              DeclTy->containsUnexpandedParameterPack() ||
5050                              DeclTy->isInstantiationDependentType();
5051     if (!IsDeclTyDependent) {
5052       if (!DeclTy->isIntegralType(Context) && !DeclTy->isAnyPointerType()) {
5053         // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++
5054         // The iterator-type must be an integral or pointer type.
5055         Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer)
5056             << DeclTy;
5057         IsCorrect = false;
5058         continue;
5059       }
5060       if (DeclTy.isConstant(Context)) {
5061         // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++
5062         // The iterator-type must not be const qualified.
5063         Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer)
5064             << DeclTy;
5065         IsCorrect = false;
5066         continue;
5067       }
5068     }
5069 
5070     // Iterator declaration.
5071     assert(D.DeclIdent && "Identifier expected.");
5072     // Always try to create iterator declarator to avoid extra error messages
5073     // about unknown declarations use.
5074     auto *VD = VarDecl::Create(Context, CurContext, StartLoc, D.DeclIdentLoc,
5075                                D.DeclIdent, DeclTy, TInfo, SC_None);
5076     VD->setImplicit();
5077     if (S) {
5078       // Check for conflicting previous declaration.
5079       DeclarationNameInfo NameInfo(VD->getDeclName(), D.DeclIdentLoc);
5080       LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5081                             ForVisibleRedeclaration);
5082       Previous.suppressDiagnostics();
5083       LookupName(Previous, S);
5084 
5085       FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false,
5086                            /*AllowInlineNamespace=*/false);
5087       if (!Previous.empty()) {
5088         NamedDecl *Old = Previous.getRepresentativeDecl();
5089         Diag(D.DeclIdentLoc, diag::err_redefinition) << VD->getDeclName();
5090         Diag(Old->getLocation(), diag::note_previous_definition);
5091       } else {
5092         PushOnScopeChains(VD, S);
5093       }
5094     } else {
5095       CurContext->addDecl(VD);
5096     }
5097     Expr *Begin = D.Range.Begin;
5098     if (!IsDeclTyDependent && Begin && !Begin->isTypeDependent()) {
5099       ExprResult BeginRes =
5100           PerformImplicitConversion(Begin, DeclTy, AA_Converting);
5101       Begin = BeginRes.get();
5102     }
5103     Expr *End = D.Range.End;
5104     if (!IsDeclTyDependent && End && !End->isTypeDependent()) {
5105       ExprResult EndRes = PerformImplicitConversion(End, DeclTy, AA_Converting);
5106       End = EndRes.get();
5107     }
5108     Expr *Step = D.Range.Step;
5109     if (!IsDeclTyDependent && Step && !Step->isTypeDependent()) {
5110       if (!Step->getType()->isIntegralType(Context)) {
5111         Diag(Step->getExprLoc(), diag::err_omp_iterator_step_not_integral)
5112             << Step << Step->getSourceRange();
5113         IsCorrect = false;
5114         continue;
5115       }
5116       llvm::APSInt Result;
5117       bool IsConstant = Step->isIntegerConstantExpr(Result, Context);
5118       // OpenMP 5.0, 2.1.6 Iterators, Restrictions
5119       // If the step expression of a range-specification equals zero, the
5120       // behavior is unspecified.
5121       if (IsConstant && Result.isNullValue()) {
5122         Diag(Step->getExprLoc(), diag::err_omp_iterator_step_constant_zero)
5123             << Step << Step->getSourceRange();
5124         IsCorrect = false;
5125         continue;
5126       }
5127     }
5128     if (!Begin || !End || !IsCorrect) {
5129       IsCorrect = false;
5130       continue;
5131     }
5132     OMPIteratorExpr::IteratorDefinition &IDElem = ID.emplace_back();
5133     IDElem.IteratorDecl = VD;
5134     IDElem.AssignmentLoc = D.AssignLoc;
5135     IDElem.Range.Begin = Begin;
5136     IDElem.Range.End = End;
5137     IDElem.Range.Step = Step;
5138     IDElem.ColonLoc = D.ColonLoc;
5139     IDElem.SecondColonLoc = D.SecColonLoc;
5140   }
5141   if (!IsCorrect) {
5142     // Invalidate all created iterator declarations if error is found.
5143     for (const OMPIteratorExpr::IteratorDefinition &D : ID) {
5144       if (Decl *ID = D.IteratorDecl)
5145         ID->setInvalidDecl();
5146     }
5147     return ExprError();
5148   }
5149   SmallVector<OMPIteratorHelperData, 4> Helpers;
5150   if (!CurContext->isDependentContext()) {
5151     // Build number of ityeration for each iteration range.
5152     // Ni = ((Stepi > 0) ? ((Endi + Stepi -1 - Begini)/Stepi) :
5153     // ((Begini-Stepi-1-Endi) / -Stepi);
5154     for (OMPIteratorExpr::IteratorDefinition &D : ID) {
5155       // (Endi - Begini)
5156       ExprResult Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, D.Range.End,
5157                                           D.Range.Begin);
5158       if(!Res.isUsable()) {
5159         IsCorrect = false;
5160         continue;
5161       }
5162       ExprResult St, St1;
5163       if (D.Range.Step) {
5164         St = D.Range.Step;
5165         // (Endi - Begini) + Stepi
5166         Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res.get(), St.get());
5167         if (!Res.isUsable()) {
5168           IsCorrect = false;
5169           continue;
5170         }
5171         // (Endi - Begini) + Stepi - 1
5172         Res =
5173             CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res.get(),
5174                                ActOnIntegerConstant(D.AssignmentLoc, 1).get());
5175         if (!Res.isUsable()) {
5176           IsCorrect = false;
5177           continue;
5178         }
5179         // ((Endi - Begini) + Stepi - 1) / Stepi
5180         Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res.get(), St.get());
5181         if (!Res.isUsable()) {
5182           IsCorrect = false;
5183           continue;
5184         }
5185         St1 = CreateBuiltinUnaryOp(D.AssignmentLoc, UO_Minus, D.Range.Step);
5186         // (Begini - Endi)
5187         ExprResult Res1 = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub,
5188                                              D.Range.Begin, D.Range.End);
5189         if (!Res1.isUsable()) {
5190           IsCorrect = false;
5191           continue;
5192         }
5193         // (Begini - Endi) - Stepi
5194         Res1 =
5195             CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res1.get(), St1.get());
5196         if (!Res1.isUsable()) {
5197           IsCorrect = false;
5198           continue;
5199         }
5200         // (Begini - Endi) - Stepi - 1
5201         Res1 =
5202             CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res1.get(),
5203                                ActOnIntegerConstant(D.AssignmentLoc, 1).get());
5204         if (!Res1.isUsable()) {
5205           IsCorrect = false;
5206           continue;
5207         }
5208         // ((Begini - Endi) - Stepi - 1) / (-Stepi)
5209         Res1 =
5210             CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res1.get(), St1.get());
5211         if (!Res1.isUsable()) {
5212           IsCorrect = false;
5213           continue;
5214         }
5215         // Stepi > 0.
5216         ExprResult CmpRes =
5217             CreateBuiltinBinOp(D.AssignmentLoc, BO_GT, D.Range.Step,
5218                                ActOnIntegerConstant(D.AssignmentLoc, 0).get());
5219         if (!CmpRes.isUsable()) {
5220           IsCorrect = false;
5221           continue;
5222         }
5223         Res = ActOnConditionalOp(D.AssignmentLoc, D.AssignmentLoc, CmpRes.get(),
5224                                  Res.get(), Res1.get());
5225         if (!Res.isUsable()) {
5226           IsCorrect = false;
5227           continue;
5228         }
5229       }
5230       Res = ActOnFinishFullExpr(Res.get(), /*DiscardedValue=*/false);
5231       if (!Res.isUsable()) {
5232         IsCorrect = false;
5233         continue;
5234       }
5235 
5236       // Build counter update.
5237       // Build counter.
5238       auto *CounterVD =
5239           VarDecl::Create(Context, CurContext, D.IteratorDecl->getBeginLoc(),
5240                           D.IteratorDecl->getBeginLoc(), nullptr,
5241                           Res.get()->getType(), nullptr, SC_None);
5242       CounterVD->setImplicit();
5243       ExprResult RefRes =
5244           BuildDeclRefExpr(CounterVD, CounterVD->getType(), VK_LValue,
5245                            D.IteratorDecl->getBeginLoc());
5246       // Build counter update.
5247       // I = Begini + counter * Stepi;
5248       ExprResult UpdateRes;
5249       if (D.Range.Step) {
5250         UpdateRes = CreateBuiltinBinOp(
5251             D.AssignmentLoc, BO_Mul,
5252             DefaultLvalueConversion(RefRes.get()).get(), St.get());
5253       } else {
5254         UpdateRes = DefaultLvalueConversion(RefRes.get());
5255       }
5256       if (!UpdateRes.isUsable()) {
5257         IsCorrect = false;
5258         continue;
5259       }
5260       UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, D.Range.Begin,
5261                                      UpdateRes.get());
5262       if (!UpdateRes.isUsable()) {
5263         IsCorrect = false;
5264         continue;
5265       }
5266       ExprResult VDRes =
5267           BuildDeclRefExpr(cast<VarDecl>(D.IteratorDecl),
5268                            cast<VarDecl>(D.IteratorDecl)->getType(), VK_LValue,
5269                            D.IteratorDecl->getBeginLoc());
5270       UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Assign, VDRes.get(),
5271                                      UpdateRes.get());
5272       if (!UpdateRes.isUsable()) {
5273         IsCorrect = false;
5274         continue;
5275       }
5276       UpdateRes =
5277           ActOnFinishFullExpr(UpdateRes.get(), /*DiscardedValue=*/true);
5278       if (!UpdateRes.isUsable()) {
5279         IsCorrect = false;
5280         continue;
5281       }
5282       ExprResult CounterUpdateRes =
5283           CreateBuiltinUnaryOp(D.AssignmentLoc, UO_PreInc, RefRes.get());
5284       if (!CounterUpdateRes.isUsable()) {
5285         IsCorrect = false;
5286         continue;
5287       }
5288       CounterUpdateRes =
5289           ActOnFinishFullExpr(CounterUpdateRes.get(), /*DiscardedValue=*/true);
5290       if (!CounterUpdateRes.isUsable()) {
5291         IsCorrect = false;
5292         continue;
5293       }
5294       OMPIteratorHelperData &HD = Helpers.emplace_back();
5295       HD.CounterVD = CounterVD;
5296       HD.Upper = Res.get();
5297       HD.Update = UpdateRes.get();
5298       HD.CounterUpdate = CounterUpdateRes.get();
5299     }
5300   } else {
5301     Helpers.assign(ID.size(), {});
5302   }
5303   if (!IsCorrect) {
5304     // Invalidate all created iterator declarations if error is found.
5305     for (const OMPIteratorExpr::IteratorDefinition &D : ID) {
5306       if (Decl *ID = D.IteratorDecl)
5307         ID->setInvalidDecl();
5308     }
5309     return ExprError();
5310   }
5311   return OMPIteratorExpr::Create(Context, Context.OMPIteratorTy, IteratorKwLoc,
5312                                  LLoc, RLoc, ID, Helpers);
5313 }
5314 
5315 ExprResult
5316 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
5317                                       Expr *Idx, SourceLocation RLoc) {
5318   Expr *LHSExp = Base;
5319   Expr *RHSExp = Idx;
5320 
5321   ExprValueKind VK = VK_LValue;
5322   ExprObjectKind OK = OK_Ordinary;
5323 
5324   // Per C++ core issue 1213, the result is an xvalue if either operand is
5325   // a non-lvalue array, and an lvalue otherwise.
5326   if (getLangOpts().CPlusPlus11) {
5327     for (auto *Op : {LHSExp, RHSExp}) {
5328       Op = Op->IgnoreImplicit();
5329       if (Op->getType()->isArrayType() && !Op->isLValue())
5330         VK = VK_XValue;
5331     }
5332   }
5333 
5334   // Perform default conversions.
5335   if (!LHSExp->getType()->getAs<VectorType>()) {
5336     ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
5337     if (Result.isInvalid())
5338       return ExprError();
5339     LHSExp = Result.get();
5340   }
5341   ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
5342   if (Result.isInvalid())
5343     return ExprError();
5344   RHSExp = Result.get();
5345 
5346   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
5347 
5348   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
5349   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
5350   // in the subscript position. As a result, we need to derive the array base
5351   // and index from the expression types.
5352   Expr *BaseExpr, *IndexExpr;
5353   QualType ResultType;
5354   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
5355     BaseExpr = LHSExp;
5356     IndexExpr = RHSExp;
5357     ResultType = Context.DependentTy;
5358   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
5359     BaseExpr = LHSExp;
5360     IndexExpr = RHSExp;
5361     ResultType = PTy->getPointeeType();
5362   } else if (const ObjCObjectPointerType *PTy =
5363                LHSTy->getAs<ObjCObjectPointerType>()) {
5364     BaseExpr = LHSExp;
5365     IndexExpr = RHSExp;
5366 
5367     // Use custom logic if this should be the pseudo-object subscript
5368     // expression.
5369     if (!LangOpts.isSubscriptPointerArithmetic())
5370       return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
5371                                           nullptr);
5372 
5373     ResultType = PTy->getPointeeType();
5374   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
5375      // Handle the uncommon case of "123[Ptr]".
5376     BaseExpr = RHSExp;
5377     IndexExpr = LHSExp;
5378     ResultType = PTy->getPointeeType();
5379   } else if (const ObjCObjectPointerType *PTy =
5380                RHSTy->getAs<ObjCObjectPointerType>()) {
5381      // Handle the uncommon case of "123[Ptr]".
5382     BaseExpr = RHSExp;
5383     IndexExpr = LHSExp;
5384     ResultType = PTy->getPointeeType();
5385     if (!LangOpts.isSubscriptPointerArithmetic()) {
5386       Diag(LLoc, diag::err_subscript_nonfragile_interface)
5387         << ResultType << BaseExpr->getSourceRange();
5388       return ExprError();
5389     }
5390   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
5391     BaseExpr = LHSExp;    // vectors: V[123]
5392     IndexExpr = RHSExp;
5393     // We apply C++ DR1213 to vector subscripting too.
5394     if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_RValue) {
5395       ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
5396       if (Materialized.isInvalid())
5397         return ExprError();
5398       LHSExp = Materialized.get();
5399     }
5400     VK = LHSExp->getValueKind();
5401     if (VK != VK_RValue)
5402       OK = OK_VectorComponent;
5403 
5404     ResultType = VTy->getElementType();
5405     QualType BaseType = BaseExpr->getType();
5406     Qualifiers BaseQuals = BaseType.getQualifiers();
5407     Qualifiers MemberQuals = ResultType.getQualifiers();
5408     Qualifiers Combined = BaseQuals + MemberQuals;
5409     if (Combined != MemberQuals)
5410       ResultType = Context.getQualifiedType(ResultType, Combined);
5411   } else if (LHSTy->isArrayType()) {
5412     // If we see an array that wasn't promoted by
5413     // DefaultFunctionArrayLvalueConversion, it must be an array that
5414     // wasn't promoted because of the C90 rule that doesn't
5415     // allow promoting non-lvalue arrays.  Warn, then
5416     // force the promotion here.
5417     Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5418         << LHSExp->getSourceRange();
5419     LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
5420                                CK_ArrayToPointerDecay).get();
5421     LHSTy = LHSExp->getType();
5422 
5423     BaseExpr = LHSExp;
5424     IndexExpr = RHSExp;
5425     ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
5426   } else if (RHSTy->isArrayType()) {
5427     // Same as previous, except for 123[f().a] case
5428     Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5429         << RHSExp->getSourceRange();
5430     RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
5431                                CK_ArrayToPointerDecay).get();
5432     RHSTy = RHSExp->getType();
5433 
5434     BaseExpr = RHSExp;
5435     IndexExpr = LHSExp;
5436     ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
5437   } else {
5438     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
5439        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
5440   }
5441   // C99 6.5.2.1p1
5442   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
5443     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
5444                      << IndexExpr->getSourceRange());
5445 
5446   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5447        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5448          && !IndexExpr->isTypeDependent())
5449     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
5450 
5451   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5452   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5453   // type. Note that Functions are not objects, and that (in C99 parlance)
5454   // incomplete types are not object types.
5455   if (ResultType->isFunctionType()) {
5456     Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type)
5457         << ResultType << BaseExpr->getSourceRange();
5458     return ExprError();
5459   }
5460 
5461   if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
5462     // GNU extension: subscripting on pointer to void
5463     Diag(LLoc, diag::ext_gnu_subscript_void_type)
5464       << BaseExpr->getSourceRange();
5465 
5466     // C forbids expressions of unqualified void type from being l-values.
5467     // See IsCForbiddenLValueType.
5468     if (!ResultType.hasQualifiers()) VK = VK_RValue;
5469   } else if (!ResultType->isDependentType() &&
5470              RequireCompleteSizedType(
5471                  LLoc, ResultType,
5472                  diag::err_subscript_incomplete_or_sizeless_type, BaseExpr))
5473     return ExprError();
5474 
5475   assert(VK == VK_RValue || LangOpts.CPlusPlus ||
5476          !ResultType.isCForbiddenLValueType());
5477 
5478   if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() &&
5479       FunctionScopes.size() > 1) {
5480     if (auto *TT =
5481             LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) {
5482       for (auto I = FunctionScopes.rbegin(),
5483                 E = std::prev(FunctionScopes.rend());
5484            I != E; ++I) {
5485         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
5486         if (CSI == nullptr)
5487           break;
5488         DeclContext *DC = nullptr;
5489         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
5490           DC = LSI->CallOperator;
5491         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
5492           DC = CRSI->TheCapturedDecl;
5493         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
5494           DC = BSI->TheDecl;
5495         if (DC) {
5496           if (DC->containsDecl(TT->getDecl()))
5497             break;
5498           captureVariablyModifiedType(
5499               Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI);
5500         }
5501       }
5502     }
5503   }
5504 
5505   return new (Context)
5506       ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
5507 }
5508 
5509 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
5510                                   ParmVarDecl *Param) {
5511   if (Param->hasUnparsedDefaultArg()) {
5512     // If we've already cleared out the location for the default argument,
5513     // that means we're parsing it right now.
5514     if (!UnparsedDefaultArgLocs.count(Param)) {
5515       Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
5516       Diag(CallLoc, diag::note_recursive_default_argument_used_here);
5517       Param->setInvalidDecl();
5518       return true;
5519     }
5520 
5521     Diag(CallLoc,
5522          diag::err_use_of_default_argument_to_function_declared_later) <<
5523       FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
5524     Diag(UnparsedDefaultArgLocs[Param],
5525          diag::note_default_argument_declared_here);
5526     return true;
5527   }
5528 
5529   if (Param->hasUninstantiatedDefaultArg()) {
5530     Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
5531 
5532     EnterExpressionEvaluationContext EvalContext(
5533         *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
5534 
5535     // Instantiate the expression.
5536     //
5537     // FIXME: Pass in a correct Pattern argument, otherwise
5538     // getTemplateInstantiationArgs uses the lexical context of FD, e.g.
5539     //
5540     // template<typename T>
5541     // struct A {
5542     //   static int FooImpl();
5543     //
5544     //   template<typename Tp>
5545     //   // bug: default argument A<T>::FooImpl() is evaluated with 2-level
5546     //   // template argument list [[T], [Tp]], should be [[Tp]].
5547     //   friend A<Tp> Foo(int a);
5548     // };
5549     //
5550     // template<typename T>
5551     // A<T> Foo(int a = A<T>::FooImpl());
5552     MultiLevelTemplateArgumentList MutiLevelArgList
5553       = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true);
5554 
5555     InstantiatingTemplate Inst(*this, CallLoc, Param,
5556                                MutiLevelArgList.getInnermost());
5557     if (Inst.isInvalid())
5558       return true;
5559     if (Inst.isAlreadyInstantiating()) {
5560       Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
5561       Param->setInvalidDecl();
5562       return true;
5563     }
5564 
5565     ExprResult Result;
5566     {
5567       // C++ [dcl.fct.default]p5:
5568       //   The names in the [default argument] expression are bound, and
5569       //   the semantic constraints are checked, at the point where the
5570       //   default argument expression appears.
5571       ContextRAII SavedContext(*this, FD);
5572       LocalInstantiationScope Local(*this);
5573       runWithSufficientStackSpace(CallLoc, [&] {
5574         Result = SubstInitializer(UninstExpr, MutiLevelArgList,
5575                                   /*DirectInit*/false);
5576       });
5577     }
5578     if (Result.isInvalid())
5579       return true;
5580 
5581     // Check the expression as an initializer for the parameter.
5582     InitializedEntity Entity
5583       = InitializedEntity::InitializeParameter(Context, Param);
5584     InitializationKind Kind = InitializationKind::CreateCopy(
5585         Param->getLocation(),
5586         /*FIXME:EqualLoc*/ UninstExpr->getBeginLoc());
5587     Expr *ResultE = Result.getAs<Expr>();
5588 
5589     InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
5590     Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
5591     if (Result.isInvalid())
5592       return true;
5593 
5594     Result =
5595         ActOnFinishFullExpr(Result.getAs<Expr>(), Param->getOuterLocStart(),
5596                             /*DiscardedValue*/ false);
5597     if (Result.isInvalid())
5598       return true;
5599 
5600     // Remember the instantiated default argument.
5601     Param->setDefaultArg(Result.getAs<Expr>());
5602     if (ASTMutationListener *L = getASTMutationListener()) {
5603       L->DefaultArgumentInstantiated(Param);
5604     }
5605   }
5606 
5607   assert(Param->hasInit() && "default argument but no initializer?");
5608 
5609   // If the default expression creates temporaries, we need to
5610   // push them to the current stack of expression temporaries so they'll
5611   // be properly destroyed.
5612   // FIXME: We should really be rebuilding the default argument with new
5613   // bound temporaries; see the comment in PR5810.
5614   // We don't need to do that with block decls, though, because
5615   // blocks in default argument expression can never capture anything.
5616   if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
5617     // Set the "needs cleanups" bit regardless of whether there are
5618     // any explicit objects.
5619     Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
5620 
5621     // Append all the objects to the cleanup list.  Right now, this
5622     // should always be a no-op, because blocks in default argument
5623     // expressions should never be able to capture anything.
5624     assert(!Init->getNumObjects() &&
5625            "default argument expression has capturing blocks?");
5626   }
5627 
5628   // We already type-checked the argument, so we know it works.
5629   // Just mark all of the declarations in this potentially-evaluated expression
5630   // as being "referenced".
5631   EnterExpressionEvaluationContext EvalContext(
5632       *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
5633   MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
5634                                    /*SkipLocalVariables=*/true);
5635   return false;
5636 }
5637 
5638 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
5639                                         FunctionDecl *FD, ParmVarDecl *Param) {
5640   assert(Param->hasDefaultArg() && "can't build nonexistent default arg");
5641   if (CheckCXXDefaultArgExpr(CallLoc, FD, Param))
5642     return ExprError();
5643   return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext);
5644 }
5645 
5646 Sema::VariadicCallType
5647 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
5648                           Expr *Fn) {
5649   if (Proto && Proto->isVariadic()) {
5650     if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
5651       return VariadicConstructor;
5652     else if (Fn && Fn->getType()->isBlockPointerType())
5653       return VariadicBlock;
5654     else if (FDecl) {
5655       if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5656         if (Method->isInstance())
5657           return VariadicMethod;
5658     } else if (Fn && Fn->getType() == Context.BoundMemberTy)
5659       return VariadicMethod;
5660     return VariadicFunction;
5661   }
5662   return VariadicDoesNotApply;
5663 }
5664 
5665 namespace {
5666 class FunctionCallCCC final : public FunctionCallFilterCCC {
5667 public:
5668   FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
5669                   unsigned NumArgs, MemberExpr *ME)
5670       : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
5671         FunctionName(FuncName) {}
5672 
5673   bool ValidateCandidate(const TypoCorrection &candidate) override {
5674     if (!candidate.getCorrectionSpecifier() ||
5675         candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
5676       return false;
5677     }
5678 
5679     return FunctionCallFilterCCC::ValidateCandidate(candidate);
5680   }
5681 
5682   std::unique_ptr<CorrectionCandidateCallback> clone() override {
5683     return std::make_unique<FunctionCallCCC>(*this);
5684   }
5685 
5686 private:
5687   const IdentifierInfo *const FunctionName;
5688 };
5689 }
5690 
5691 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
5692                                                FunctionDecl *FDecl,
5693                                                ArrayRef<Expr *> Args) {
5694   MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
5695   DeclarationName FuncName = FDecl->getDeclName();
5696   SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
5697 
5698   FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
5699   if (TypoCorrection Corrected = S.CorrectTypo(
5700           DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
5701           S.getScopeForContext(S.CurContext), nullptr, CCC,
5702           Sema::CTK_ErrorRecovery)) {
5703     if (NamedDecl *ND = Corrected.getFoundDecl()) {
5704       if (Corrected.isOverloaded()) {
5705         OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
5706         OverloadCandidateSet::iterator Best;
5707         for (NamedDecl *CD : Corrected) {
5708           if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
5709             S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
5710                                    OCS);
5711         }
5712         switch (OCS.BestViableFunction(S, NameLoc, Best)) {
5713         case OR_Success:
5714           ND = Best->FoundDecl;
5715           Corrected.setCorrectionDecl(ND);
5716           break;
5717         default:
5718           break;
5719         }
5720       }
5721       ND = ND->getUnderlyingDecl();
5722       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
5723         return Corrected;
5724     }
5725   }
5726   return TypoCorrection();
5727 }
5728 
5729 /// ConvertArgumentsForCall - Converts the arguments specified in
5730 /// Args/NumArgs to the parameter types of the function FDecl with
5731 /// function prototype Proto. Call is the call expression itself, and
5732 /// Fn is the function expression. For a C++ member function, this
5733 /// routine does not attempt to convert the object argument. Returns
5734 /// true if the call is ill-formed.
5735 bool
5736 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
5737                               FunctionDecl *FDecl,
5738                               const FunctionProtoType *Proto,
5739                               ArrayRef<Expr *> Args,
5740                               SourceLocation RParenLoc,
5741                               bool IsExecConfig) {
5742   // Bail out early if calling a builtin with custom typechecking.
5743   if (FDecl)
5744     if (unsigned ID = FDecl->getBuiltinID())
5745       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
5746         return false;
5747 
5748   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
5749   // assignment, to the types of the corresponding parameter, ...
5750   unsigned NumParams = Proto->getNumParams();
5751   bool Invalid = false;
5752   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
5753   unsigned FnKind = Fn->getType()->isBlockPointerType()
5754                        ? 1 /* block */
5755                        : (IsExecConfig ? 3 /* kernel function (exec config) */
5756                                        : 0 /* function */);
5757 
5758   // If too few arguments are available (and we don't have default
5759   // arguments for the remaining parameters), don't make the call.
5760   if (Args.size() < NumParams) {
5761     if (Args.size() < MinArgs) {
5762       TypoCorrection TC;
5763       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5764         unsigned diag_id =
5765             MinArgs == NumParams && !Proto->isVariadic()
5766                 ? diag::err_typecheck_call_too_few_args_suggest
5767                 : diag::err_typecheck_call_too_few_args_at_least_suggest;
5768         diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
5769                                         << static_cast<unsigned>(Args.size())
5770                                         << TC.getCorrectionRange());
5771       } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
5772         Diag(RParenLoc,
5773              MinArgs == NumParams && !Proto->isVariadic()
5774                  ? diag::err_typecheck_call_too_few_args_one
5775                  : diag::err_typecheck_call_too_few_args_at_least_one)
5776             << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
5777       else
5778         Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
5779                             ? diag::err_typecheck_call_too_few_args
5780                             : diag::err_typecheck_call_too_few_args_at_least)
5781             << FnKind << MinArgs << static_cast<unsigned>(Args.size())
5782             << Fn->getSourceRange();
5783 
5784       // Emit the location of the prototype.
5785       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5786         Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
5787 
5788       return true;
5789     }
5790     // We reserve space for the default arguments when we create
5791     // the call expression, before calling ConvertArgumentsForCall.
5792     assert((Call->getNumArgs() == NumParams) &&
5793            "We should have reserved space for the default arguments before!");
5794   }
5795 
5796   // If too many are passed and not variadic, error on the extras and drop
5797   // them.
5798   if (Args.size() > NumParams) {
5799     if (!Proto->isVariadic()) {
5800       TypoCorrection TC;
5801       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5802         unsigned diag_id =
5803             MinArgs == NumParams && !Proto->isVariadic()
5804                 ? diag::err_typecheck_call_too_many_args_suggest
5805                 : diag::err_typecheck_call_too_many_args_at_most_suggest;
5806         diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
5807                                         << static_cast<unsigned>(Args.size())
5808                                         << TC.getCorrectionRange());
5809       } else if (NumParams == 1 && FDecl &&
5810                  FDecl->getParamDecl(0)->getDeclName())
5811         Diag(Args[NumParams]->getBeginLoc(),
5812              MinArgs == NumParams
5813                  ? diag::err_typecheck_call_too_many_args_one
5814                  : diag::err_typecheck_call_too_many_args_at_most_one)
5815             << FnKind << FDecl->getParamDecl(0)
5816             << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
5817             << SourceRange(Args[NumParams]->getBeginLoc(),
5818                            Args.back()->getEndLoc());
5819       else
5820         Diag(Args[NumParams]->getBeginLoc(),
5821              MinArgs == NumParams
5822                  ? diag::err_typecheck_call_too_many_args
5823                  : diag::err_typecheck_call_too_many_args_at_most)
5824             << FnKind << NumParams << static_cast<unsigned>(Args.size())
5825             << Fn->getSourceRange()
5826             << SourceRange(Args[NumParams]->getBeginLoc(),
5827                            Args.back()->getEndLoc());
5828 
5829       // Emit the location of the prototype.
5830       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5831         Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
5832 
5833       // This deletes the extra arguments.
5834       Call->shrinkNumArgs(NumParams);
5835       return true;
5836     }
5837   }
5838   SmallVector<Expr *, 8> AllArgs;
5839   VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
5840 
5841   Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args,
5842                                    AllArgs, CallType);
5843   if (Invalid)
5844     return true;
5845   unsigned TotalNumArgs = AllArgs.size();
5846   for (unsigned i = 0; i < TotalNumArgs; ++i)
5847     Call->setArg(i, AllArgs[i]);
5848 
5849   return false;
5850 }
5851 
5852 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
5853                                   const FunctionProtoType *Proto,
5854                                   unsigned FirstParam, ArrayRef<Expr *> Args,
5855                                   SmallVectorImpl<Expr *> &AllArgs,
5856                                   VariadicCallType CallType, bool AllowExplicit,
5857                                   bool IsListInitialization) {
5858   unsigned NumParams = Proto->getNumParams();
5859   bool Invalid = false;
5860   size_t ArgIx = 0;
5861   // Continue to check argument types (even if we have too few/many args).
5862   for (unsigned i = FirstParam; i < NumParams; i++) {
5863     QualType ProtoArgType = Proto->getParamType(i);
5864 
5865     Expr *Arg;
5866     ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
5867     if (ArgIx < Args.size()) {
5868       Arg = Args[ArgIx++];
5869 
5870       if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType,
5871                               diag::err_call_incomplete_argument, Arg))
5872         return true;
5873 
5874       // Strip the unbridged-cast placeholder expression off, if applicable.
5875       bool CFAudited = false;
5876       if (Arg->getType() == Context.ARCUnbridgedCastTy &&
5877           FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5878           (!Param || !Param->hasAttr<CFConsumedAttr>()))
5879         Arg = stripARCUnbridgedCast(Arg);
5880       else if (getLangOpts().ObjCAutoRefCount &&
5881                FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5882                (!Param || !Param->hasAttr<CFConsumedAttr>()))
5883         CFAudited = true;
5884 
5885       if (Proto->getExtParameterInfo(i).isNoEscape())
5886         if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
5887           BE->getBlockDecl()->setDoesNotEscape();
5888 
5889       InitializedEntity Entity =
5890           Param ? InitializedEntity::InitializeParameter(Context, Param,
5891                                                          ProtoArgType)
5892                 : InitializedEntity::InitializeParameter(
5893                       Context, ProtoArgType, Proto->isParamConsumed(i));
5894 
5895       // Remember that parameter belongs to a CF audited API.
5896       if (CFAudited)
5897         Entity.setParameterCFAudited();
5898 
5899       ExprResult ArgE = PerformCopyInitialization(
5900           Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
5901       if (ArgE.isInvalid())
5902         return true;
5903 
5904       Arg = ArgE.getAs<Expr>();
5905     } else {
5906       assert(Param && "can't use default arguments without a known callee");
5907 
5908       ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
5909       if (ArgExpr.isInvalid())
5910         return true;
5911 
5912       Arg = ArgExpr.getAs<Expr>();
5913     }
5914 
5915     // Check for array bounds violations for each argument to the call. This
5916     // check only triggers warnings when the argument isn't a more complex Expr
5917     // with its own checking, such as a BinaryOperator.
5918     CheckArrayAccess(Arg);
5919 
5920     // Check for violations of C99 static array rules (C99 6.7.5.3p7).
5921     CheckStaticArrayArgument(CallLoc, Param, Arg);
5922 
5923     AllArgs.push_back(Arg);
5924   }
5925 
5926   // If this is a variadic call, handle args passed through "...".
5927   if (CallType != VariadicDoesNotApply) {
5928     // Assume that extern "C" functions with variadic arguments that
5929     // return __unknown_anytype aren't *really* variadic.
5930     if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
5931         FDecl->isExternC()) {
5932       for (Expr *A : Args.slice(ArgIx)) {
5933         QualType paramType; // ignored
5934         ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
5935         Invalid |= arg.isInvalid();
5936         AllArgs.push_back(arg.get());
5937       }
5938 
5939     // Otherwise do argument promotion, (C99 6.5.2.2p7).
5940     } else {
5941       for (Expr *A : Args.slice(ArgIx)) {
5942         ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
5943         Invalid |= Arg.isInvalid();
5944         // Copy blocks to the heap.
5945         if (A->getType()->isBlockPointerType())
5946           maybeExtendBlockObject(Arg);
5947         AllArgs.push_back(Arg.get());
5948       }
5949     }
5950 
5951     // Check for array bounds violations.
5952     for (Expr *A : Args.slice(ArgIx))
5953       CheckArrayAccess(A);
5954   }
5955   return Invalid;
5956 }
5957 
5958 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
5959   TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
5960   if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
5961     TL = DTL.getOriginalLoc();
5962   if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
5963     S.Diag(PVD->getLocation(), diag::note_callee_static_array)
5964       << ATL.getLocalSourceRange();
5965 }
5966 
5967 /// CheckStaticArrayArgument - If the given argument corresponds to a static
5968 /// array parameter, check that it is non-null, and that if it is formed by
5969 /// array-to-pointer decay, the underlying array is sufficiently large.
5970 ///
5971 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
5972 /// array type derivation, then for each call to the function, the value of the
5973 /// corresponding actual argument shall provide access to the first element of
5974 /// an array with at least as many elements as specified by the size expression.
5975 void
5976 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
5977                                ParmVarDecl *Param,
5978                                const Expr *ArgExpr) {
5979   // Static array parameters are not supported in C++.
5980   if (!Param || getLangOpts().CPlusPlus)
5981     return;
5982 
5983   QualType OrigTy = Param->getOriginalType();
5984 
5985   const ArrayType *AT = Context.getAsArrayType(OrigTy);
5986   if (!AT || AT->getSizeModifier() != ArrayType::Static)
5987     return;
5988 
5989   if (ArgExpr->isNullPointerConstant(Context,
5990                                      Expr::NPC_NeverValueDependent)) {
5991     Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
5992     DiagnoseCalleeStaticArrayParam(*this, Param);
5993     return;
5994   }
5995 
5996   const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
5997   if (!CAT)
5998     return;
5999 
6000   const ConstantArrayType *ArgCAT =
6001     Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType());
6002   if (!ArgCAT)
6003     return;
6004 
6005   if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(),
6006                                              ArgCAT->getElementType())) {
6007     if (ArgCAT->getSize().ult(CAT->getSize())) {
6008       Diag(CallLoc, diag::warn_static_array_too_small)
6009           << ArgExpr->getSourceRange()
6010           << (unsigned)ArgCAT->getSize().getZExtValue()
6011           << (unsigned)CAT->getSize().getZExtValue() << 0;
6012       DiagnoseCalleeStaticArrayParam(*this, Param);
6013     }
6014     return;
6015   }
6016 
6017   Optional<CharUnits> ArgSize =
6018       getASTContext().getTypeSizeInCharsIfKnown(ArgCAT);
6019   Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT);
6020   if (ArgSize && ParmSize && *ArgSize < *ParmSize) {
6021     Diag(CallLoc, diag::warn_static_array_too_small)
6022         << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()
6023         << (unsigned)ParmSize->getQuantity() << 1;
6024     DiagnoseCalleeStaticArrayParam(*this, Param);
6025   }
6026 }
6027 
6028 /// Given a function expression of unknown-any type, try to rebuild it
6029 /// to have a function type.
6030 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
6031 
6032 /// Is the given type a placeholder that we need to lower out
6033 /// immediately during argument processing?
6034 static bool isPlaceholderToRemoveAsArg(QualType type) {
6035   // Placeholders are never sugared.
6036   const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
6037   if (!placeholder) return false;
6038 
6039   switch (placeholder->getKind()) {
6040   // Ignore all the non-placeholder types.
6041 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6042   case BuiltinType::Id:
6043 #include "clang/Basic/OpenCLImageTypes.def"
6044 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6045   case BuiltinType::Id:
6046 #include "clang/Basic/OpenCLExtensionTypes.def"
6047   // In practice we'll never use this, since all SVE types are sugared
6048   // via TypedefTypes rather than exposed directly as BuiltinTypes.
6049 #define SVE_TYPE(Name, Id, SingletonId) \
6050   case BuiltinType::Id:
6051 #include "clang/Basic/AArch64SVEACLETypes.def"
6052 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
6053 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
6054 #include "clang/AST/BuiltinTypes.def"
6055     return false;
6056 
6057   // We cannot lower out overload sets; they might validly be resolved
6058   // by the call machinery.
6059   case BuiltinType::Overload:
6060     return false;
6061 
6062   // Unbridged casts in ARC can be handled in some call positions and
6063   // should be left in place.
6064   case BuiltinType::ARCUnbridgedCast:
6065     return false;
6066 
6067   // Pseudo-objects should be converted as soon as possible.
6068   case BuiltinType::PseudoObject:
6069     return true;
6070 
6071   // The debugger mode could theoretically but currently does not try
6072   // to resolve unknown-typed arguments based on known parameter types.
6073   case BuiltinType::UnknownAny:
6074     return true;
6075 
6076   // These are always invalid as call arguments and should be reported.
6077   case BuiltinType::BoundMember:
6078   case BuiltinType::BuiltinFn:
6079   case BuiltinType::IncompleteMatrixIdx:
6080   case BuiltinType::OMPArraySection:
6081   case BuiltinType::OMPArrayShaping:
6082   case BuiltinType::OMPIterator:
6083     return true;
6084 
6085   }
6086   llvm_unreachable("bad builtin type kind");
6087 }
6088 
6089 /// Check an argument list for placeholders that we won't try to
6090 /// handle later.
6091 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
6092   // Apply this processing to all the arguments at once instead of
6093   // dying at the first failure.
6094   bool hasInvalid = false;
6095   for (size_t i = 0, e = args.size(); i != e; i++) {
6096     if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
6097       ExprResult result = S.CheckPlaceholderExpr(args[i]);
6098       if (result.isInvalid()) hasInvalid = true;
6099       else args[i] = result.get();
6100     } else if (hasInvalid) {
6101       (void)S.CorrectDelayedTyposInExpr(args[i]);
6102     }
6103   }
6104   return hasInvalid;
6105 }
6106 
6107 /// If a builtin function has a pointer argument with no explicit address
6108 /// space, then it should be able to accept a pointer to any address
6109 /// space as input.  In order to do this, we need to replace the
6110 /// standard builtin declaration with one that uses the same address space
6111 /// as the call.
6112 ///
6113 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
6114 ///                  it does not contain any pointer arguments without
6115 ///                  an address space qualifer.  Otherwise the rewritten
6116 ///                  FunctionDecl is returned.
6117 /// TODO: Handle pointer return types.
6118 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
6119                                                 FunctionDecl *FDecl,
6120                                                 MultiExprArg ArgExprs) {
6121 
6122   QualType DeclType = FDecl->getType();
6123   const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
6124 
6125   if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT ||
6126       ArgExprs.size() < FT->getNumParams())
6127     return nullptr;
6128 
6129   bool NeedsNewDecl = false;
6130   unsigned i = 0;
6131   SmallVector<QualType, 8> OverloadParams;
6132 
6133   for (QualType ParamType : FT->param_types()) {
6134 
6135     // Convert array arguments to pointer to simplify type lookup.
6136     ExprResult ArgRes =
6137         Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
6138     if (ArgRes.isInvalid())
6139       return nullptr;
6140     Expr *Arg = ArgRes.get();
6141     QualType ArgType = Arg->getType();
6142     if (!ParamType->isPointerType() ||
6143         ParamType.hasAddressSpace() ||
6144         !ArgType->isPointerType() ||
6145         !ArgType->getPointeeType().hasAddressSpace()) {
6146       OverloadParams.push_back(ParamType);
6147       continue;
6148     }
6149 
6150     QualType PointeeType = ParamType->getPointeeType();
6151     if (PointeeType.hasAddressSpace())
6152       continue;
6153 
6154     NeedsNewDecl = true;
6155     LangAS AS = ArgType->getPointeeType().getAddressSpace();
6156 
6157     PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
6158     OverloadParams.push_back(Context.getPointerType(PointeeType));
6159   }
6160 
6161   if (!NeedsNewDecl)
6162     return nullptr;
6163 
6164   FunctionProtoType::ExtProtoInfo EPI;
6165   EPI.Variadic = FT->isVariadic();
6166   QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
6167                                                 OverloadParams, EPI);
6168   DeclContext *Parent = FDecl->getParent();
6169   FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
6170                                                     FDecl->getLocation(),
6171                                                     FDecl->getLocation(),
6172                                                     FDecl->getIdentifier(),
6173                                                     OverloadTy,
6174                                                     /*TInfo=*/nullptr,
6175                                                     SC_Extern, false,
6176                                                     /*hasPrototype=*/true);
6177   SmallVector<ParmVarDecl*, 16> Params;
6178   FT = cast<FunctionProtoType>(OverloadTy);
6179   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
6180     QualType ParamType = FT->getParamType(i);
6181     ParmVarDecl *Parm =
6182         ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
6183                                 SourceLocation(), nullptr, ParamType,
6184                                 /*TInfo=*/nullptr, SC_None, nullptr);
6185     Parm->setScopeInfo(0, i);
6186     Params.push_back(Parm);
6187   }
6188   OverloadDecl->setParams(Params);
6189   return OverloadDecl;
6190 }
6191 
6192 static void checkDirectCallValidity(Sema &S, const Expr *Fn,
6193                                     FunctionDecl *Callee,
6194                                     MultiExprArg ArgExprs) {
6195   // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
6196   // similar attributes) really don't like it when functions are called with an
6197   // invalid number of args.
6198   if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
6199                          /*PartialOverloading=*/false) &&
6200       !Callee->isVariadic())
6201     return;
6202   if (Callee->getMinRequiredArguments() > ArgExprs.size())
6203     return;
6204 
6205   if (const EnableIfAttr *Attr =
6206           S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) {
6207     S.Diag(Fn->getBeginLoc(),
6208            isa<CXXMethodDecl>(Callee)
6209                ? diag::err_ovl_no_viable_member_function_in_call
6210                : diag::err_ovl_no_viable_function_in_call)
6211         << Callee << Callee->getSourceRange();
6212     S.Diag(Callee->getLocation(),
6213            diag::note_ovl_candidate_disabled_by_function_cond_attr)
6214         << Attr->getCond()->getSourceRange() << Attr->getMessage();
6215     return;
6216   }
6217 }
6218 
6219 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(
6220     const UnresolvedMemberExpr *const UME, Sema &S) {
6221 
6222   const auto GetFunctionLevelDCIfCXXClass =
6223       [](Sema &S) -> const CXXRecordDecl * {
6224     const DeclContext *const DC = S.getFunctionLevelDeclContext();
6225     if (!DC || !DC->getParent())
6226       return nullptr;
6227 
6228     // If the call to some member function was made from within a member
6229     // function body 'M' return return 'M's parent.
6230     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
6231       return MD->getParent()->getCanonicalDecl();
6232     // else the call was made from within a default member initializer of a
6233     // class, so return the class.
6234     if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
6235       return RD->getCanonicalDecl();
6236     return nullptr;
6237   };
6238   // If our DeclContext is neither a member function nor a class (in the
6239   // case of a lambda in a default member initializer), we can't have an
6240   // enclosing 'this'.
6241 
6242   const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
6243   if (!CurParentClass)
6244     return false;
6245 
6246   // The naming class for implicit member functions call is the class in which
6247   // name lookup starts.
6248   const CXXRecordDecl *const NamingClass =
6249       UME->getNamingClass()->getCanonicalDecl();
6250   assert(NamingClass && "Must have naming class even for implicit access");
6251 
6252   // If the unresolved member functions were found in a 'naming class' that is
6253   // related (either the same or derived from) to the class that contains the
6254   // member function that itself contained the implicit member access.
6255 
6256   return CurParentClass == NamingClass ||
6257          CurParentClass->isDerivedFrom(NamingClass);
6258 }
6259 
6260 static void
6261 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
6262     Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
6263 
6264   if (!UME)
6265     return;
6266 
6267   LambdaScopeInfo *const CurLSI = S.getCurLambda();
6268   // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
6269   // already been captured, or if this is an implicit member function call (if
6270   // it isn't, an attempt to capture 'this' should already have been made).
6271   if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
6272       !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
6273     return;
6274 
6275   // Check if the naming class in which the unresolved members were found is
6276   // related (same as or is a base of) to the enclosing class.
6277 
6278   if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S))
6279     return;
6280 
6281 
6282   DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
6283   // If the enclosing function is not dependent, then this lambda is
6284   // capture ready, so if we can capture this, do so.
6285   if (!EnclosingFunctionCtx->isDependentContext()) {
6286     // If the current lambda and all enclosing lambdas can capture 'this' -
6287     // then go ahead and capture 'this' (since our unresolved overload set
6288     // contains at least one non-static member function).
6289     if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
6290       S.CheckCXXThisCapture(CallLoc);
6291   } else if (S.CurContext->isDependentContext()) {
6292     // ... since this is an implicit member reference, that might potentially
6293     // involve a 'this' capture, mark 'this' for potential capture in
6294     // enclosing lambdas.
6295     if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
6296       CurLSI->addPotentialThisCapture(CallLoc);
6297   }
6298 }
6299 
6300 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
6301                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
6302                                Expr *ExecConfig) {
6303   ExprResult Call =
6304       BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig);
6305   if (Call.isInvalid())
6306     return Call;
6307 
6308   // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier
6309   // language modes.
6310   if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) {
6311     if (ULE->hasExplicitTemplateArgs() &&
6312         ULE->decls_begin() == ULE->decls_end()) {
6313       Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus20
6314                                  ? diag::warn_cxx17_compat_adl_only_template_id
6315                                  : diag::ext_adl_only_template_id)
6316           << ULE->getName();
6317     }
6318   }
6319 
6320   if (LangOpts.OpenMP)
6321     Call = ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc,
6322                            ExecConfig);
6323 
6324   return Call;
6325 }
6326 
6327 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments.
6328 /// This provides the location of the left/right parens and a list of comma
6329 /// locations.
6330 ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
6331                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
6332                                Expr *ExecConfig, bool IsExecConfig) {
6333   // Since this might be a postfix expression, get rid of ParenListExprs.
6334   ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
6335   if (Result.isInvalid()) return ExprError();
6336   Fn = Result.get();
6337 
6338   if (checkArgsForPlaceholders(*this, ArgExprs))
6339     return ExprError();
6340 
6341   if (getLangOpts().CPlusPlus) {
6342     // If this is a pseudo-destructor expression, build the call immediately.
6343     if (isa<CXXPseudoDestructorExpr>(Fn)) {
6344       if (!ArgExprs.empty()) {
6345         // Pseudo-destructor calls should not have any arguments.
6346         Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args)
6347             << FixItHint::CreateRemoval(
6348                    SourceRange(ArgExprs.front()->getBeginLoc(),
6349                                ArgExprs.back()->getEndLoc()));
6350       }
6351 
6352       return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy,
6353                               VK_RValue, RParenLoc);
6354     }
6355     if (Fn->getType() == Context.PseudoObjectTy) {
6356       ExprResult result = CheckPlaceholderExpr(Fn);
6357       if (result.isInvalid()) return ExprError();
6358       Fn = result.get();
6359     }
6360 
6361     // Determine whether this is a dependent call inside a C++ template,
6362     // in which case we won't do any semantic analysis now.
6363     if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) {
6364       if (ExecConfig) {
6365         return CUDAKernelCallExpr::Create(
6366             Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
6367             Context.DependentTy, VK_RValue, RParenLoc);
6368       } else {
6369 
6370         tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
6371             *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
6372             Fn->getBeginLoc());
6373 
6374         return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6375                                 VK_RValue, RParenLoc);
6376       }
6377     }
6378 
6379     // Determine whether this is a call to an object (C++ [over.call.object]).
6380     if (Fn->getType()->isRecordType())
6381       return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
6382                                           RParenLoc);
6383 
6384     if (Fn->getType() == Context.UnknownAnyTy) {
6385       ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6386       if (result.isInvalid()) return ExprError();
6387       Fn = result.get();
6388     }
6389 
6390     if (Fn->getType() == Context.BoundMemberTy) {
6391       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6392                                        RParenLoc);
6393     }
6394   }
6395 
6396   // Check for overloaded calls.  This can happen even in C due to extensions.
6397   if (Fn->getType() == Context.OverloadTy) {
6398     OverloadExpr::FindResult find = OverloadExpr::find(Fn);
6399 
6400     // We aren't supposed to apply this logic if there's an '&' involved.
6401     if (!find.HasFormOfMemberPointer) {
6402       if (Expr::hasAnyTypeDependentArguments(ArgExprs))
6403         return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6404                                 VK_RValue, RParenLoc);
6405       OverloadExpr *ovl = find.Expression;
6406       if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
6407         return BuildOverloadedCallExpr(
6408             Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6409             /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
6410       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6411                                        RParenLoc);
6412     }
6413   }
6414 
6415   // If we're directly calling a function, get the appropriate declaration.
6416   if (Fn->getType() == Context.UnknownAnyTy) {
6417     ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6418     if (result.isInvalid()) return ExprError();
6419     Fn = result.get();
6420   }
6421 
6422   Expr *NakedFn = Fn->IgnoreParens();
6423 
6424   bool CallingNDeclIndirectly = false;
6425   NamedDecl *NDecl = nullptr;
6426   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
6427     if (UnOp->getOpcode() == UO_AddrOf) {
6428       CallingNDeclIndirectly = true;
6429       NakedFn = UnOp->getSubExpr()->IgnoreParens();
6430     }
6431   }
6432 
6433   if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
6434     NDecl = DRE->getDecl();
6435 
6436     FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
6437     if (FDecl && FDecl->getBuiltinID()) {
6438       // Rewrite the function decl for this builtin by replacing parameters
6439       // with no explicit address space with the address space of the arguments
6440       // in ArgExprs.
6441       if ((FDecl =
6442                rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
6443         NDecl = FDecl;
6444         Fn = DeclRefExpr::Create(
6445             Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
6446             SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl,
6447             nullptr, DRE->isNonOdrUse());
6448       }
6449     }
6450   } else if (isa<MemberExpr>(NakedFn))
6451     NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
6452 
6453   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
6454     if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
6455                                       FD, /*Complain=*/true, Fn->getBeginLoc()))
6456       return ExprError();
6457 
6458     if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn))
6459       return ExprError();
6460 
6461     checkDirectCallValidity(*this, Fn, FD, ArgExprs);
6462   }
6463 
6464   return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
6465                                ExecConfig, IsExecConfig);
6466 }
6467 
6468 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
6469 ///
6470 /// __builtin_astype( value, dst type )
6471 ///
6472 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
6473                                  SourceLocation BuiltinLoc,
6474                                  SourceLocation RParenLoc) {
6475   ExprValueKind VK = VK_RValue;
6476   ExprObjectKind OK = OK_Ordinary;
6477   QualType DstTy = GetTypeFromParser(ParsedDestTy);
6478   QualType SrcTy = E->getType();
6479   if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
6480     return ExprError(Diag(BuiltinLoc,
6481                           diag::err_invalid_astype_of_different_size)
6482                      << DstTy
6483                      << SrcTy
6484                      << E->getSourceRange());
6485   return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
6486 }
6487 
6488 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
6489 /// provided arguments.
6490 ///
6491 /// __builtin_convertvector( value, dst type )
6492 ///
6493 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
6494                                         SourceLocation BuiltinLoc,
6495                                         SourceLocation RParenLoc) {
6496   TypeSourceInfo *TInfo;
6497   GetTypeFromParser(ParsedDestTy, &TInfo);
6498   return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
6499 }
6500 
6501 /// BuildResolvedCallExpr - Build a call to a resolved expression,
6502 /// i.e. an expression not of \p OverloadTy.  The expression should
6503 /// unary-convert to an expression of function-pointer or
6504 /// block-pointer type.
6505 ///
6506 /// \param NDecl the declaration being called, if available
6507 ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
6508                                        SourceLocation LParenLoc,
6509                                        ArrayRef<Expr *> Args,
6510                                        SourceLocation RParenLoc, Expr *Config,
6511                                        bool IsExecConfig, ADLCallKind UsesADL) {
6512   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
6513   unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
6514 
6515   // Functions with 'interrupt' attribute cannot be called directly.
6516   if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
6517     Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
6518     return ExprError();
6519   }
6520 
6521   // Interrupt handlers don't save off the VFP regs automatically on ARM,
6522   // so there's some risk when calling out to non-interrupt handler functions
6523   // that the callee might not preserve them. This is easy to diagnose here,
6524   // but can be very challenging to debug.
6525   if (auto *Caller = getCurFunctionDecl())
6526     if (Caller->hasAttr<ARMInterruptAttr>()) {
6527       bool VFP = Context.getTargetInfo().hasFeature("vfp");
6528       if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>()))
6529         Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention);
6530     }
6531 
6532   // Promote the function operand.
6533   // We special-case function promotion here because we only allow promoting
6534   // builtin functions to function pointers in the callee of a call.
6535   ExprResult Result;
6536   QualType ResultTy;
6537   if (BuiltinID &&
6538       Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
6539     // Extract the return type from the (builtin) function pointer type.
6540     // FIXME Several builtins still have setType in
6541     // Sema::CheckBuiltinFunctionCall. One should review their definitions in
6542     // Builtins.def to ensure they are correct before removing setType calls.
6543     QualType FnPtrTy = Context.getPointerType(FDecl->getType());
6544     Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get();
6545     ResultTy = FDecl->getCallResultType();
6546   } else {
6547     Result = CallExprUnaryConversions(Fn);
6548     ResultTy = Context.BoolTy;
6549   }
6550   if (Result.isInvalid())
6551     return ExprError();
6552   Fn = Result.get();
6553 
6554   // Check for a valid function type, but only if it is not a builtin which
6555   // requires custom type checking. These will be handled by
6556   // CheckBuiltinFunctionCall below just after creation of the call expression.
6557   const FunctionType *FuncT = nullptr;
6558   if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
6559   retry:
6560     if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
6561       // C99 6.5.2.2p1 - "The expression that denotes the called function shall
6562       // have type pointer to function".
6563       FuncT = PT->getPointeeType()->getAs<FunctionType>();
6564       if (!FuncT)
6565         return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
6566                          << Fn->getType() << Fn->getSourceRange());
6567     } else if (const BlockPointerType *BPT =
6568                    Fn->getType()->getAs<BlockPointerType>()) {
6569       FuncT = BPT->getPointeeType()->castAs<FunctionType>();
6570     } else {
6571       // Handle calls to expressions of unknown-any type.
6572       if (Fn->getType() == Context.UnknownAnyTy) {
6573         ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
6574         if (rewrite.isInvalid())
6575           return ExprError();
6576         Fn = rewrite.get();
6577         goto retry;
6578       }
6579 
6580       return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
6581                        << Fn->getType() << Fn->getSourceRange());
6582     }
6583   }
6584 
6585   // Get the number of parameters in the function prototype, if any.
6586   // We will allocate space for max(Args.size(), NumParams) arguments
6587   // in the call expression.
6588   const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT);
6589   unsigned NumParams = Proto ? Proto->getNumParams() : 0;
6590 
6591   CallExpr *TheCall;
6592   if (Config) {
6593     assert(UsesADL == ADLCallKind::NotADL &&
6594            "CUDAKernelCallExpr should not use ADL");
6595     TheCall =
6596         CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config), Args,
6597                                    ResultTy, VK_RValue, RParenLoc, NumParams);
6598   } else {
6599     TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue,
6600                                RParenLoc, NumParams, UsesADL);
6601   }
6602 
6603   if (!getLangOpts().CPlusPlus) {
6604     // Forget about the nulled arguments since typo correction
6605     // do not handle them well.
6606     TheCall->shrinkNumArgs(Args.size());
6607     // C cannot always handle TypoExpr nodes in builtin calls and direct
6608     // function calls as their argument checking don't necessarily handle
6609     // dependent types properly, so make sure any TypoExprs have been
6610     // dealt with.
6611     ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
6612     if (!Result.isUsable()) return ExprError();
6613     CallExpr *TheOldCall = TheCall;
6614     TheCall = dyn_cast<CallExpr>(Result.get());
6615     bool CorrectedTypos = TheCall != TheOldCall;
6616     if (!TheCall) return Result;
6617     Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
6618 
6619     // A new call expression node was created if some typos were corrected.
6620     // However it may not have been constructed with enough storage. In this
6621     // case, rebuild the node with enough storage. The waste of space is
6622     // immaterial since this only happens when some typos were corrected.
6623     if (CorrectedTypos && Args.size() < NumParams) {
6624       if (Config)
6625         TheCall = CUDAKernelCallExpr::Create(
6626             Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_RValue,
6627             RParenLoc, NumParams);
6628       else
6629         TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue,
6630                                    RParenLoc, NumParams, UsesADL);
6631     }
6632     // We can now handle the nulled arguments for the default arguments.
6633     TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams));
6634   }
6635 
6636   // Bail out early if calling a builtin with custom type checking.
6637   if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
6638     return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
6639 
6640   if (getLangOpts().CUDA) {
6641     if (Config) {
6642       // CUDA: Kernel calls must be to global functions
6643       if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
6644         return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
6645             << FDecl << Fn->getSourceRange());
6646 
6647       // CUDA: Kernel function must have 'void' return type
6648       if (!FuncT->getReturnType()->isVoidType() &&
6649           !FuncT->getReturnType()->getAs<AutoType>() &&
6650           !FuncT->getReturnType()->isInstantiationDependentType())
6651         return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
6652             << Fn->getType() << Fn->getSourceRange());
6653     } else {
6654       // CUDA: Calls to global functions must be configured
6655       if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
6656         return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
6657             << FDecl << Fn->getSourceRange());
6658     }
6659   }
6660 
6661   // Check for a valid return type
6662   if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall,
6663                           FDecl))
6664     return ExprError();
6665 
6666   // We know the result type of the call, set it.
6667   TheCall->setType(FuncT->getCallResultType(Context));
6668   TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
6669 
6670   if (Proto) {
6671     if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
6672                                 IsExecConfig))
6673       return ExprError();
6674   } else {
6675     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
6676 
6677     if (FDecl) {
6678       // Check if we have too few/too many template arguments, based
6679       // on our knowledge of the function definition.
6680       const FunctionDecl *Def = nullptr;
6681       if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
6682         Proto = Def->getType()->getAs<FunctionProtoType>();
6683        if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
6684           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
6685           << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
6686       }
6687 
6688       // If the function we're calling isn't a function prototype, but we have
6689       // a function prototype from a prior declaratiom, use that prototype.
6690       if (!FDecl->hasPrototype())
6691         Proto = FDecl->getType()->getAs<FunctionProtoType>();
6692     }
6693 
6694     // Promote the arguments (C99 6.5.2.2p6).
6695     for (unsigned i = 0, e = Args.size(); i != e; i++) {
6696       Expr *Arg = Args[i];
6697 
6698       if (Proto && i < Proto->getNumParams()) {
6699         InitializedEntity Entity = InitializedEntity::InitializeParameter(
6700             Context, Proto->getParamType(i), Proto->isParamConsumed(i));
6701         ExprResult ArgE =
6702             PerformCopyInitialization(Entity, SourceLocation(), Arg);
6703         if (ArgE.isInvalid())
6704           return true;
6705 
6706         Arg = ArgE.getAs<Expr>();
6707 
6708       } else {
6709         ExprResult ArgE = DefaultArgumentPromotion(Arg);
6710 
6711         if (ArgE.isInvalid())
6712           return true;
6713 
6714         Arg = ArgE.getAs<Expr>();
6715       }
6716 
6717       if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(),
6718                               diag::err_call_incomplete_argument, Arg))
6719         return ExprError();
6720 
6721       TheCall->setArg(i, Arg);
6722     }
6723   }
6724 
6725   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
6726     if (!Method->isStatic())
6727       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
6728         << Fn->getSourceRange());
6729 
6730   // Check for sentinels
6731   if (NDecl)
6732     DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
6733 
6734   // Warn for unions passing across security boundary (CMSE).
6735   if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) {
6736     for (unsigned i = 0, e = Args.size(); i != e; i++) {
6737       if (const auto *RT =
6738               dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) {
6739         if (RT->getDecl()->isOrContainsUnion())
6740           Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union)
6741               << 0 << i;
6742       }
6743     }
6744   }
6745 
6746   // Do special checking on direct calls to functions.
6747   if (FDecl) {
6748     if (CheckFunctionCall(FDecl, TheCall, Proto))
6749       return ExprError();
6750 
6751     checkFortifiedBuiltinMemoryFunction(FDecl, TheCall);
6752 
6753     if (BuiltinID)
6754       return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
6755   } else if (NDecl) {
6756     if (CheckPointerCall(NDecl, TheCall, Proto))
6757       return ExprError();
6758   } else {
6759     if (CheckOtherCall(TheCall, Proto))
6760       return ExprError();
6761   }
6762 
6763   return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl);
6764 }
6765 
6766 ExprResult
6767 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
6768                            SourceLocation RParenLoc, Expr *InitExpr) {
6769   assert(Ty && "ActOnCompoundLiteral(): missing type");
6770   assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
6771 
6772   TypeSourceInfo *TInfo;
6773   QualType literalType = GetTypeFromParser(Ty, &TInfo);
6774   if (!TInfo)
6775     TInfo = Context.getTrivialTypeSourceInfo(literalType);
6776 
6777   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
6778 }
6779 
6780 ExprResult
6781 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
6782                                SourceLocation RParenLoc, Expr *LiteralExpr) {
6783   QualType literalType = TInfo->getType();
6784 
6785   if (literalType->isArrayType()) {
6786     if (RequireCompleteSizedType(
6787             LParenLoc, Context.getBaseElementType(literalType),
6788             diag::err_array_incomplete_or_sizeless_type,
6789             SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
6790       return ExprError();
6791     if (literalType->isVariableArrayType())
6792       return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
6793         << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
6794   } else if (!literalType->isDependentType() &&
6795              RequireCompleteType(LParenLoc, literalType,
6796                diag::err_typecheck_decl_incomplete_type,
6797                SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
6798     return ExprError();
6799 
6800   InitializedEntity Entity
6801     = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
6802   InitializationKind Kind
6803     = InitializationKind::CreateCStyleCast(LParenLoc,
6804                                            SourceRange(LParenLoc, RParenLoc),
6805                                            /*InitList=*/true);
6806   InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
6807   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
6808                                       &literalType);
6809   if (Result.isInvalid())
6810     return ExprError();
6811   LiteralExpr = Result.get();
6812 
6813   bool isFileScope = !CurContext->isFunctionOrMethod();
6814 
6815   // In C, compound literals are l-values for some reason.
6816   // For GCC compatibility, in C++, file-scope array compound literals with
6817   // constant initializers are also l-values, and compound literals are
6818   // otherwise prvalues.
6819   //
6820   // (GCC also treats C++ list-initialized file-scope array prvalues with
6821   // constant initializers as l-values, but that's non-conforming, so we don't
6822   // follow it there.)
6823   //
6824   // FIXME: It would be better to handle the lvalue cases as materializing and
6825   // lifetime-extending a temporary object, but our materialized temporaries
6826   // representation only supports lifetime extension from a variable, not "out
6827   // of thin air".
6828   // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
6829   // is bound to the result of applying array-to-pointer decay to the compound
6830   // literal.
6831   // FIXME: GCC supports compound literals of reference type, which should
6832   // obviously have a value kind derived from the kind of reference involved.
6833   ExprValueKind VK =
6834       (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
6835           ? VK_RValue
6836           : VK_LValue;
6837 
6838   if (isFileScope)
6839     if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr))
6840       for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {
6841         Expr *Init = ILE->getInit(i);
6842         ILE->setInit(i, ConstantExpr::Create(Context, Init));
6843       }
6844 
6845   auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
6846                                               VK, LiteralExpr, isFileScope);
6847   if (isFileScope) {
6848     if (!LiteralExpr->isTypeDependent() &&
6849         !LiteralExpr->isValueDependent() &&
6850         !literalType->isDependentType()) // C99 6.5.2.5p3
6851       if (CheckForConstantInitializer(LiteralExpr, literalType))
6852         return ExprError();
6853   } else if (literalType.getAddressSpace() != LangAS::opencl_private &&
6854              literalType.getAddressSpace() != LangAS::Default) {
6855     // Embedded-C extensions to C99 6.5.2.5:
6856     //   "If the compound literal occurs inside the body of a function, the
6857     //   type name shall not be qualified by an address-space qualifier."
6858     Diag(LParenLoc, diag::err_compound_literal_with_address_space)
6859       << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
6860     return ExprError();
6861   }
6862 
6863   if (!isFileScope && !getLangOpts().CPlusPlus) {
6864     // Compound literals that have automatic storage duration are destroyed at
6865     // the end of the scope in C; in C++, they're just temporaries.
6866 
6867     // Emit diagnostics if it is or contains a C union type that is non-trivial
6868     // to destruct.
6869     if (E->getType().hasNonTrivialToPrimitiveDestructCUnion())
6870       checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
6871                             NTCUC_CompoundLiteral, NTCUK_Destruct);
6872 
6873     // Diagnose jumps that enter or exit the lifetime of the compound literal.
6874     if (literalType.isDestructedType()) {
6875       Cleanup.setExprNeedsCleanups(true);
6876       ExprCleanupObjects.push_back(E);
6877       getCurFunction()->setHasBranchProtectedScope();
6878     }
6879   }
6880 
6881   if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
6882       E->getType().hasNonTrivialToPrimitiveCopyCUnion())
6883     checkNonTrivialCUnionInInitializer(E->getInitializer(),
6884                                        E->getInitializer()->getExprLoc());
6885 
6886   return MaybeBindToTemporary(E);
6887 }
6888 
6889 ExprResult
6890 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
6891                     SourceLocation RBraceLoc) {
6892   // Only produce each kind of designated initialization diagnostic once.
6893   SourceLocation FirstDesignator;
6894   bool DiagnosedArrayDesignator = false;
6895   bool DiagnosedNestedDesignator = false;
6896   bool DiagnosedMixedDesignator = false;
6897 
6898   // Check that any designated initializers are syntactically valid in the
6899   // current language mode.
6900   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
6901     if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) {
6902       if (FirstDesignator.isInvalid())
6903         FirstDesignator = DIE->getBeginLoc();
6904 
6905       if (!getLangOpts().CPlusPlus)
6906         break;
6907 
6908       if (!DiagnosedNestedDesignator && DIE->size() > 1) {
6909         DiagnosedNestedDesignator = true;
6910         Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested)
6911           << DIE->getDesignatorsSourceRange();
6912       }
6913 
6914       for (auto &Desig : DIE->designators()) {
6915         if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) {
6916           DiagnosedArrayDesignator = true;
6917           Diag(Desig.getBeginLoc(), diag::ext_designated_init_array)
6918             << Desig.getSourceRange();
6919         }
6920       }
6921 
6922       if (!DiagnosedMixedDesignator &&
6923           !isa<DesignatedInitExpr>(InitArgList[0])) {
6924         DiagnosedMixedDesignator = true;
6925         Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
6926           << DIE->getSourceRange();
6927         Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed)
6928           << InitArgList[0]->getSourceRange();
6929       }
6930     } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator &&
6931                isa<DesignatedInitExpr>(InitArgList[0])) {
6932       DiagnosedMixedDesignator = true;
6933       auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]);
6934       Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
6935         << DIE->getSourceRange();
6936       Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed)
6937         << InitArgList[I]->getSourceRange();
6938     }
6939   }
6940 
6941   if (FirstDesignator.isValid()) {
6942     // Only diagnose designated initiaization as a C++20 extension if we didn't
6943     // already diagnose use of (non-C++20) C99 designator syntax.
6944     if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator &&
6945         !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) {
6946       Diag(FirstDesignator, getLangOpts().CPlusPlus20
6947                                 ? diag::warn_cxx17_compat_designated_init
6948                                 : diag::ext_cxx_designated_init);
6949     } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) {
6950       Diag(FirstDesignator, diag::ext_designated_init);
6951     }
6952   }
6953 
6954   return BuildInitList(LBraceLoc, InitArgList, RBraceLoc);
6955 }
6956 
6957 ExprResult
6958 Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
6959                     SourceLocation RBraceLoc) {
6960   // Semantic analysis for initializers is done by ActOnDeclarator() and
6961   // CheckInitializer() - it requires knowledge of the object being initialized.
6962 
6963   // Immediately handle non-overload placeholders.  Overloads can be
6964   // resolved contextually, but everything else here can't.
6965   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
6966     if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
6967       ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
6968 
6969       // Ignore failures; dropping the entire initializer list because
6970       // of one failure would be terrible for indexing/etc.
6971       if (result.isInvalid()) continue;
6972 
6973       InitArgList[I] = result.get();
6974     }
6975   }
6976 
6977   InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
6978                                                RBraceLoc);
6979   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
6980   return E;
6981 }
6982 
6983 /// Do an explicit extend of the given block pointer if we're in ARC.
6984 void Sema::maybeExtendBlockObject(ExprResult &E) {
6985   assert(E.get()->getType()->isBlockPointerType());
6986   assert(E.get()->isRValue());
6987 
6988   // Only do this in an r-value context.
6989   if (!getLangOpts().ObjCAutoRefCount) return;
6990 
6991   E = ImplicitCastExpr::Create(Context, E.get()->getType(),
6992                                CK_ARCExtendBlockObject, E.get(),
6993                                /*base path*/ nullptr, VK_RValue);
6994   Cleanup.setExprNeedsCleanups(true);
6995 }
6996 
6997 /// Prepare a conversion of the given expression to an ObjC object
6998 /// pointer type.
6999 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
7000   QualType type = E.get()->getType();
7001   if (type->isObjCObjectPointerType()) {
7002     return CK_BitCast;
7003   } else if (type->isBlockPointerType()) {
7004     maybeExtendBlockObject(E);
7005     return CK_BlockPointerToObjCPointerCast;
7006   } else {
7007     assert(type->isPointerType());
7008     return CK_CPointerToObjCPointerCast;
7009   }
7010 }
7011 
7012 /// Prepares for a scalar cast, performing all the necessary stages
7013 /// except the final cast and returning the kind required.
7014 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
7015   // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
7016   // Also, callers should have filtered out the invalid cases with
7017   // pointers.  Everything else should be possible.
7018 
7019   QualType SrcTy = Src.get()->getType();
7020   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
7021     return CK_NoOp;
7022 
7023   switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
7024   case Type::STK_MemberPointer:
7025     llvm_unreachable("member pointer type in C");
7026 
7027   case Type::STK_CPointer:
7028   case Type::STK_BlockPointer:
7029   case Type::STK_ObjCObjectPointer:
7030     switch (DestTy->getScalarTypeKind()) {
7031     case Type::STK_CPointer: {
7032       LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
7033       LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
7034       if (SrcAS != DestAS)
7035         return CK_AddressSpaceConversion;
7036       if (Context.hasCvrSimilarType(SrcTy, DestTy))
7037         return CK_NoOp;
7038       return CK_BitCast;
7039     }
7040     case Type::STK_BlockPointer:
7041       return (SrcKind == Type::STK_BlockPointer
7042                 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
7043     case Type::STK_ObjCObjectPointer:
7044       if (SrcKind == Type::STK_ObjCObjectPointer)
7045         return CK_BitCast;
7046       if (SrcKind == Type::STK_CPointer)
7047         return CK_CPointerToObjCPointerCast;
7048       maybeExtendBlockObject(Src);
7049       return CK_BlockPointerToObjCPointerCast;
7050     case Type::STK_Bool:
7051       return CK_PointerToBoolean;
7052     case Type::STK_Integral:
7053       return CK_PointerToIntegral;
7054     case Type::STK_Floating:
7055     case Type::STK_FloatingComplex:
7056     case Type::STK_IntegralComplex:
7057     case Type::STK_MemberPointer:
7058     case Type::STK_FixedPoint:
7059       llvm_unreachable("illegal cast from pointer");
7060     }
7061     llvm_unreachable("Should have returned before this");
7062 
7063   case Type::STK_FixedPoint:
7064     switch (DestTy->getScalarTypeKind()) {
7065     case Type::STK_FixedPoint:
7066       return CK_FixedPointCast;
7067     case Type::STK_Bool:
7068       return CK_FixedPointToBoolean;
7069     case Type::STK_Integral:
7070       return CK_FixedPointToIntegral;
7071     case Type::STK_Floating:
7072     case Type::STK_IntegralComplex:
7073     case Type::STK_FloatingComplex:
7074       Diag(Src.get()->getExprLoc(),
7075            diag::err_unimplemented_conversion_with_fixed_point_type)
7076           << DestTy;
7077       return CK_IntegralCast;
7078     case Type::STK_CPointer:
7079     case Type::STK_ObjCObjectPointer:
7080     case Type::STK_BlockPointer:
7081     case Type::STK_MemberPointer:
7082       llvm_unreachable("illegal cast to pointer type");
7083     }
7084     llvm_unreachable("Should have returned before this");
7085 
7086   case Type::STK_Bool: // casting from bool is like casting from an integer
7087   case Type::STK_Integral:
7088     switch (DestTy->getScalarTypeKind()) {
7089     case Type::STK_CPointer:
7090     case Type::STK_ObjCObjectPointer:
7091     case Type::STK_BlockPointer:
7092       if (Src.get()->isNullPointerConstant(Context,
7093                                            Expr::NPC_ValueDependentIsNull))
7094         return CK_NullToPointer;
7095       return CK_IntegralToPointer;
7096     case Type::STK_Bool:
7097       return CK_IntegralToBoolean;
7098     case Type::STK_Integral:
7099       return CK_IntegralCast;
7100     case Type::STK_Floating:
7101       return CK_IntegralToFloating;
7102     case Type::STK_IntegralComplex:
7103       Src = ImpCastExprToType(Src.get(),
7104                       DestTy->castAs<ComplexType>()->getElementType(),
7105                       CK_IntegralCast);
7106       return CK_IntegralRealToComplex;
7107     case Type::STK_FloatingComplex:
7108       Src = ImpCastExprToType(Src.get(),
7109                       DestTy->castAs<ComplexType>()->getElementType(),
7110                       CK_IntegralToFloating);
7111       return CK_FloatingRealToComplex;
7112     case Type::STK_MemberPointer:
7113       llvm_unreachable("member pointer type in C");
7114     case Type::STK_FixedPoint:
7115       return CK_IntegralToFixedPoint;
7116     }
7117     llvm_unreachable("Should have returned before this");
7118 
7119   case Type::STK_Floating:
7120     switch (DestTy->getScalarTypeKind()) {
7121     case Type::STK_Floating:
7122       return CK_FloatingCast;
7123     case Type::STK_Bool:
7124       return CK_FloatingToBoolean;
7125     case Type::STK_Integral:
7126       return CK_FloatingToIntegral;
7127     case Type::STK_FloatingComplex:
7128       Src = ImpCastExprToType(Src.get(),
7129                               DestTy->castAs<ComplexType>()->getElementType(),
7130                               CK_FloatingCast);
7131       return CK_FloatingRealToComplex;
7132     case Type::STK_IntegralComplex:
7133       Src = ImpCastExprToType(Src.get(),
7134                               DestTy->castAs<ComplexType>()->getElementType(),
7135                               CK_FloatingToIntegral);
7136       return CK_IntegralRealToComplex;
7137     case Type::STK_CPointer:
7138     case Type::STK_ObjCObjectPointer:
7139     case Type::STK_BlockPointer:
7140       llvm_unreachable("valid float->pointer cast?");
7141     case Type::STK_MemberPointer:
7142       llvm_unreachable("member pointer type in C");
7143     case Type::STK_FixedPoint:
7144       Diag(Src.get()->getExprLoc(),
7145            diag::err_unimplemented_conversion_with_fixed_point_type)
7146           << SrcTy;
7147       return CK_IntegralCast;
7148     }
7149     llvm_unreachable("Should have returned before this");
7150 
7151   case Type::STK_FloatingComplex:
7152     switch (DestTy->getScalarTypeKind()) {
7153     case Type::STK_FloatingComplex:
7154       return CK_FloatingComplexCast;
7155     case Type::STK_IntegralComplex:
7156       return CK_FloatingComplexToIntegralComplex;
7157     case Type::STK_Floating: {
7158       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7159       if (Context.hasSameType(ET, DestTy))
7160         return CK_FloatingComplexToReal;
7161       Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
7162       return CK_FloatingCast;
7163     }
7164     case Type::STK_Bool:
7165       return CK_FloatingComplexToBoolean;
7166     case Type::STK_Integral:
7167       Src = ImpCastExprToType(Src.get(),
7168                               SrcTy->castAs<ComplexType>()->getElementType(),
7169                               CK_FloatingComplexToReal);
7170       return CK_FloatingToIntegral;
7171     case Type::STK_CPointer:
7172     case Type::STK_ObjCObjectPointer:
7173     case Type::STK_BlockPointer:
7174       llvm_unreachable("valid complex float->pointer cast?");
7175     case Type::STK_MemberPointer:
7176       llvm_unreachable("member pointer type in C");
7177     case Type::STK_FixedPoint:
7178       Diag(Src.get()->getExprLoc(),
7179            diag::err_unimplemented_conversion_with_fixed_point_type)
7180           << SrcTy;
7181       return CK_IntegralCast;
7182     }
7183     llvm_unreachable("Should have returned before this");
7184 
7185   case Type::STK_IntegralComplex:
7186     switch (DestTy->getScalarTypeKind()) {
7187     case Type::STK_FloatingComplex:
7188       return CK_IntegralComplexToFloatingComplex;
7189     case Type::STK_IntegralComplex:
7190       return CK_IntegralComplexCast;
7191     case Type::STK_Integral: {
7192       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7193       if (Context.hasSameType(ET, DestTy))
7194         return CK_IntegralComplexToReal;
7195       Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
7196       return CK_IntegralCast;
7197     }
7198     case Type::STK_Bool:
7199       return CK_IntegralComplexToBoolean;
7200     case Type::STK_Floating:
7201       Src = ImpCastExprToType(Src.get(),
7202                               SrcTy->castAs<ComplexType>()->getElementType(),
7203                               CK_IntegralComplexToReal);
7204       return CK_IntegralToFloating;
7205     case Type::STK_CPointer:
7206     case Type::STK_ObjCObjectPointer:
7207     case Type::STK_BlockPointer:
7208       llvm_unreachable("valid complex int->pointer cast?");
7209     case Type::STK_MemberPointer:
7210       llvm_unreachable("member pointer type in C");
7211     case Type::STK_FixedPoint:
7212       Diag(Src.get()->getExprLoc(),
7213            diag::err_unimplemented_conversion_with_fixed_point_type)
7214           << SrcTy;
7215       return CK_IntegralCast;
7216     }
7217     llvm_unreachable("Should have returned before this");
7218   }
7219 
7220   llvm_unreachable("Unhandled scalar cast");
7221 }
7222 
7223 static bool breakDownVectorType(QualType type, uint64_t &len,
7224                                 QualType &eltType) {
7225   // Vectors are simple.
7226   if (const VectorType *vecType = type->getAs<VectorType>()) {
7227     len = vecType->getNumElements();
7228     eltType = vecType->getElementType();
7229     assert(eltType->isScalarType());
7230     return true;
7231   }
7232 
7233   // We allow lax conversion to and from non-vector types, but only if
7234   // they're real types (i.e. non-complex, non-pointer scalar types).
7235   if (!type->isRealType()) return false;
7236 
7237   len = 1;
7238   eltType = type;
7239   return true;
7240 }
7241 
7242 /// Are the two types lax-compatible vector types?  That is, given
7243 /// that one of them is a vector, do they have equal storage sizes,
7244 /// where the storage size is the number of elements times the element
7245 /// size?
7246 ///
7247 /// This will also return false if either of the types is neither a
7248 /// vector nor a real type.
7249 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
7250   assert(destTy->isVectorType() || srcTy->isVectorType());
7251 
7252   // Disallow lax conversions between scalars and ExtVectors (these
7253   // conversions are allowed for other vector types because common headers
7254   // depend on them).  Most scalar OP ExtVector cases are handled by the
7255   // splat path anyway, which does what we want (convert, not bitcast).
7256   // What this rules out for ExtVectors is crazy things like char4*float.
7257   if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
7258   if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
7259 
7260   uint64_t srcLen, destLen;
7261   QualType srcEltTy, destEltTy;
7262   if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false;
7263   if (!breakDownVectorType(destTy, destLen, destEltTy)) return false;
7264 
7265   // ASTContext::getTypeSize will return the size rounded up to a
7266   // power of 2, so instead of using that, we need to use the raw
7267   // element size multiplied by the element count.
7268   uint64_t srcEltSize = Context.getTypeSize(srcEltTy);
7269   uint64_t destEltSize = Context.getTypeSize(destEltTy);
7270 
7271   return (srcLen * srcEltSize == destLen * destEltSize);
7272 }
7273 
7274 /// Is this a legal conversion between two types, one of which is
7275 /// known to be a vector type?
7276 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
7277   assert(destTy->isVectorType() || srcTy->isVectorType());
7278 
7279   switch (Context.getLangOpts().getLaxVectorConversions()) {
7280   case LangOptions::LaxVectorConversionKind::None:
7281     return false;
7282 
7283   case LangOptions::LaxVectorConversionKind::Integer:
7284     if (!srcTy->isIntegralOrEnumerationType()) {
7285       auto *Vec = srcTy->getAs<VectorType>();
7286       if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7287         return false;
7288     }
7289     if (!destTy->isIntegralOrEnumerationType()) {
7290       auto *Vec = destTy->getAs<VectorType>();
7291       if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7292         return false;
7293     }
7294     // OK, integer (vector) -> integer (vector) bitcast.
7295     break;
7296 
7297     case LangOptions::LaxVectorConversionKind::All:
7298     break;
7299   }
7300 
7301   return areLaxCompatibleVectorTypes(srcTy, destTy);
7302 }
7303 
7304 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
7305                            CastKind &Kind) {
7306   assert(VectorTy->isVectorType() && "Not a vector type!");
7307 
7308   if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
7309     if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
7310       return Diag(R.getBegin(),
7311                   Ty->isVectorType() ?
7312                   diag::err_invalid_conversion_between_vectors :
7313                   diag::err_invalid_conversion_between_vector_and_integer)
7314         << VectorTy << Ty << R;
7315   } else
7316     return Diag(R.getBegin(),
7317                 diag::err_invalid_conversion_between_vector_and_scalar)
7318       << VectorTy << Ty << R;
7319 
7320   Kind = CK_BitCast;
7321   return false;
7322 }
7323 
7324 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
7325   QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
7326 
7327   if (DestElemTy == SplattedExpr->getType())
7328     return SplattedExpr;
7329 
7330   assert(DestElemTy->isFloatingType() ||
7331          DestElemTy->isIntegralOrEnumerationType());
7332 
7333   CastKind CK;
7334   if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
7335     // OpenCL requires that we convert `true` boolean expressions to -1, but
7336     // only when splatting vectors.
7337     if (DestElemTy->isFloatingType()) {
7338       // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
7339       // in two steps: boolean to signed integral, then to floating.
7340       ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
7341                                                  CK_BooleanToSignedIntegral);
7342       SplattedExpr = CastExprRes.get();
7343       CK = CK_IntegralToFloating;
7344     } else {
7345       CK = CK_BooleanToSignedIntegral;
7346     }
7347   } else {
7348     ExprResult CastExprRes = SplattedExpr;
7349     CK = PrepareScalarCast(CastExprRes, DestElemTy);
7350     if (CastExprRes.isInvalid())
7351       return ExprError();
7352     SplattedExpr = CastExprRes.get();
7353   }
7354   return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
7355 }
7356 
7357 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
7358                                     Expr *CastExpr, CastKind &Kind) {
7359   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
7360 
7361   QualType SrcTy = CastExpr->getType();
7362 
7363   // If SrcTy is a VectorType, the total size must match to explicitly cast to
7364   // an ExtVectorType.
7365   // In OpenCL, casts between vectors of different types are not allowed.
7366   // (See OpenCL 6.2).
7367   if (SrcTy->isVectorType()) {
7368     if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
7369         (getLangOpts().OpenCL &&
7370          !Context.hasSameUnqualifiedType(DestTy, SrcTy))) {
7371       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
7372         << DestTy << SrcTy << R;
7373       return ExprError();
7374     }
7375     Kind = CK_BitCast;
7376     return CastExpr;
7377   }
7378 
7379   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
7380   // conversion will take place first from scalar to elt type, and then
7381   // splat from elt type to vector.
7382   if (SrcTy->isPointerType())
7383     return Diag(R.getBegin(),
7384                 diag::err_invalid_conversion_between_vector_and_scalar)
7385       << DestTy << SrcTy << R;
7386 
7387   Kind = CK_VectorSplat;
7388   return prepareVectorSplat(DestTy, CastExpr);
7389 }
7390 
7391 ExprResult
7392 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
7393                     Declarator &D, ParsedType &Ty,
7394                     SourceLocation RParenLoc, Expr *CastExpr) {
7395   assert(!D.isInvalidType() && (CastExpr != nullptr) &&
7396          "ActOnCastExpr(): missing type or expr");
7397 
7398   TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
7399   if (D.isInvalidType())
7400     return ExprError();
7401 
7402   if (getLangOpts().CPlusPlus) {
7403     // Check that there are no default arguments (C++ only).
7404     CheckExtraCXXDefaultArguments(D);
7405   } else {
7406     // Make sure any TypoExprs have been dealt with.
7407     ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
7408     if (!Res.isUsable())
7409       return ExprError();
7410     CastExpr = Res.get();
7411   }
7412 
7413   checkUnusedDeclAttributes(D);
7414 
7415   QualType castType = castTInfo->getType();
7416   Ty = CreateParsedType(castType, castTInfo);
7417 
7418   bool isVectorLiteral = false;
7419 
7420   // Check for an altivec or OpenCL literal,
7421   // i.e. all the elements are integer constants.
7422   ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
7423   ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
7424   if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
7425        && castType->isVectorType() && (PE || PLE)) {
7426     if (PLE && PLE->getNumExprs() == 0) {
7427       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
7428       return ExprError();
7429     }
7430     if (PE || PLE->getNumExprs() == 1) {
7431       Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
7432       if (!E->getType()->isVectorType())
7433         isVectorLiteral = true;
7434     }
7435     else
7436       isVectorLiteral = true;
7437   }
7438 
7439   // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
7440   // then handle it as such.
7441   if (isVectorLiteral)
7442     return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
7443 
7444   // If the Expr being casted is a ParenListExpr, handle it specially.
7445   // This is not an AltiVec-style cast, so turn the ParenListExpr into a
7446   // sequence of BinOp comma operators.
7447   if (isa<ParenListExpr>(CastExpr)) {
7448     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
7449     if (Result.isInvalid()) return ExprError();
7450     CastExpr = Result.get();
7451   }
7452 
7453   if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
7454       !getSourceManager().isInSystemMacro(LParenLoc))
7455     Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
7456 
7457   CheckTollFreeBridgeCast(castType, CastExpr);
7458 
7459   CheckObjCBridgeRelatedCast(castType, CastExpr);
7460 
7461   DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
7462 
7463   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
7464 }
7465 
7466 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
7467                                     SourceLocation RParenLoc, Expr *E,
7468                                     TypeSourceInfo *TInfo) {
7469   assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
7470          "Expected paren or paren list expression");
7471 
7472   Expr **exprs;
7473   unsigned numExprs;
7474   Expr *subExpr;
7475   SourceLocation LiteralLParenLoc, LiteralRParenLoc;
7476   if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
7477     LiteralLParenLoc = PE->getLParenLoc();
7478     LiteralRParenLoc = PE->getRParenLoc();
7479     exprs = PE->getExprs();
7480     numExprs = PE->getNumExprs();
7481   } else { // isa<ParenExpr> by assertion at function entrance
7482     LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
7483     LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
7484     subExpr = cast<ParenExpr>(E)->getSubExpr();
7485     exprs = &subExpr;
7486     numExprs = 1;
7487   }
7488 
7489   QualType Ty = TInfo->getType();
7490   assert(Ty->isVectorType() && "Expected vector type");
7491 
7492   SmallVector<Expr *, 8> initExprs;
7493   const VectorType *VTy = Ty->castAs<VectorType>();
7494   unsigned numElems = VTy->getNumElements();
7495 
7496   // '(...)' form of vector initialization in AltiVec: the number of
7497   // initializers must be one or must match the size of the vector.
7498   // If a single value is specified in the initializer then it will be
7499   // replicated to all the components of the vector
7500   if (VTy->getVectorKind() == VectorType::AltiVecVector) {
7501     // The number of initializers must be one or must match the size of the
7502     // vector. If a single value is specified in the initializer then it will
7503     // be replicated to all the components of the vector
7504     if (numExprs == 1) {
7505       QualType ElemTy = VTy->getElementType();
7506       ExprResult Literal = DefaultLvalueConversion(exprs[0]);
7507       if (Literal.isInvalid())
7508         return ExprError();
7509       Literal = ImpCastExprToType(Literal.get(), ElemTy,
7510                                   PrepareScalarCast(Literal, ElemTy));
7511       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
7512     }
7513     else if (numExprs < numElems) {
7514       Diag(E->getExprLoc(),
7515            diag::err_incorrect_number_of_vector_initializers);
7516       return ExprError();
7517     }
7518     else
7519       initExprs.append(exprs, exprs + numExprs);
7520   }
7521   else {
7522     // For OpenCL, when the number of initializers is a single value,
7523     // it will be replicated to all components of the vector.
7524     if (getLangOpts().OpenCL &&
7525         VTy->getVectorKind() == VectorType::GenericVector &&
7526         numExprs == 1) {
7527         QualType ElemTy = VTy->getElementType();
7528         ExprResult Literal = DefaultLvalueConversion(exprs[0]);
7529         if (Literal.isInvalid())
7530           return ExprError();
7531         Literal = ImpCastExprToType(Literal.get(), ElemTy,
7532                                     PrepareScalarCast(Literal, ElemTy));
7533         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
7534     }
7535 
7536     initExprs.append(exprs, exprs + numExprs);
7537   }
7538   // FIXME: This means that pretty-printing the final AST will produce curly
7539   // braces instead of the original commas.
7540   InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
7541                                                    initExprs, LiteralRParenLoc);
7542   initE->setType(Ty);
7543   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
7544 }
7545 
7546 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
7547 /// the ParenListExpr into a sequence of comma binary operators.
7548 ExprResult
7549 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
7550   ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
7551   if (!E)
7552     return OrigExpr;
7553 
7554   ExprResult Result(E->getExpr(0));
7555 
7556   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
7557     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
7558                         E->getExpr(i));
7559 
7560   if (Result.isInvalid()) return ExprError();
7561 
7562   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
7563 }
7564 
7565 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
7566                                     SourceLocation R,
7567                                     MultiExprArg Val) {
7568   return ParenListExpr::Create(Context, L, Val, R);
7569 }
7570 
7571 /// Emit a specialized diagnostic when one expression is a null pointer
7572 /// constant and the other is not a pointer.  Returns true if a diagnostic is
7573 /// emitted.
7574 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
7575                                       SourceLocation QuestionLoc) {
7576   Expr *NullExpr = LHSExpr;
7577   Expr *NonPointerExpr = RHSExpr;
7578   Expr::NullPointerConstantKind NullKind =
7579       NullExpr->isNullPointerConstant(Context,
7580                                       Expr::NPC_ValueDependentIsNotNull);
7581 
7582   if (NullKind == Expr::NPCK_NotNull) {
7583     NullExpr = RHSExpr;
7584     NonPointerExpr = LHSExpr;
7585     NullKind =
7586         NullExpr->isNullPointerConstant(Context,
7587                                         Expr::NPC_ValueDependentIsNotNull);
7588   }
7589 
7590   if (NullKind == Expr::NPCK_NotNull)
7591     return false;
7592 
7593   if (NullKind == Expr::NPCK_ZeroExpression)
7594     return false;
7595 
7596   if (NullKind == Expr::NPCK_ZeroLiteral) {
7597     // In this case, check to make sure that we got here from a "NULL"
7598     // string in the source code.
7599     NullExpr = NullExpr->IgnoreParenImpCasts();
7600     SourceLocation loc = NullExpr->getExprLoc();
7601     if (!findMacroSpelling(loc, "NULL"))
7602       return false;
7603   }
7604 
7605   int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
7606   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
7607       << NonPointerExpr->getType() << DiagType
7608       << NonPointerExpr->getSourceRange();
7609   return true;
7610 }
7611 
7612 /// Return false if the condition expression is valid, true otherwise.
7613 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
7614   QualType CondTy = Cond->getType();
7615 
7616   // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
7617   if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
7618     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
7619       << CondTy << Cond->getSourceRange();
7620     return true;
7621   }
7622 
7623   // C99 6.5.15p2
7624   if (CondTy->isScalarType()) return false;
7625 
7626   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
7627     << CondTy << Cond->getSourceRange();
7628   return true;
7629 }
7630 
7631 /// Handle when one or both operands are void type.
7632 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
7633                                          ExprResult &RHS) {
7634     Expr *LHSExpr = LHS.get();
7635     Expr *RHSExpr = RHS.get();
7636 
7637     if (!LHSExpr->getType()->isVoidType())
7638       S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
7639           << RHSExpr->getSourceRange();
7640     if (!RHSExpr->getType()->isVoidType())
7641       S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
7642           << LHSExpr->getSourceRange();
7643     LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
7644     RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
7645     return S.Context.VoidTy;
7646 }
7647 
7648 /// Return false if the NullExpr can be promoted to PointerTy,
7649 /// true otherwise.
7650 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
7651                                         QualType PointerTy) {
7652   if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
7653       !NullExpr.get()->isNullPointerConstant(S.Context,
7654                                             Expr::NPC_ValueDependentIsNull))
7655     return true;
7656 
7657   NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
7658   return false;
7659 }
7660 
7661 /// Checks compatibility between two pointers and return the resulting
7662 /// type.
7663 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
7664                                                      ExprResult &RHS,
7665                                                      SourceLocation Loc) {
7666   QualType LHSTy = LHS.get()->getType();
7667   QualType RHSTy = RHS.get()->getType();
7668 
7669   if (S.Context.hasSameType(LHSTy, RHSTy)) {
7670     // Two identical pointers types are always compatible.
7671     return LHSTy;
7672   }
7673 
7674   QualType lhptee, rhptee;
7675 
7676   // Get the pointee types.
7677   bool IsBlockPointer = false;
7678   if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
7679     lhptee = LHSBTy->getPointeeType();
7680     rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
7681     IsBlockPointer = true;
7682   } else {
7683     lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
7684     rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
7685   }
7686 
7687   // C99 6.5.15p6: If both operands are pointers to compatible types or to
7688   // differently qualified versions of compatible types, the result type is
7689   // a pointer to an appropriately qualified version of the composite
7690   // type.
7691 
7692   // Only CVR-qualifiers exist in the standard, and the differently-qualified
7693   // clause doesn't make sense for our extensions. E.g. address space 2 should
7694   // be incompatible with address space 3: they may live on different devices or
7695   // anything.
7696   Qualifiers lhQual = lhptee.getQualifiers();
7697   Qualifiers rhQual = rhptee.getQualifiers();
7698 
7699   LangAS ResultAddrSpace = LangAS::Default;
7700   LangAS LAddrSpace = lhQual.getAddressSpace();
7701   LangAS RAddrSpace = rhQual.getAddressSpace();
7702 
7703   // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
7704   // spaces is disallowed.
7705   if (lhQual.isAddressSpaceSupersetOf(rhQual))
7706     ResultAddrSpace = LAddrSpace;
7707   else if (rhQual.isAddressSpaceSupersetOf(lhQual))
7708     ResultAddrSpace = RAddrSpace;
7709   else {
7710     S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
7711         << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
7712         << RHS.get()->getSourceRange();
7713     return QualType();
7714   }
7715 
7716   unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
7717   auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
7718   lhQual.removeCVRQualifiers();
7719   rhQual.removeCVRQualifiers();
7720 
7721   // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
7722   // (C99 6.7.3) for address spaces. We assume that the check should behave in
7723   // the same manner as it's defined for CVR qualifiers, so for OpenCL two
7724   // qual types are compatible iff
7725   //  * corresponded types are compatible
7726   //  * CVR qualifiers are equal
7727   //  * address spaces are equal
7728   // Thus for conditional operator we merge CVR and address space unqualified
7729   // pointees and if there is a composite type we return a pointer to it with
7730   // merged qualifiers.
7731   LHSCastKind =
7732       LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
7733   RHSCastKind =
7734       RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
7735   lhQual.removeAddressSpace();
7736   rhQual.removeAddressSpace();
7737 
7738   lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
7739   rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
7740 
7741   QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
7742 
7743   if (CompositeTy.isNull()) {
7744     // In this situation, we assume void* type. No especially good
7745     // reason, but this is what gcc does, and we do have to pick
7746     // to get a consistent AST.
7747     QualType incompatTy;
7748     incompatTy = S.Context.getPointerType(
7749         S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
7750     LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
7751     RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
7752 
7753     // FIXME: For OpenCL the warning emission and cast to void* leaves a room
7754     // for casts between types with incompatible address space qualifiers.
7755     // For the following code the compiler produces casts between global and
7756     // local address spaces of the corresponded innermost pointees:
7757     // local int *global *a;
7758     // global int *global *b;
7759     // a = (0 ? a : b); // see C99 6.5.16.1.p1.
7760     S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
7761         << LHSTy << RHSTy << LHS.get()->getSourceRange()
7762         << RHS.get()->getSourceRange();
7763 
7764     return incompatTy;
7765   }
7766 
7767   // The pointer types are compatible.
7768   // In case of OpenCL ResultTy should have the address space qualifier
7769   // which is a superset of address spaces of both the 2nd and the 3rd
7770   // operands of the conditional operator.
7771   QualType ResultTy = [&, ResultAddrSpace]() {
7772     if (S.getLangOpts().OpenCL) {
7773       Qualifiers CompositeQuals = CompositeTy.getQualifiers();
7774       CompositeQuals.setAddressSpace(ResultAddrSpace);
7775       return S.Context
7776           .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
7777           .withCVRQualifiers(MergedCVRQual);
7778     }
7779     return CompositeTy.withCVRQualifiers(MergedCVRQual);
7780   }();
7781   if (IsBlockPointer)
7782     ResultTy = S.Context.getBlockPointerType(ResultTy);
7783   else
7784     ResultTy = S.Context.getPointerType(ResultTy);
7785 
7786   LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
7787   RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
7788   return ResultTy;
7789 }
7790 
7791 /// Return the resulting type when the operands are both block pointers.
7792 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
7793                                                           ExprResult &LHS,
7794                                                           ExprResult &RHS,
7795                                                           SourceLocation Loc) {
7796   QualType LHSTy = LHS.get()->getType();
7797   QualType RHSTy = RHS.get()->getType();
7798 
7799   if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
7800     if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
7801       QualType destType = S.Context.getPointerType(S.Context.VoidTy);
7802       LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
7803       RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
7804       return destType;
7805     }
7806     S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
7807       << LHSTy << RHSTy << LHS.get()->getSourceRange()
7808       << RHS.get()->getSourceRange();
7809     return QualType();
7810   }
7811 
7812   // We have 2 block pointer types.
7813   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
7814 }
7815 
7816 /// Return the resulting type when the operands are both pointers.
7817 static QualType
7818 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
7819                                             ExprResult &RHS,
7820                                             SourceLocation Loc) {
7821   // get the pointer types
7822   QualType LHSTy = LHS.get()->getType();
7823   QualType RHSTy = RHS.get()->getType();
7824 
7825   // get the "pointed to" types
7826   QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
7827   QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
7828 
7829   // ignore qualifiers on void (C99 6.5.15p3, clause 6)
7830   if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
7831     // Figure out necessary qualifiers (C99 6.5.15p6)
7832     QualType destPointee
7833       = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
7834     QualType destType = S.Context.getPointerType(destPointee);
7835     // Add qualifiers if necessary.
7836     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
7837     // Promote to void*.
7838     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
7839     return destType;
7840   }
7841   if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
7842     QualType destPointee
7843       = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
7844     QualType destType = S.Context.getPointerType(destPointee);
7845     // Add qualifiers if necessary.
7846     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
7847     // Promote to void*.
7848     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
7849     return destType;
7850   }
7851 
7852   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
7853 }
7854 
7855 /// Return false if the first expression is not an integer and the second
7856 /// expression is not a pointer, true otherwise.
7857 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
7858                                         Expr* PointerExpr, SourceLocation Loc,
7859                                         bool IsIntFirstExpr) {
7860   if (!PointerExpr->getType()->isPointerType() ||
7861       !Int.get()->getType()->isIntegerType())
7862     return false;
7863 
7864   Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
7865   Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
7866 
7867   S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
7868     << Expr1->getType() << Expr2->getType()
7869     << Expr1->getSourceRange() << Expr2->getSourceRange();
7870   Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
7871                             CK_IntegralToPointer);
7872   return true;
7873 }
7874 
7875 /// Simple conversion between integer and floating point types.
7876 ///
7877 /// Used when handling the OpenCL conditional operator where the
7878 /// condition is a vector while the other operands are scalar.
7879 ///
7880 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
7881 /// types are either integer or floating type. Between the two
7882 /// operands, the type with the higher rank is defined as the "result
7883 /// type". The other operand needs to be promoted to the same type. No
7884 /// other type promotion is allowed. We cannot use
7885 /// UsualArithmeticConversions() for this purpose, since it always
7886 /// promotes promotable types.
7887 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
7888                                             ExprResult &RHS,
7889                                             SourceLocation QuestionLoc) {
7890   LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
7891   if (LHS.isInvalid())
7892     return QualType();
7893   RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
7894   if (RHS.isInvalid())
7895     return QualType();
7896 
7897   // For conversion purposes, we ignore any qualifiers.
7898   // For example, "const float" and "float" are equivalent.
7899   QualType LHSType =
7900     S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
7901   QualType RHSType =
7902     S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
7903 
7904   if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
7905     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
7906       << LHSType << LHS.get()->getSourceRange();
7907     return QualType();
7908   }
7909 
7910   if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
7911     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
7912       << RHSType << RHS.get()->getSourceRange();
7913     return QualType();
7914   }
7915 
7916   // If both types are identical, no conversion is needed.
7917   if (LHSType == RHSType)
7918     return LHSType;
7919 
7920   // Now handle "real" floating types (i.e. float, double, long double).
7921   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
7922     return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
7923                                  /*IsCompAssign = */ false);
7924 
7925   // Finally, we have two differing integer types.
7926   return handleIntegerConversion<doIntegralCast, doIntegralCast>
7927   (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
7928 }
7929 
7930 /// Convert scalar operands to a vector that matches the
7931 ///        condition in length.
7932 ///
7933 /// Used when handling the OpenCL conditional operator where the
7934 /// condition is a vector while the other operands are scalar.
7935 ///
7936 /// We first compute the "result type" for the scalar operands
7937 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
7938 /// into a vector of that type where the length matches the condition
7939 /// vector type. s6.11.6 requires that the element types of the result
7940 /// and the condition must have the same number of bits.
7941 static QualType
7942 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
7943                               QualType CondTy, SourceLocation QuestionLoc) {
7944   QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
7945   if (ResTy.isNull()) return QualType();
7946 
7947   const VectorType *CV = CondTy->getAs<VectorType>();
7948   assert(CV);
7949 
7950   // Determine the vector result type
7951   unsigned NumElements = CV->getNumElements();
7952   QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
7953 
7954   // Ensure that all types have the same number of bits
7955   if (S.Context.getTypeSize(CV->getElementType())
7956       != S.Context.getTypeSize(ResTy)) {
7957     // Since VectorTy is created internally, it does not pretty print
7958     // with an OpenCL name. Instead, we just print a description.
7959     std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
7960     SmallString<64> Str;
7961     llvm::raw_svector_ostream OS(Str);
7962     OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
7963     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
7964       << CondTy << OS.str();
7965     return QualType();
7966   }
7967 
7968   // Convert operands to the vector result type
7969   LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
7970   RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
7971 
7972   return VectorTy;
7973 }
7974 
7975 /// Return false if this is a valid OpenCL condition vector
7976 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
7977                                        SourceLocation QuestionLoc) {
7978   // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
7979   // integral type.
7980   const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
7981   assert(CondTy);
7982   QualType EleTy = CondTy->getElementType();
7983   if (EleTy->isIntegerType()) return false;
7984 
7985   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
7986     << Cond->getType() << Cond->getSourceRange();
7987   return true;
7988 }
7989 
7990 /// Return false if the vector condition type and the vector
7991 ///        result type are compatible.
7992 ///
7993 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
7994 /// number of elements, and their element types have the same number
7995 /// of bits.
7996 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
7997                               SourceLocation QuestionLoc) {
7998   const VectorType *CV = CondTy->getAs<VectorType>();
7999   const VectorType *RV = VecResTy->getAs<VectorType>();
8000   assert(CV && RV);
8001 
8002   if (CV->getNumElements() != RV->getNumElements()) {
8003     S.Diag(QuestionLoc, diag::err_conditional_vector_size)
8004       << CondTy << VecResTy;
8005     return true;
8006   }
8007 
8008   QualType CVE = CV->getElementType();
8009   QualType RVE = RV->getElementType();
8010 
8011   if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
8012     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
8013       << CondTy << VecResTy;
8014     return true;
8015   }
8016 
8017   return false;
8018 }
8019 
8020 /// Return the resulting type for the conditional operator in
8021 ///        OpenCL (aka "ternary selection operator", OpenCL v1.1
8022 ///        s6.3.i) when the condition is a vector type.
8023 static QualType
8024 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
8025                              ExprResult &LHS, ExprResult &RHS,
8026                              SourceLocation QuestionLoc) {
8027   Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
8028   if (Cond.isInvalid())
8029     return QualType();
8030   QualType CondTy = Cond.get()->getType();
8031 
8032   if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
8033     return QualType();
8034 
8035   // If either operand is a vector then find the vector type of the
8036   // result as specified in OpenCL v1.1 s6.3.i.
8037   if (LHS.get()->getType()->isVectorType() ||
8038       RHS.get()->getType()->isVectorType()) {
8039     QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
8040                                               /*isCompAssign*/false,
8041                                               /*AllowBothBool*/true,
8042                                               /*AllowBoolConversions*/false);
8043     if (VecResTy.isNull()) return QualType();
8044     // The result type must match the condition type as specified in
8045     // OpenCL v1.1 s6.11.6.
8046     if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
8047       return QualType();
8048     return VecResTy;
8049   }
8050 
8051   // Both operands are scalar.
8052   return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
8053 }
8054 
8055 /// Return true if the Expr is block type
8056 static bool checkBlockType(Sema &S, const Expr *E) {
8057   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
8058     QualType Ty = CE->getCallee()->getType();
8059     if (Ty->isBlockPointerType()) {
8060       S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
8061       return true;
8062     }
8063   }
8064   return false;
8065 }
8066 
8067 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
8068 /// In that case, LHS = cond.
8069 /// C99 6.5.15
8070 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
8071                                         ExprResult &RHS, ExprValueKind &VK,
8072                                         ExprObjectKind &OK,
8073                                         SourceLocation QuestionLoc) {
8074 
8075   ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
8076   if (!LHSResult.isUsable()) return QualType();
8077   LHS = LHSResult;
8078 
8079   ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
8080   if (!RHSResult.isUsable()) return QualType();
8081   RHS = RHSResult;
8082 
8083   // C++ is sufficiently different to merit its own checker.
8084   if (getLangOpts().CPlusPlus)
8085     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
8086 
8087   VK = VK_RValue;
8088   OK = OK_Ordinary;
8089 
8090   // The OpenCL operator with a vector condition is sufficiently
8091   // different to merit its own checker.
8092   if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) ||
8093       Cond.get()->getType()->isExtVectorType())
8094     return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
8095 
8096   // First, check the condition.
8097   Cond = UsualUnaryConversions(Cond.get());
8098   if (Cond.isInvalid())
8099     return QualType();
8100   if (checkCondition(*this, Cond.get(), QuestionLoc))
8101     return QualType();
8102 
8103   // Now check the two expressions.
8104   if (LHS.get()->getType()->isVectorType() ||
8105       RHS.get()->getType()->isVectorType())
8106     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
8107                                /*AllowBothBool*/true,
8108                                /*AllowBoolConversions*/false);
8109 
8110   QualType ResTy =
8111       UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional);
8112   if (LHS.isInvalid() || RHS.isInvalid())
8113     return QualType();
8114 
8115   QualType LHSTy = LHS.get()->getType();
8116   QualType RHSTy = RHS.get()->getType();
8117 
8118   // Diagnose attempts to convert between __float128 and long double where
8119   // such conversions currently can't be handled.
8120   if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
8121     Diag(QuestionLoc,
8122          diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
8123       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8124     return QualType();
8125   }
8126 
8127   // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
8128   // selection operator (?:).
8129   if (getLangOpts().OpenCL &&
8130       (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) {
8131     return QualType();
8132   }
8133 
8134   // If both operands have arithmetic type, do the usual arithmetic conversions
8135   // to find a common type: C99 6.5.15p3,5.
8136   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
8137     LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
8138     RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
8139 
8140     return ResTy;
8141   }
8142 
8143   // And if they're both bfloat (which isn't arithmetic), that's fine too.
8144   if (LHSTy->isBFloat16Type() && RHSTy->isBFloat16Type()) {
8145     return LHSTy;
8146   }
8147 
8148   // If both operands are the same structure or union type, the result is that
8149   // type.
8150   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
8151     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
8152       if (LHSRT->getDecl() == RHSRT->getDecl())
8153         // "If both the operands have structure or union type, the result has
8154         // that type."  This implies that CV qualifiers are dropped.
8155         return LHSTy.getUnqualifiedType();
8156     // FIXME: Type of conditional expression must be complete in C mode.
8157   }
8158 
8159   // C99 6.5.15p5: "If both operands have void type, the result has void type."
8160   // The following || allows only one side to be void (a GCC-ism).
8161   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
8162     return checkConditionalVoidType(*this, LHS, RHS);
8163   }
8164 
8165   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
8166   // the type of the other operand."
8167   if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
8168   if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
8169 
8170   // All objective-c pointer type analysis is done here.
8171   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
8172                                                         QuestionLoc);
8173   if (LHS.isInvalid() || RHS.isInvalid())
8174     return QualType();
8175   if (!compositeType.isNull())
8176     return compositeType;
8177 
8178 
8179   // Handle block pointer types.
8180   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
8181     return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
8182                                                      QuestionLoc);
8183 
8184   // Check constraints for C object pointers types (C99 6.5.15p3,6).
8185   if (LHSTy->isPointerType() && RHSTy->isPointerType())
8186     return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
8187                                                        QuestionLoc);
8188 
8189   // GCC compatibility: soften pointer/integer mismatch.  Note that
8190   // null pointers have been filtered out by this point.
8191   if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
8192       /*IsIntFirstExpr=*/true))
8193     return RHSTy;
8194   if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
8195       /*IsIntFirstExpr=*/false))
8196     return LHSTy;
8197 
8198   // Allow ?: operations in which both operands have the same
8199   // built-in sizeless type.
8200   if (LHSTy->isSizelessBuiltinType() && LHSTy == RHSTy)
8201     return LHSTy;
8202 
8203   // Emit a better diagnostic if one of the expressions is a null pointer
8204   // constant and the other is not a pointer type. In this case, the user most
8205   // likely forgot to take the address of the other expression.
8206   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
8207     return QualType();
8208 
8209   // Otherwise, the operands are not compatible.
8210   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
8211     << LHSTy << RHSTy << LHS.get()->getSourceRange()
8212     << RHS.get()->getSourceRange();
8213   return QualType();
8214 }
8215 
8216 /// FindCompositeObjCPointerType - Helper method to find composite type of
8217 /// two objective-c pointer types of the two input expressions.
8218 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
8219                                             SourceLocation QuestionLoc) {
8220   QualType LHSTy = LHS.get()->getType();
8221   QualType RHSTy = RHS.get()->getType();
8222 
8223   // Handle things like Class and struct objc_class*.  Here we case the result
8224   // to the pseudo-builtin, because that will be implicitly cast back to the
8225   // redefinition type if an attempt is made to access its fields.
8226   if (LHSTy->isObjCClassType() &&
8227       (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
8228     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
8229     return LHSTy;
8230   }
8231   if (RHSTy->isObjCClassType() &&
8232       (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
8233     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
8234     return RHSTy;
8235   }
8236   // And the same for struct objc_object* / id
8237   if (LHSTy->isObjCIdType() &&
8238       (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
8239     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
8240     return LHSTy;
8241   }
8242   if (RHSTy->isObjCIdType() &&
8243       (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
8244     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
8245     return RHSTy;
8246   }
8247   // And the same for struct objc_selector* / SEL
8248   if (Context.isObjCSelType(LHSTy) &&
8249       (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
8250     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
8251     return LHSTy;
8252   }
8253   if (Context.isObjCSelType(RHSTy) &&
8254       (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
8255     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
8256     return RHSTy;
8257   }
8258   // Check constraints for Objective-C object pointers types.
8259   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
8260 
8261     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
8262       // Two identical object pointer types are always compatible.
8263       return LHSTy;
8264     }
8265     const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
8266     const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
8267     QualType compositeType = LHSTy;
8268 
8269     // If both operands are interfaces and either operand can be
8270     // assigned to the other, use that type as the composite
8271     // type. This allows
8272     //   xxx ? (A*) a : (B*) b
8273     // where B is a subclass of A.
8274     //
8275     // Additionally, as for assignment, if either type is 'id'
8276     // allow silent coercion. Finally, if the types are
8277     // incompatible then make sure to use 'id' as the composite
8278     // type so the result is acceptable for sending messages to.
8279 
8280     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
8281     // It could return the composite type.
8282     if (!(compositeType =
8283           Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
8284       // Nothing more to do.
8285     } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
8286       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
8287     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
8288       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
8289     } else if ((LHSOPT->isObjCQualifiedIdType() ||
8290                 RHSOPT->isObjCQualifiedIdType()) &&
8291                Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT,
8292                                                          true)) {
8293       // Need to handle "id<xx>" explicitly.
8294       // GCC allows qualified id and any Objective-C type to devolve to
8295       // id. Currently localizing to here until clear this should be
8296       // part of ObjCQualifiedIdTypesAreCompatible.
8297       compositeType = Context.getObjCIdType();
8298     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
8299       compositeType = Context.getObjCIdType();
8300     } else {
8301       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
8302       << LHSTy << RHSTy
8303       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8304       QualType incompatTy = Context.getObjCIdType();
8305       LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
8306       RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
8307       return incompatTy;
8308     }
8309     // The object pointer types are compatible.
8310     LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
8311     RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
8312     return compositeType;
8313   }
8314   // Check Objective-C object pointer types and 'void *'
8315   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
8316     if (getLangOpts().ObjCAutoRefCount) {
8317       // ARC forbids the implicit conversion of object pointers to 'void *',
8318       // so these types are not compatible.
8319       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
8320           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8321       LHS = RHS = true;
8322       return QualType();
8323     }
8324     QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8325     QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
8326     QualType destPointee
8327     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
8328     QualType destType = Context.getPointerType(destPointee);
8329     // Add qualifiers if necessary.
8330     LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
8331     // Promote to void*.
8332     RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8333     return destType;
8334   }
8335   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
8336     if (getLangOpts().ObjCAutoRefCount) {
8337       // ARC forbids the implicit conversion of object pointers to 'void *',
8338       // so these types are not compatible.
8339       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
8340           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8341       LHS = RHS = true;
8342       return QualType();
8343     }
8344     QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
8345     QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8346     QualType destPointee
8347     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
8348     QualType destType = Context.getPointerType(destPointee);
8349     // Add qualifiers if necessary.
8350     RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
8351     // Promote to void*.
8352     LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8353     return destType;
8354   }
8355   return QualType();
8356 }
8357 
8358 /// SuggestParentheses - Emit a note with a fixit hint that wraps
8359 /// ParenRange in parentheses.
8360 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
8361                                const PartialDiagnostic &Note,
8362                                SourceRange ParenRange) {
8363   SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
8364   if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
8365       EndLoc.isValid()) {
8366     Self.Diag(Loc, Note)
8367       << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
8368       << FixItHint::CreateInsertion(EndLoc, ")");
8369   } else {
8370     // We can't display the parentheses, so just show the bare note.
8371     Self.Diag(Loc, Note) << ParenRange;
8372   }
8373 }
8374 
8375 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
8376   return BinaryOperator::isAdditiveOp(Opc) ||
8377          BinaryOperator::isMultiplicativeOp(Opc) ||
8378          BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or;
8379   // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and
8380   // not any of the logical operators.  Bitwise-xor is commonly used as a
8381   // logical-xor because there is no logical-xor operator.  The logical
8382   // operators, including uses of xor, have a high false positive rate for
8383   // precedence warnings.
8384 }
8385 
8386 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
8387 /// expression, either using a built-in or overloaded operator,
8388 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
8389 /// expression.
8390 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
8391                                    Expr **RHSExprs) {
8392   // Don't strip parenthesis: we should not warn if E is in parenthesis.
8393   E = E->IgnoreImpCasts();
8394   E = E->IgnoreConversionOperator();
8395   E = E->IgnoreImpCasts();
8396   if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
8397     E = MTE->getSubExpr();
8398     E = E->IgnoreImpCasts();
8399   }
8400 
8401   // Built-in binary operator.
8402   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
8403     if (IsArithmeticOp(OP->getOpcode())) {
8404       *Opcode = OP->getOpcode();
8405       *RHSExprs = OP->getRHS();
8406       return true;
8407     }
8408   }
8409 
8410   // Overloaded operator.
8411   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
8412     if (Call->getNumArgs() != 2)
8413       return false;
8414 
8415     // Make sure this is really a binary operator that is safe to pass into
8416     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
8417     OverloadedOperatorKind OO = Call->getOperator();
8418     if (OO < OO_Plus || OO > OO_Arrow ||
8419         OO == OO_PlusPlus || OO == OO_MinusMinus)
8420       return false;
8421 
8422     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
8423     if (IsArithmeticOp(OpKind)) {
8424       *Opcode = OpKind;
8425       *RHSExprs = Call->getArg(1);
8426       return true;
8427     }
8428   }
8429 
8430   return false;
8431 }
8432 
8433 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
8434 /// or is a logical expression such as (x==y) which has int type, but is
8435 /// commonly interpreted as boolean.
8436 static bool ExprLooksBoolean(Expr *E) {
8437   E = E->IgnoreParenImpCasts();
8438 
8439   if (E->getType()->isBooleanType())
8440     return true;
8441   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
8442     return OP->isComparisonOp() || OP->isLogicalOp();
8443   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
8444     return OP->getOpcode() == UO_LNot;
8445   if (E->getType()->isPointerType())
8446     return true;
8447   // FIXME: What about overloaded operator calls returning "unspecified boolean
8448   // type"s (commonly pointer-to-members)?
8449 
8450   return false;
8451 }
8452 
8453 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
8454 /// and binary operator are mixed in a way that suggests the programmer assumed
8455 /// the conditional operator has higher precedence, for example:
8456 /// "int x = a + someBinaryCondition ? 1 : 2".
8457 static void DiagnoseConditionalPrecedence(Sema &Self,
8458                                           SourceLocation OpLoc,
8459                                           Expr *Condition,
8460                                           Expr *LHSExpr,
8461                                           Expr *RHSExpr) {
8462   BinaryOperatorKind CondOpcode;
8463   Expr *CondRHS;
8464 
8465   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
8466     return;
8467   if (!ExprLooksBoolean(CondRHS))
8468     return;
8469 
8470   // The condition is an arithmetic binary expression, with a right-
8471   // hand side that looks boolean, so warn.
8472 
8473   unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode)
8474                         ? diag::warn_precedence_bitwise_conditional
8475                         : diag::warn_precedence_conditional;
8476 
8477   Self.Diag(OpLoc, DiagID)
8478       << Condition->getSourceRange()
8479       << BinaryOperator::getOpcodeStr(CondOpcode);
8480 
8481   SuggestParentheses(
8482       Self, OpLoc,
8483       Self.PDiag(diag::note_precedence_silence)
8484           << BinaryOperator::getOpcodeStr(CondOpcode),
8485       SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
8486 
8487   SuggestParentheses(Self, OpLoc,
8488                      Self.PDiag(diag::note_precedence_conditional_first),
8489                      SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
8490 }
8491 
8492 /// Compute the nullability of a conditional expression.
8493 static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
8494                                               QualType LHSTy, QualType RHSTy,
8495                                               ASTContext &Ctx) {
8496   if (!ResTy->isAnyPointerType())
8497     return ResTy;
8498 
8499   auto GetNullability = [&Ctx](QualType Ty) {
8500     Optional<NullabilityKind> Kind = Ty->getNullability(Ctx);
8501     if (Kind)
8502       return *Kind;
8503     return NullabilityKind::Unspecified;
8504   };
8505 
8506   auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
8507   NullabilityKind MergedKind;
8508 
8509   // Compute nullability of a binary conditional expression.
8510   if (IsBin) {
8511     if (LHSKind == NullabilityKind::NonNull)
8512       MergedKind = NullabilityKind::NonNull;
8513     else
8514       MergedKind = RHSKind;
8515   // Compute nullability of a normal conditional expression.
8516   } else {
8517     if (LHSKind == NullabilityKind::Nullable ||
8518         RHSKind == NullabilityKind::Nullable)
8519       MergedKind = NullabilityKind::Nullable;
8520     else if (LHSKind == NullabilityKind::NonNull)
8521       MergedKind = RHSKind;
8522     else if (RHSKind == NullabilityKind::NonNull)
8523       MergedKind = LHSKind;
8524     else
8525       MergedKind = NullabilityKind::Unspecified;
8526   }
8527 
8528   // Return if ResTy already has the correct nullability.
8529   if (GetNullability(ResTy) == MergedKind)
8530     return ResTy;
8531 
8532   // Strip all nullability from ResTy.
8533   while (ResTy->getNullability(Ctx))
8534     ResTy = ResTy.getSingleStepDesugaredType(Ctx);
8535 
8536   // Create a new AttributedType with the new nullability kind.
8537   auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
8538   return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
8539 }
8540 
8541 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
8542 /// in the case of a the GNU conditional expr extension.
8543 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
8544                                     SourceLocation ColonLoc,
8545                                     Expr *CondExpr, Expr *LHSExpr,
8546                                     Expr *RHSExpr) {
8547   if (!getLangOpts().CPlusPlus) {
8548     // C cannot handle TypoExpr nodes in the condition because it
8549     // doesn't handle dependent types properly, so make sure any TypoExprs have
8550     // been dealt with before checking the operands.
8551     ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
8552     ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
8553     ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
8554 
8555     if (!CondResult.isUsable())
8556       return ExprError();
8557 
8558     if (LHSExpr) {
8559       if (!LHSResult.isUsable())
8560         return ExprError();
8561     }
8562 
8563     if (!RHSResult.isUsable())
8564       return ExprError();
8565 
8566     CondExpr = CondResult.get();
8567     LHSExpr = LHSResult.get();
8568     RHSExpr = RHSResult.get();
8569   }
8570 
8571   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
8572   // was the condition.
8573   OpaqueValueExpr *opaqueValue = nullptr;
8574   Expr *commonExpr = nullptr;
8575   if (!LHSExpr) {
8576     commonExpr = CondExpr;
8577     // Lower out placeholder types first.  This is important so that we don't
8578     // try to capture a placeholder. This happens in few cases in C++; such
8579     // as Objective-C++'s dictionary subscripting syntax.
8580     if (commonExpr->hasPlaceholderType()) {
8581       ExprResult result = CheckPlaceholderExpr(commonExpr);
8582       if (!result.isUsable()) return ExprError();
8583       commonExpr = result.get();
8584     }
8585     // We usually want to apply unary conversions *before* saving, except
8586     // in the special case of a C++ l-value conditional.
8587     if (!(getLangOpts().CPlusPlus
8588           && !commonExpr->isTypeDependent()
8589           && commonExpr->getValueKind() == RHSExpr->getValueKind()
8590           && commonExpr->isGLValue()
8591           && commonExpr->isOrdinaryOrBitFieldObject()
8592           && RHSExpr->isOrdinaryOrBitFieldObject()
8593           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
8594       ExprResult commonRes = UsualUnaryConversions(commonExpr);
8595       if (commonRes.isInvalid())
8596         return ExprError();
8597       commonExpr = commonRes.get();
8598     }
8599 
8600     // If the common expression is a class or array prvalue, materialize it
8601     // so that we can safely refer to it multiple times.
8602     if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() ||
8603                                    commonExpr->getType()->isArrayType())) {
8604       ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
8605       if (MatExpr.isInvalid())
8606         return ExprError();
8607       commonExpr = MatExpr.get();
8608     }
8609 
8610     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
8611                                                 commonExpr->getType(),
8612                                                 commonExpr->getValueKind(),
8613                                                 commonExpr->getObjectKind(),
8614                                                 commonExpr);
8615     LHSExpr = CondExpr = opaqueValue;
8616   }
8617 
8618   QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
8619   ExprValueKind VK = VK_RValue;
8620   ExprObjectKind OK = OK_Ordinary;
8621   ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
8622   QualType result = CheckConditionalOperands(Cond, LHS, RHS,
8623                                              VK, OK, QuestionLoc);
8624   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
8625       RHS.isInvalid())
8626     return ExprError();
8627 
8628   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
8629                                 RHS.get());
8630 
8631   CheckBoolLikeConversion(Cond.get(), QuestionLoc);
8632 
8633   result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
8634                                          Context);
8635 
8636   if (!commonExpr)
8637     return new (Context)
8638         ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
8639                             RHS.get(), result, VK, OK);
8640 
8641   return new (Context) BinaryConditionalOperator(
8642       commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
8643       ColonLoc, result, VK, OK);
8644 }
8645 
8646 // Check if we have a conversion between incompatible cmse function pointer
8647 // types, that is, a conversion between a function pointer with the
8648 // cmse_nonsecure_call attribute and one without.
8649 static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType,
8650                                           QualType ToType) {
8651   if (const auto *ToFn =
8652           dyn_cast<FunctionType>(S.Context.getCanonicalType(ToType))) {
8653     if (const auto *FromFn =
8654             dyn_cast<FunctionType>(S.Context.getCanonicalType(FromType))) {
8655       FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
8656       FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
8657 
8658       return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall();
8659     }
8660   }
8661   return false;
8662 }
8663 
8664 // checkPointerTypesForAssignment - This is a very tricky routine (despite
8665 // being closely modeled after the C99 spec:-). The odd characteristic of this
8666 // routine is it effectively iqnores the qualifiers on the top level pointee.
8667 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
8668 // FIXME: add a couple examples in this comment.
8669 static Sema::AssignConvertType
8670 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
8671   assert(LHSType.isCanonical() && "LHS not canonicalized!");
8672   assert(RHSType.isCanonical() && "RHS not canonicalized!");
8673 
8674   // get the "pointed to" type (ignoring qualifiers at the top level)
8675   const Type *lhptee, *rhptee;
8676   Qualifiers lhq, rhq;
8677   std::tie(lhptee, lhq) =
8678       cast<PointerType>(LHSType)->getPointeeType().split().asPair();
8679   std::tie(rhptee, rhq) =
8680       cast<PointerType>(RHSType)->getPointeeType().split().asPair();
8681 
8682   Sema::AssignConvertType ConvTy = Sema::Compatible;
8683 
8684   // C99 6.5.16.1p1: This following citation is common to constraints
8685   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
8686   // qualifiers of the type *pointed to* by the right;
8687 
8688   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
8689   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
8690       lhq.compatiblyIncludesObjCLifetime(rhq)) {
8691     // Ignore lifetime for further calculation.
8692     lhq.removeObjCLifetime();
8693     rhq.removeObjCLifetime();
8694   }
8695 
8696   if (!lhq.compatiblyIncludes(rhq)) {
8697     // Treat address-space mismatches as fatal.
8698     if (!lhq.isAddressSpaceSupersetOf(rhq))
8699       return Sema::IncompatiblePointerDiscardsQualifiers;
8700 
8701     // It's okay to add or remove GC or lifetime qualifiers when converting to
8702     // and from void*.
8703     else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
8704                         .compatiblyIncludes(
8705                                 rhq.withoutObjCGCAttr().withoutObjCLifetime())
8706              && (lhptee->isVoidType() || rhptee->isVoidType()))
8707       ; // keep old
8708 
8709     // Treat lifetime mismatches as fatal.
8710     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
8711       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
8712 
8713     // For GCC/MS compatibility, other qualifier mismatches are treated
8714     // as still compatible in C.
8715     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
8716   }
8717 
8718   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
8719   // incomplete type and the other is a pointer to a qualified or unqualified
8720   // version of void...
8721   if (lhptee->isVoidType()) {
8722     if (rhptee->isIncompleteOrObjectType())
8723       return ConvTy;
8724 
8725     // As an extension, we allow cast to/from void* to function pointer.
8726     assert(rhptee->isFunctionType());
8727     return Sema::FunctionVoidPointer;
8728   }
8729 
8730   if (rhptee->isVoidType()) {
8731     if (lhptee->isIncompleteOrObjectType())
8732       return ConvTy;
8733 
8734     // As an extension, we allow cast to/from void* to function pointer.
8735     assert(lhptee->isFunctionType());
8736     return Sema::FunctionVoidPointer;
8737   }
8738 
8739   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
8740   // unqualified versions of compatible types, ...
8741   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
8742   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
8743     // Check if the pointee types are compatible ignoring the sign.
8744     // We explicitly check for char so that we catch "char" vs
8745     // "unsigned char" on systems where "char" is unsigned.
8746     if (lhptee->isCharType())
8747       ltrans = S.Context.UnsignedCharTy;
8748     else if (lhptee->hasSignedIntegerRepresentation())
8749       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
8750 
8751     if (rhptee->isCharType())
8752       rtrans = S.Context.UnsignedCharTy;
8753     else if (rhptee->hasSignedIntegerRepresentation())
8754       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
8755 
8756     if (ltrans == rtrans) {
8757       // Types are compatible ignoring the sign. Qualifier incompatibility
8758       // takes priority over sign incompatibility because the sign
8759       // warning can be disabled.
8760       if (ConvTy != Sema::Compatible)
8761         return ConvTy;
8762 
8763       return Sema::IncompatiblePointerSign;
8764     }
8765 
8766     // If we are a multi-level pointer, it's possible that our issue is simply
8767     // one of qualification - e.g. char ** -> const char ** is not allowed. If
8768     // the eventual target type is the same and the pointers have the same
8769     // level of indirection, this must be the issue.
8770     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
8771       do {
8772         std::tie(lhptee, lhq) =
8773           cast<PointerType>(lhptee)->getPointeeType().split().asPair();
8774         std::tie(rhptee, rhq) =
8775           cast<PointerType>(rhptee)->getPointeeType().split().asPair();
8776 
8777         // Inconsistent address spaces at this point is invalid, even if the
8778         // address spaces would be compatible.
8779         // FIXME: This doesn't catch address space mismatches for pointers of
8780         // different nesting levels, like:
8781         //   __local int *** a;
8782         //   int ** b = a;
8783         // It's not clear how to actually determine when such pointers are
8784         // invalidly incompatible.
8785         if (lhq.getAddressSpace() != rhq.getAddressSpace())
8786           return Sema::IncompatibleNestedPointerAddressSpaceMismatch;
8787 
8788       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
8789 
8790       if (lhptee == rhptee)
8791         return Sema::IncompatibleNestedPointerQualifiers;
8792     }
8793 
8794     // General pointer incompatibility takes priority over qualifiers.
8795     if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType())
8796       return Sema::IncompatibleFunctionPointer;
8797     return Sema::IncompatiblePointer;
8798   }
8799   if (!S.getLangOpts().CPlusPlus &&
8800       S.IsFunctionConversion(ltrans, rtrans, ltrans))
8801     return Sema::IncompatibleFunctionPointer;
8802   if (IsInvalidCmseNSCallConversion(S, ltrans, rtrans))
8803     return Sema::IncompatibleFunctionPointer;
8804   return ConvTy;
8805 }
8806 
8807 /// checkBlockPointerTypesForAssignment - This routine determines whether two
8808 /// block pointer types are compatible or whether a block and normal pointer
8809 /// are compatible. It is more restrict than comparing two function pointer
8810 // types.
8811 static Sema::AssignConvertType
8812 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
8813                                     QualType RHSType) {
8814   assert(LHSType.isCanonical() && "LHS not canonicalized!");
8815   assert(RHSType.isCanonical() && "RHS not canonicalized!");
8816 
8817   QualType lhptee, rhptee;
8818 
8819   // get the "pointed to" type (ignoring qualifiers at the top level)
8820   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
8821   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
8822 
8823   // In C++, the types have to match exactly.
8824   if (S.getLangOpts().CPlusPlus)
8825     return Sema::IncompatibleBlockPointer;
8826 
8827   Sema::AssignConvertType ConvTy = Sema::Compatible;
8828 
8829   // For blocks we enforce that qualifiers are identical.
8830   Qualifiers LQuals = lhptee.getLocalQualifiers();
8831   Qualifiers RQuals = rhptee.getLocalQualifiers();
8832   if (S.getLangOpts().OpenCL) {
8833     LQuals.removeAddressSpace();
8834     RQuals.removeAddressSpace();
8835   }
8836   if (LQuals != RQuals)
8837     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
8838 
8839   // FIXME: OpenCL doesn't define the exact compile time semantics for a block
8840   // assignment.
8841   // The current behavior is similar to C++ lambdas. A block might be
8842   // assigned to a variable iff its return type and parameters are compatible
8843   // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
8844   // an assignment. Presumably it should behave in way that a function pointer
8845   // assignment does in C, so for each parameter and return type:
8846   //  * CVR and address space of LHS should be a superset of CVR and address
8847   //  space of RHS.
8848   //  * unqualified types should be compatible.
8849   if (S.getLangOpts().OpenCL) {
8850     if (!S.Context.typesAreBlockPointerCompatible(
8851             S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
8852             S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
8853       return Sema::IncompatibleBlockPointer;
8854   } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
8855     return Sema::IncompatibleBlockPointer;
8856 
8857   return ConvTy;
8858 }
8859 
8860 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
8861 /// for assignment compatibility.
8862 static Sema::AssignConvertType
8863 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
8864                                    QualType RHSType) {
8865   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
8866   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
8867 
8868   if (LHSType->isObjCBuiltinType()) {
8869     // Class is not compatible with ObjC object pointers.
8870     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
8871         !RHSType->isObjCQualifiedClassType())
8872       return Sema::IncompatiblePointer;
8873     return Sema::Compatible;
8874   }
8875   if (RHSType->isObjCBuiltinType()) {
8876     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
8877         !LHSType->isObjCQualifiedClassType())
8878       return Sema::IncompatiblePointer;
8879     return Sema::Compatible;
8880   }
8881   QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
8882   QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
8883 
8884   if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
8885       // make an exception for id<P>
8886       !LHSType->isObjCQualifiedIdType())
8887     return Sema::CompatiblePointerDiscardsQualifiers;
8888 
8889   if (S.Context.typesAreCompatible(LHSType, RHSType))
8890     return Sema::Compatible;
8891   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
8892     return Sema::IncompatibleObjCQualifiedId;
8893   return Sema::IncompatiblePointer;
8894 }
8895 
8896 Sema::AssignConvertType
8897 Sema::CheckAssignmentConstraints(SourceLocation Loc,
8898                                  QualType LHSType, QualType RHSType) {
8899   // Fake up an opaque expression.  We don't actually care about what
8900   // cast operations are required, so if CheckAssignmentConstraints
8901   // adds casts to this they'll be wasted, but fortunately that doesn't
8902   // usually happen on valid code.
8903   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
8904   ExprResult RHSPtr = &RHSExpr;
8905   CastKind K;
8906 
8907   return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
8908 }
8909 
8910 /// This helper function returns true if QT is a vector type that has element
8911 /// type ElementType.
8912 static bool isVector(QualType QT, QualType ElementType) {
8913   if (const VectorType *VT = QT->getAs<VectorType>())
8914     return VT->getElementType().getCanonicalType() == ElementType;
8915   return false;
8916 }
8917 
8918 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
8919 /// has code to accommodate several GCC extensions when type checking
8920 /// pointers. Here are some objectionable examples that GCC considers warnings:
8921 ///
8922 ///  int a, *pint;
8923 ///  short *pshort;
8924 ///  struct foo *pfoo;
8925 ///
8926 ///  pint = pshort; // warning: assignment from incompatible pointer type
8927 ///  a = pint; // warning: assignment makes integer from pointer without a cast
8928 ///  pint = a; // warning: assignment makes pointer from integer without a cast
8929 ///  pint = pfoo; // warning: assignment from incompatible pointer type
8930 ///
8931 /// As a result, the code for dealing with pointers is more complex than the
8932 /// C99 spec dictates.
8933 ///
8934 /// Sets 'Kind' for any result kind except Incompatible.
8935 Sema::AssignConvertType
8936 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
8937                                  CastKind &Kind, bool ConvertRHS) {
8938   QualType RHSType = RHS.get()->getType();
8939   QualType OrigLHSType = LHSType;
8940 
8941   // Get canonical types.  We're not formatting these types, just comparing
8942   // them.
8943   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
8944   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
8945 
8946   // Common case: no conversion required.
8947   if (LHSType == RHSType) {
8948     Kind = CK_NoOp;
8949     return Compatible;
8950   }
8951 
8952   // If we have an atomic type, try a non-atomic assignment, then just add an
8953   // atomic qualification step.
8954   if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
8955     Sema::AssignConvertType result =
8956       CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
8957     if (result != Compatible)
8958       return result;
8959     if (Kind != CK_NoOp && ConvertRHS)
8960       RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
8961     Kind = CK_NonAtomicToAtomic;
8962     return Compatible;
8963   }
8964 
8965   // If the left-hand side is a reference type, then we are in a
8966   // (rare!) case where we've allowed the use of references in C,
8967   // e.g., as a parameter type in a built-in function. In this case,
8968   // just make sure that the type referenced is compatible with the
8969   // right-hand side type. The caller is responsible for adjusting
8970   // LHSType so that the resulting expression does not have reference
8971   // type.
8972   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
8973     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
8974       Kind = CK_LValueBitCast;
8975       return Compatible;
8976     }
8977     return Incompatible;
8978   }
8979 
8980   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
8981   // to the same ExtVector type.
8982   if (LHSType->isExtVectorType()) {
8983     if (RHSType->isExtVectorType())
8984       return Incompatible;
8985     if (RHSType->isArithmeticType()) {
8986       // CK_VectorSplat does T -> vector T, so first cast to the element type.
8987       if (ConvertRHS)
8988         RHS = prepareVectorSplat(LHSType, RHS.get());
8989       Kind = CK_VectorSplat;
8990       return Compatible;
8991     }
8992   }
8993 
8994   // Conversions to or from vector type.
8995   if (LHSType->isVectorType() || RHSType->isVectorType()) {
8996     if (LHSType->isVectorType() && RHSType->isVectorType()) {
8997       // Allow assignments of an AltiVec vector type to an equivalent GCC
8998       // vector type and vice versa
8999       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
9000         Kind = CK_BitCast;
9001         return Compatible;
9002       }
9003 
9004       // If we are allowing lax vector conversions, and LHS and RHS are both
9005       // vectors, the total size only needs to be the same. This is a bitcast;
9006       // no bits are changed but the result type is different.
9007       if (isLaxVectorConversion(RHSType, LHSType)) {
9008         Kind = CK_BitCast;
9009         return IncompatibleVectors;
9010       }
9011     }
9012 
9013     // When the RHS comes from another lax conversion (e.g. binops between
9014     // scalars and vectors) the result is canonicalized as a vector. When the
9015     // LHS is also a vector, the lax is allowed by the condition above. Handle
9016     // the case where LHS is a scalar.
9017     if (LHSType->isScalarType()) {
9018       const VectorType *VecType = RHSType->getAs<VectorType>();
9019       if (VecType && VecType->getNumElements() == 1 &&
9020           isLaxVectorConversion(RHSType, LHSType)) {
9021         ExprResult *VecExpr = &RHS;
9022         *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
9023         Kind = CK_BitCast;
9024         return Compatible;
9025       }
9026     }
9027 
9028     return Incompatible;
9029   }
9030 
9031   // Diagnose attempts to convert between __float128 and long double where
9032   // such conversions currently can't be handled.
9033   if (unsupportedTypeConversion(*this, LHSType, RHSType))
9034     return Incompatible;
9035 
9036   // Disallow assigning a _Complex to a real type in C++ mode since it simply
9037   // discards the imaginary part.
9038   if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
9039       !LHSType->getAs<ComplexType>())
9040     return Incompatible;
9041 
9042   // Arithmetic conversions.
9043   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
9044       !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
9045     if (ConvertRHS)
9046       Kind = PrepareScalarCast(RHS, LHSType);
9047     return Compatible;
9048   }
9049 
9050   // Conversions to normal pointers.
9051   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
9052     // U* -> T*
9053     if (isa<PointerType>(RHSType)) {
9054       LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9055       LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
9056       if (AddrSpaceL != AddrSpaceR)
9057         Kind = CK_AddressSpaceConversion;
9058       else if (Context.hasCvrSimilarType(RHSType, LHSType))
9059         Kind = CK_NoOp;
9060       else
9061         Kind = CK_BitCast;
9062       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
9063     }
9064 
9065     // int -> T*
9066     if (RHSType->isIntegerType()) {
9067       Kind = CK_IntegralToPointer; // FIXME: null?
9068       return IntToPointer;
9069     }
9070 
9071     // C pointers are not compatible with ObjC object pointers,
9072     // with two exceptions:
9073     if (isa<ObjCObjectPointerType>(RHSType)) {
9074       //  - conversions to void*
9075       if (LHSPointer->getPointeeType()->isVoidType()) {
9076         Kind = CK_BitCast;
9077         return Compatible;
9078       }
9079 
9080       //  - conversions from 'Class' to the redefinition type
9081       if (RHSType->isObjCClassType() &&
9082           Context.hasSameType(LHSType,
9083                               Context.getObjCClassRedefinitionType())) {
9084         Kind = CK_BitCast;
9085         return Compatible;
9086       }
9087 
9088       Kind = CK_BitCast;
9089       return IncompatiblePointer;
9090     }
9091 
9092     // U^ -> void*
9093     if (RHSType->getAs<BlockPointerType>()) {
9094       if (LHSPointer->getPointeeType()->isVoidType()) {
9095         LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9096         LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9097                                 ->getPointeeType()
9098                                 .getAddressSpace();
9099         Kind =
9100             AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9101         return Compatible;
9102       }
9103     }
9104 
9105     return Incompatible;
9106   }
9107 
9108   // Conversions to block pointers.
9109   if (isa<BlockPointerType>(LHSType)) {
9110     // U^ -> T^
9111     if (RHSType->isBlockPointerType()) {
9112       LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
9113                               ->getPointeeType()
9114                               .getAddressSpace();
9115       LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9116                               ->getPointeeType()
9117                               .getAddressSpace();
9118       Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9119       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
9120     }
9121 
9122     // int or null -> T^
9123     if (RHSType->isIntegerType()) {
9124       Kind = CK_IntegralToPointer; // FIXME: null
9125       return IntToBlockPointer;
9126     }
9127 
9128     // id -> T^
9129     if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
9130       Kind = CK_AnyPointerToBlockPointerCast;
9131       return Compatible;
9132     }
9133 
9134     // void* -> T^
9135     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
9136       if (RHSPT->getPointeeType()->isVoidType()) {
9137         Kind = CK_AnyPointerToBlockPointerCast;
9138         return Compatible;
9139       }
9140 
9141     return Incompatible;
9142   }
9143 
9144   // Conversions to Objective-C pointers.
9145   if (isa<ObjCObjectPointerType>(LHSType)) {
9146     // A* -> B*
9147     if (RHSType->isObjCObjectPointerType()) {
9148       Kind = CK_BitCast;
9149       Sema::AssignConvertType result =
9150         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
9151       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9152           result == Compatible &&
9153           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
9154         result = IncompatibleObjCWeakRef;
9155       return result;
9156     }
9157 
9158     // int or null -> A*
9159     if (RHSType->isIntegerType()) {
9160       Kind = CK_IntegralToPointer; // FIXME: null
9161       return IntToPointer;
9162     }
9163 
9164     // In general, C pointers are not compatible with ObjC object pointers,
9165     // with two exceptions:
9166     if (isa<PointerType>(RHSType)) {
9167       Kind = CK_CPointerToObjCPointerCast;
9168 
9169       //  - conversions from 'void*'
9170       if (RHSType->isVoidPointerType()) {
9171         return Compatible;
9172       }
9173 
9174       //  - conversions to 'Class' from its redefinition type
9175       if (LHSType->isObjCClassType() &&
9176           Context.hasSameType(RHSType,
9177                               Context.getObjCClassRedefinitionType())) {
9178         return Compatible;
9179       }
9180 
9181       return IncompatiblePointer;
9182     }
9183 
9184     // Only under strict condition T^ is compatible with an Objective-C pointer.
9185     if (RHSType->isBlockPointerType() &&
9186         LHSType->isBlockCompatibleObjCPointerType(Context)) {
9187       if (ConvertRHS)
9188         maybeExtendBlockObject(RHS);
9189       Kind = CK_BlockPointerToObjCPointerCast;
9190       return Compatible;
9191     }
9192 
9193     return Incompatible;
9194   }
9195 
9196   // Conversions from pointers that are not covered by the above.
9197   if (isa<PointerType>(RHSType)) {
9198     // T* -> _Bool
9199     if (LHSType == Context.BoolTy) {
9200       Kind = CK_PointerToBoolean;
9201       return Compatible;
9202     }
9203 
9204     // T* -> int
9205     if (LHSType->isIntegerType()) {
9206       Kind = CK_PointerToIntegral;
9207       return PointerToInt;
9208     }
9209 
9210     return Incompatible;
9211   }
9212 
9213   // Conversions from Objective-C pointers that are not covered by the above.
9214   if (isa<ObjCObjectPointerType>(RHSType)) {
9215     // T* -> _Bool
9216     if (LHSType == Context.BoolTy) {
9217       Kind = CK_PointerToBoolean;
9218       return Compatible;
9219     }
9220 
9221     // T* -> int
9222     if (LHSType->isIntegerType()) {
9223       Kind = CK_PointerToIntegral;
9224       return PointerToInt;
9225     }
9226 
9227     return Incompatible;
9228   }
9229 
9230   // struct A -> struct B
9231   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
9232     if (Context.typesAreCompatible(LHSType, RHSType)) {
9233       Kind = CK_NoOp;
9234       return Compatible;
9235     }
9236   }
9237 
9238   if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
9239     Kind = CK_IntToOCLSampler;
9240     return Compatible;
9241   }
9242 
9243   return Incompatible;
9244 }
9245 
9246 /// Constructs a transparent union from an expression that is
9247 /// used to initialize the transparent union.
9248 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
9249                                       ExprResult &EResult, QualType UnionType,
9250                                       FieldDecl *Field) {
9251   // Build an initializer list that designates the appropriate member
9252   // of the transparent union.
9253   Expr *E = EResult.get();
9254   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
9255                                                    E, SourceLocation());
9256   Initializer->setType(UnionType);
9257   Initializer->setInitializedFieldInUnion(Field);
9258 
9259   // Build a compound literal constructing a value of the transparent
9260   // union type from this initializer list.
9261   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
9262   EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
9263                                         VK_RValue, Initializer, false);
9264 }
9265 
9266 Sema::AssignConvertType
9267 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
9268                                                ExprResult &RHS) {
9269   QualType RHSType = RHS.get()->getType();
9270 
9271   // If the ArgType is a Union type, we want to handle a potential
9272   // transparent_union GCC extension.
9273   const RecordType *UT = ArgType->getAsUnionType();
9274   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
9275     return Incompatible;
9276 
9277   // The field to initialize within the transparent union.
9278   RecordDecl *UD = UT->getDecl();
9279   FieldDecl *InitField = nullptr;
9280   // It's compatible if the expression matches any of the fields.
9281   for (auto *it : UD->fields()) {
9282     if (it->getType()->isPointerType()) {
9283       // If the transparent union contains a pointer type, we allow:
9284       // 1) void pointer
9285       // 2) null pointer constant
9286       if (RHSType->isPointerType())
9287         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
9288           RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
9289           InitField = it;
9290           break;
9291         }
9292 
9293       if (RHS.get()->isNullPointerConstant(Context,
9294                                            Expr::NPC_ValueDependentIsNull)) {
9295         RHS = ImpCastExprToType(RHS.get(), it->getType(),
9296                                 CK_NullToPointer);
9297         InitField = it;
9298         break;
9299       }
9300     }
9301 
9302     CastKind Kind;
9303     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
9304           == Compatible) {
9305       RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
9306       InitField = it;
9307       break;
9308     }
9309   }
9310 
9311   if (!InitField)
9312     return Incompatible;
9313 
9314   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
9315   return Compatible;
9316 }
9317 
9318 Sema::AssignConvertType
9319 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
9320                                        bool Diagnose,
9321                                        bool DiagnoseCFAudited,
9322                                        bool ConvertRHS) {
9323   // We need to be able to tell the caller whether we diagnosed a problem, if
9324   // they ask us to issue diagnostics.
9325   assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
9326 
9327   // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
9328   // we can't avoid *all* modifications at the moment, so we need some somewhere
9329   // to put the updated value.
9330   ExprResult LocalRHS = CallerRHS;
9331   ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
9332 
9333   if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
9334     if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
9335       if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
9336           !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
9337         Diag(RHS.get()->getExprLoc(),
9338              diag::warn_noderef_to_dereferenceable_pointer)
9339             << RHS.get()->getSourceRange();
9340       }
9341     }
9342   }
9343 
9344   if (getLangOpts().CPlusPlus) {
9345     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
9346       // C++ 5.17p3: If the left operand is not of class type, the
9347       // expression is implicitly converted (C++ 4) to the
9348       // cv-unqualified type of the left operand.
9349       QualType RHSType = RHS.get()->getType();
9350       if (Diagnose) {
9351         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9352                                         AA_Assigning);
9353       } else {
9354         ImplicitConversionSequence ICS =
9355             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9356                                   /*SuppressUserConversions=*/false,
9357                                   AllowedExplicit::None,
9358                                   /*InOverloadResolution=*/false,
9359                                   /*CStyle=*/false,
9360                                   /*AllowObjCWritebackConversion=*/false);
9361         if (ICS.isFailure())
9362           return Incompatible;
9363         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9364                                         ICS, AA_Assigning);
9365       }
9366       if (RHS.isInvalid())
9367         return Incompatible;
9368       Sema::AssignConvertType result = Compatible;
9369       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9370           !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
9371         result = IncompatibleObjCWeakRef;
9372       return result;
9373     }
9374 
9375     // FIXME: Currently, we fall through and treat C++ classes like C
9376     // structures.
9377     // FIXME: We also fall through for atomics; not sure what should
9378     // happen there, though.
9379   } else if (RHS.get()->getType() == Context.OverloadTy) {
9380     // As a set of extensions to C, we support overloading on functions. These
9381     // functions need to be resolved here.
9382     DeclAccessPair DAP;
9383     if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
9384             RHS.get(), LHSType, /*Complain=*/false, DAP))
9385       RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
9386     else
9387       return Incompatible;
9388   }
9389 
9390   // C99 6.5.16.1p1: the left operand is a pointer and the right is
9391   // a null pointer constant.
9392   if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
9393        LHSType->isBlockPointerType()) &&
9394       RHS.get()->isNullPointerConstant(Context,
9395                                        Expr::NPC_ValueDependentIsNull)) {
9396     if (Diagnose || ConvertRHS) {
9397       CastKind Kind;
9398       CXXCastPath Path;
9399       CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
9400                              /*IgnoreBaseAccess=*/false, Diagnose);
9401       if (ConvertRHS)
9402         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
9403     }
9404     return Compatible;
9405   }
9406 
9407   // OpenCL queue_t type assignment.
9408   if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
9409                                  Context, Expr::NPC_ValueDependentIsNull)) {
9410     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9411     return Compatible;
9412   }
9413 
9414   // This check seems unnatural, however it is necessary to ensure the proper
9415   // conversion of functions/arrays. If the conversion were done for all
9416   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
9417   // expressions that suppress this implicit conversion (&, sizeof).
9418   //
9419   // Suppress this for references: C++ 8.5.3p5.
9420   if (!LHSType->isReferenceType()) {
9421     // FIXME: We potentially allocate here even if ConvertRHS is false.
9422     RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
9423     if (RHS.isInvalid())
9424       return Incompatible;
9425   }
9426   CastKind Kind;
9427   Sema::AssignConvertType result =
9428     CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
9429 
9430   // C99 6.5.16.1p2: The value of the right operand is converted to the
9431   // type of the assignment expression.
9432   // CheckAssignmentConstraints allows the left-hand side to be a reference,
9433   // so that we can use references in built-in functions even in C.
9434   // The getNonReferenceType() call makes sure that the resulting expression
9435   // does not have reference type.
9436   if (result != Incompatible && RHS.get()->getType() != LHSType) {
9437     QualType Ty = LHSType.getNonLValueExprType(Context);
9438     Expr *E = RHS.get();
9439 
9440     // Check for various Objective-C errors. If we are not reporting
9441     // diagnostics and just checking for errors, e.g., during overload
9442     // resolution, return Incompatible to indicate the failure.
9443     if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9444         CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
9445                             Diagnose, DiagnoseCFAudited) != ACR_okay) {
9446       if (!Diagnose)
9447         return Incompatible;
9448     }
9449     if (getLangOpts().ObjC &&
9450         (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType,
9451                                            E->getType(), E, Diagnose) ||
9452          CheckConversionToObjCLiteral(LHSType, E, Diagnose))) {
9453       if (!Diagnose)
9454         return Incompatible;
9455       // Replace the expression with a corrected version and continue so we
9456       // can find further errors.
9457       RHS = E;
9458       return Compatible;
9459     }
9460 
9461     if (ConvertRHS)
9462       RHS = ImpCastExprToType(E, Ty, Kind);
9463   }
9464 
9465   return result;
9466 }
9467 
9468 namespace {
9469 /// The original operand to an operator, prior to the application of the usual
9470 /// arithmetic conversions and converting the arguments of a builtin operator
9471 /// candidate.
9472 struct OriginalOperand {
9473   explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
9474     if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op))
9475       Op = MTE->getSubExpr();
9476     if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op))
9477       Op = BTE->getSubExpr();
9478     if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) {
9479       Orig = ICE->getSubExprAsWritten();
9480       Conversion = ICE->getConversionFunction();
9481     }
9482   }
9483 
9484   QualType getType() const { return Orig->getType(); }
9485 
9486   Expr *Orig;
9487   NamedDecl *Conversion;
9488 };
9489 }
9490 
9491 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
9492                                ExprResult &RHS) {
9493   OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
9494 
9495   Diag(Loc, diag::err_typecheck_invalid_operands)
9496     << OrigLHS.getType() << OrigRHS.getType()
9497     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9498 
9499   // If a user-defined conversion was applied to either of the operands prior
9500   // to applying the built-in operator rules, tell the user about it.
9501   if (OrigLHS.Conversion) {
9502     Diag(OrigLHS.Conversion->getLocation(),
9503          diag::note_typecheck_invalid_operands_converted)
9504       << 0 << LHS.get()->getType();
9505   }
9506   if (OrigRHS.Conversion) {
9507     Diag(OrigRHS.Conversion->getLocation(),
9508          diag::note_typecheck_invalid_operands_converted)
9509       << 1 << RHS.get()->getType();
9510   }
9511 
9512   return QualType();
9513 }
9514 
9515 // Diagnose cases where a scalar was implicitly converted to a vector and
9516 // diagnose the underlying types. Otherwise, diagnose the error
9517 // as invalid vector logical operands for non-C++ cases.
9518 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
9519                                             ExprResult &RHS) {
9520   QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
9521   QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
9522 
9523   bool LHSNatVec = LHSType->isVectorType();
9524   bool RHSNatVec = RHSType->isVectorType();
9525 
9526   if (!(LHSNatVec && RHSNatVec)) {
9527     Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
9528     Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
9529     Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
9530         << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
9531         << Vector->getSourceRange();
9532     return QualType();
9533   }
9534 
9535   Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
9536       << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
9537       << RHS.get()->getSourceRange();
9538 
9539   return QualType();
9540 }
9541 
9542 /// Try to convert a value of non-vector type to a vector type by converting
9543 /// the type to the element type of the vector and then performing a splat.
9544 /// If the language is OpenCL, we only use conversions that promote scalar
9545 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
9546 /// for float->int.
9547 ///
9548 /// OpenCL V2.0 6.2.6.p2:
9549 /// An error shall occur if any scalar operand type has greater rank
9550 /// than the type of the vector element.
9551 ///
9552 /// \param scalar - if non-null, actually perform the conversions
9553 /// \return true if the operation fails (but without diagnosing the failure)
9554 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
9555                                      QualType scalarTy,
9556                                      QualType vectorEltTy,
9557                                      QualType vectorTy,
9558                                      unsigned &DiagID) {
9559   // The conversion to apply to the scalar before splatting it,
9560   // if necessary.
9561   CastKind scalarCast = CK_NoOp;
9562 
9563   if (vectorEltTy->isIntegralType(S.Context)) {
9564     if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
9565         (scalarTy->isIntegerType() &&
9566          S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
9567       DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
9568       return true;
9569     }
9570     if (!scalarTy->isIntegralType(S.Context))
9571       return true;
9572     scalarCast = CK_IntegralCast;
9573   } else if (vectorEltTy->isRealFloatingType()) {
9574     if (scalarTy->isRealFloatingType()) {
9575       if (S.getLangOpts().OpenCL &&
9576           S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
9577         DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
9578         return true;
9579       }
9580       scalarCast = CK_FloatingCast;
9581     }
9582     else if (scalarTy->isIntegralType(S.Context))
9583       scalarCast = CK_IntegralToFloating;
9584     else
9585       return true;
9586   } else {
9587     return true;
9588   }
9589 
9590   // Adjust scalar if desired.
9591   if (scalar) {
9592     if (scalarCast != CK_NoOp)
9593       *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
9594     *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
9595   }
9596   return false;
9597 }
9598 
9599 /// Convert vector E to a vector with the same number of elements but different
9600 /// element type.
9601 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
9602   const auto *VecTy = E->getType()->getAs<VectorType>();
9603   assert(VecTy && "Expression E must be a vector");
9604   QualType NewVecTy = S.Context.getVectorType(ElementType,
9605                                               VecTy->getNumElements(),
9606                                               VecTy->getVectorKind());
9607 
9608   // Look through the implicit cast. Return the subexpression if its type is
9609   // NewVecTy.
9610   if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
9611     if (ICE->getSubExpr()->getType() == NewVecTy)
9612       return ICE->getSubExpr();
9613 
9614   auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
9615   return S.ImpCastExprToType(E, NewVecTy, Cast);
9616 }
9617 
9618 /// Test if a (constant) integer Int can be casted to another integer type
9619 /// IntTy without losing precision.
9620 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int,
9621                                       QualType OtherIntTy) {
9622   QualType IntTy = Int->get()->getType().getUnqualifiedType();
9623 
9624   // Reject cases where the value of the Int is unknown as that would
9625   // possibly cause truncation, but accept cases where the scalar can be
9626   // demoted without loss of precision.
9627   Expr::EvalResult EVResult;
9628   bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
9629   int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
9630   bool IntSigned = IntTy->hasSignedIntegerRepresentation();
9631   bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
9632 
9633   if (CstInt) {
9634     // If the scalar is constant and is of a higher order and has more active
9635     // bits that the vector element type, reject it.
9636     llvm::APSInt Result = EVResult.Val.getInt();
9637     unsigned NumBits = IntSigned
9638                            ? (Result.isNegative() ? Result.getMinSignedBits()
9639                                                   : Result.getActiveBits())
9640                            : Result.getActiveBits();
9641     if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
9642       return true;
9643 
9644     // If the signedness of the scalar type and the vector element type
9645     // differs and the number of bits is greater than that of the vector
9646     // element reject it.
9647     return (IntSigned != OtherIntSigned &&
9648             NumBits > S.Context.getIntWidth(OtherIntTy));
9649   }
9650 
9651   // Reject cases where the value of the scalar is not constant and it's
9652   // order is greater than that of the vector element type.
9653   return (Order < 0);
9654 }
9655 
9656 /// Test if a (constant) integer Int can be casted to floating point type
9657 /// FloatTy without losing precision.
9658 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int,
9659                                      QualType FloatTy) {
9660   QualType IntTy = Int->get()->getType().getUnqualifiedType();
9661 
9662   // Determine if the integer constant can be expressed as a floating point
9663   // number of the appropriate type.
9664   Expr::EvalResult EVResult;
9665   bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
9666 
9667   uint64_t Bits = 0;
9668   if (CstInt) {
9669     // Reject constants that would be truncated if they were converted to
9670     // the floating point type. Test by simple to/from conversion.
9671     // FIXME: Ideally the conversion to an APFloat and from an APFloat
9672     //        could be avoided if there was a convertFromAPInt method
9673     //        which could signal back if implicit truncation occurred.
9674     llvm::APSInt Result = EVResult.Val.getInt();
9675     llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
9676     Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
9677                            llvm::APFloat::rmTowardZero);
9678     llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
9679                              !IntTy->hasSignedIntegerRepresentation());
9680     bool Ignored = false;
9681     Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
9682                            &Ignored);
9683     if (Result != ConvertBack)
9684       return true;
9685   } else {
9686     // Reject types that cannot be fully encoded into the mantissa of
9687     // the float.
9688     Bits = S.Context.getTypeSize(IntTy);
9689     unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
9690         S.Context.getFloatTypeSemantics(FloatTy));
9691     if (Bits > FloatPrec)
9692       return true;
9693   }
9694 
9695   return false;
9696 }
9697 
9698 /// Attempt to convert and splat Scalar into a vector whose types matches
9699 /// Vector following GCC conversion rules. The rule is that implicit
9700 /// conversion can occur when Scalar can be casted to match Vector's element
9701 /// type without causing truncation of Scalar.
9702 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar,
9703                                         ExprResult *Vector) {
9704   QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
9705   QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
9706   const VectorType *VT = VectorTy->getAs<VectorType>();
9707 
9708   assert(!isa<ExtVectorType>(VT) &&
9709          "ExtVectorTypes should not be handled here!");
9710 
9711   QualType VectorEltTy = VT->getElementType();
9712 
9713   // Reject cases where the vector element type or the scalar element type are
9714   // not integral or floating point types.
9715   if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
9716     return true;
9717 
9718   // The conversion to apply to the scalar before splatting it,
9719   // if necessary.
9720   CastKind ScalarCast = CK_NoOp;
9721 
9722   // Accept cases where the vector elements are integers and the scalar is
9723   // an integer.
9724   // FIXME: Notionally if the scalar was a floating point value with a precise
9725   //        integral representation, we could cast it to an appropriate integer
9726   //        type and then perform the rest of the checks here. GCC will perform
9727   //        this conversion in some cases as determined by the input language.
9728   //        We should accept it on a language independent basis.
9729   if (VectorEltTy->isIntegralType(S.Context) &&
9730       ScalarTy->isIntegralType(S.Context) &&
9731       S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
9732 
9733     if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
9734       return true;
9735 
9736     ScalarCast = CK_IntegralCast;
9737   } else if (VectorEltTy->isIntegralType(S.Context) &&
9738              ScalarTy->isRealFloatingType()) {
9739     if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy))
9740       ScalarCast = CK_FloatingToIntegral;
9741     else
9742       return true;
9743   } else if (VectorEltTy->isRealFloatingType()) {
9744     if (ScalarTy->isRealFloatingType()) {
9745 
9746       // Reject cases where the scalar type is not a constant and has a higher
9747       // Order than the vector element type.
9748       llvm::APFloat Result(0.0);
9749 
9750       // Determine whether this is a constant scalar. In the event that the
9751       // value is dependent (and thus cannot be evaluated by the constant
9752       // evaluator), skip the evaluation. This will then diagnose once the
9753       // expression is instantiated.
9754       bool CstScalar = Scalar->get()->isValueDependent() ||
9755                        Scalar->get()->EvaluateAsFloat(Result, S.Context);
9756       int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
9757       if (!CstScalar && Order < 0)
9758         return true;
9759 
9760       // If the scalar cannot be safely casted to the vector element type,
9761       // reject it.
9762       if (CstScalar) {
9763         bool Truncated = false;
9764         Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
9765                        llvm::APFloat::rmNearestTiesToEven, &Truncated);
9766         if (Truncated)
9767           return true;
9768       }
9769 
9770       ScalarCast = CK_FloatingCast;
9771     } else if (ScalarTy->isIntegralType(S.Context)) {
9772       if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
9773         return true;
9774 
9775       ScalarCast = CK_IntegralToFloating;
9776     } else
9777       return true;
9778   } else if (ScalarTy->isEnumeralType())
9779     return true;
9780 
9781   // Adjust scalar if desired.
9782   if (Scalar) {
9783     if (ScalarCast != CK_NoOp)
9784       *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
9785     *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
9786   }
9787   return false;
9788 }
9789 
9790 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
9791                                    SourceLocation Loc, bool IsCompAssign,
9792                                    bool AllowBothBool,
9793                                    bool AllowBoolConversions) {
9794   if (!IsCompAssign) {
9795     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
9796     if (LHS.isInvalid())
9797       return QualType();
9798   }
9799   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
9800   if (RHS.isInvalid())
9801     return QualType();
9802 
9803   // For conversion purposes, we ignore any qualifiers.
9804   // For example, "const float" and "float" are equivalent.
9805   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
9806   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
9807 
9808   const VectorType *LHSVecType = LHSType->getAs<VectorType>();
9809   const VectorType *RHSVecType = RHSType->getAs<VectorType>();
9810   assert(LHSVecType || RHSVecType);
9811 
9812   // AltiVec-style "vector bool op vector bool" combinations are allowed
9813   // for some operators but not others.
9814   if (!AllowBothBool &&
9815       LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
9816       RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
9817     return InvalidOperands(Loc, LHS, RHS);
9818 
9819   // If the vector types are identical, return.
9820   if (Context.hasSameType(LHSType, RHSType))
9821     return LHSType;
9822 
9823   // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
9824   if (LHSVecType && RHSVecType &&
9825       Context.areCompatibleVectorTypes(LHSType, RHSType)) {
9826     if (isa<ExtVectorType>(LHSVecType)) {
9827       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9828       return LHSType;
9829     }
9830 
9831     if (!IsCompAssign)
9832       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
9833     return RHSType;
9834   }
9835 
9836   // AllowBoolConversions says that bool and non-bool AltiVec vectors
9837   // can be mixed, with the result being the non-bool type.  The non-bool
9838   // operand must have integer element type.
9839   if (AllowBoolConversions && LHSVecType && RHSVecType &&
9840       LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
9841       (Context.getTypeSize(LHSVecType->getElementType()) ==
9842        Context.getTypeSize(RHSVecType->getElementType()))) {
9843     if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
9844         LHSVecType->getElementType()->isIntegerType() &&
9845         RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
9846       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9847       return LHSType;
9848     }
9849     if (!IsCompAssign &&
9850         LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
9851         RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
9852         RHSVecType->getElementType()->isIntegerType()) {
9853       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
9854       return RHSType;
9855     }
9856   }
9857 
9858   // If there's a vector type and a scalar, try to convert the scalar to
9859   // the vector element type and splat.
9860   unsigned DiagID = diag::err_typecheck_vector_not_convertable;
9861   if (!RHSVecType) {
9862     if (isa<ExtVectorType>(LHSVecType)) {
9863       if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
9864                                     LHSVecType->getElementType(), LHSType,
9865                                     DiagID))
9866         return LHSType;
9867     } else {
9868       if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
9869         return LHSType;
9870     }
9871   }
9872   if (!LHSVecType) {
9873     if (isa<ExtVectorType>(RHSVecType)) {
9874       if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
9875                                     LHSType, RHSVecType->getElementType(),
9876                                     RHSType, DiagID))
9877         return RHSType;
9878     } else {
9879       if (LHS.get()->getValueKind() == VK_LValue ||
9880           !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
9881         return RHSType;
9882     }
9883   }
9884 
9885   // FIXME: The code below also handles conversion between vectors and
9886   // non-scalars, we should break this down into fine grained specific checks
9887   // and emit proper diagnostics.
9888   QualType VecType = LHSVecType ? LHSType : RHSType;
9889   const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
9890   QualType OtherType = LHSVecType ? RHSType : LHSType;
9891   ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
9892   if (isLaxVectorConversion(OtherType, VecType)) {
9893     // If we're allowing lax vector conversions, only the total (data) size
9894     // needs to be the same. For non compound assignment, if one of the types is
9895     // scalar, the result is always the vector type.
9896     if (!IsCompAssign) {
9897       *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
9898       return VecType;
9899     // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
9900     // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
9901     // type. Note that this is already done by non-compound assignments in
9902     // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
9903     // <1 x T> -> T. The result is also a vector type.
9904     } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
9905                (OtherType->isScalarType() && VT->getNumElements() == 1)) {
9906       ExprResult *RHSExpr = &RHS;
9907       *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
9908       return VecType;
9909     }
9910   }
9911 
9912   // Okay, the expression is invalid.
9913 
9914   // If there's a non-vector, non-real operand, diagnose that.
9915   if ((!RHSVecType && !RHSType->isRealType()) ||
9916       (!LHSVecType && !LHSType->isRealType())) {
9917     Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
9918       << LHSType << RHSType
9919       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9920     return QualType();
9921   }
9922 
9923   // OpenCL V1.1 6.2.6.p1:
9924   // If the operands are of more than one vector type, then an error shall
9925   // occur. Implicit conversions between vector types are not permitted, per
9926   // section 6.2.1.
9927   if (getLangOpts().OpenCL &&
9928       RHSVecType && isa<ExtVectorType>(RHSVecType) &&
9929       LHSVecType && isa<ExtVectorType>(LHSVecType)) {
9930     Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
9931                                                            << RHSType;
9932     return QualType();
9933   }
9934 
9935 
9936   // If there is a vector type that is not a ExtVector and a scalar, we reach
9937   // this point if scalar could not be converted to the vector's element type
9938   // without truncation.
9939   if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
9940       (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
9941     QualType Scalar = LHSVecType ? RHSType : LHSType;
9942     QualType Vector = LHSVecType ? LHSType : RHSType;
9943     unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
9944     Diag(Loc,
9945          diag::err_typecheck_vector_not_convertable_implict_truncation)
9946         << ScalarOrVector << Scalar << Vector;
9947 
9948     return QualType();
9949   }
9950 
9951   // Otherwise, use the generic diagnostic.
9952   Diag(Loc, DiagID)
9953     << LHSType << RHSType
9954     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9955   return QualType();
9956 }
9957 
9958 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
9959 // expression.  These are mainly cases where the null pointer is used as an
9960 // integer instead of a pointer.
9961 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
9962                                 SourceLocation Loc, bool IsCompare) {
9963   // The canonical way to check for a GNU null is with isNullPointerConstant,
9964   // but we use a bit of a hack here for speed; this is a relatively
9965   // hot path, and isNullPointerConstant is slow.
9966   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
9967   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
9968 
9969   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
9970 
9971   // Avoid analyzing cases where the result will either be invalid (and
9972   // diagnosed as such) or entirely valid and not something to warn about.
9973   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
9974       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
9975     return;
9976 
9977   // Comparison operations would not make sense with a null pointer no matter
9978   // what the other expression is.
9979   if (!IsCompare) {
9980     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
9981         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
9982         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
9983     return;
9984   }
9985 
9986   // The rest of the operations only make sense with a null pointer
9987   // if the other expression is a pointer.
9988   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
9989       NonNullType->canDecayToPointerType())
9990     return;
9991 
9992   S.Diag(Loc, diag::warn_null_in_comparison_operation)
9993       << LHSNull /* LHS is NULL */ << NonNullType
9994       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9995 }
9996 
9997 static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS,
9998                                           SourceLocation Loc) {
9999   const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS);
10000   const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS);
10001   if (!LUE || !RUE)
10002     return;
10003   if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
10004       RUE->getKind() != UETT_SizeOf)
10005     return;
10006 
10007   const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens();
10008   QualType LHSTy = LHSArg->getType();
10009   QualType RHSTy;
10010 
10011   if (RUE->isArgumentType())
10012     RHSTy = RUE->getArgumentType();
10013   else
10014     RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
10015 
10016   if (LHSTy->isPointerType() && !RHSTy->isPointerType()) {
10017     if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy))
10018       return;
10019 
10020     S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
10021     if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
10022       if (const ValueDecl *LHSArgDecl = DRE->getDecl())
10023         S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here)
10024             << LHSArgDecl;
10025     }
10026   } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) {
10027     QualType ArrayElemTy = ArrayTy->getElementType();
10028     if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) ||
10029         ArrayElemTy->isDependentType() || RHSTy->isDependentType() ||
10030         ArrayElemTy->isCharType() ||
10031         S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy))
10032       return;
10033     S.Diag(Loc, diag::warn_division_sizeof_array)
10034         << LHSArg->getSourceRange() << ArrayElemTy << RHSTy;
10035     if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
10036       if (const ValueDecl *LHSArgDecl = DRE->getDecl())
10037         S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here)
10038             << LHSArgDecl;
10039     }
10040 
10041     S.Diag(Loc, diag::note_precedence_silence) << RHS;
10042   }
10043 }
10044 
10045 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
10046                                                ExprResult &RHS,
10047                                                SourceLocation Loc, bool IsDiv) {
10048   // Check for division/remainder by zero.
10049   Expr::EvalResult RHSValue;
10050   if (!RHS.get()->isValueDependent() &&
10051       RHS.get()->EvaluateAsInt(RHSValue, S.Context) &&
10052       RHSValue.Val.getInt() == 0)
10053     S.DiagRuntimeBehavior(Loc, RHS.get(),
10054                           S.PDiag(diag::warn_remainder_division_by_zero)
10055                             << IsDiv << RHS.get()->getSourceRange());
10056 }
10057 
10058 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
10059                                            SourceLocation Loc,
10060                                            bool IsCompAssign, bool IsDiv) {
10061   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10062 
10063   if (LHS.get()->getType()->isVectorType() ||
10064       RHS.get()->getType()->isVectorType())
10065     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10066                                /*AllowBothBool*/getLangOpts().AltiVec,
10067                                /*AllowBoolConversions*/false);
10068   if (!IsDiv && (LHS.get()->getType()->isConstantMatrixType() ||
10069                  RHS.get()->getType()->isConstantMatrixType()))
10070     return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign);
10071 
10072   QualType compType = UsualArithmeticConversions(
10073       LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
10074   if (LHS.isInvalid() || RHS.isInvalid())
10075     return QualType();
10076 
10077 
10078   if (compType.isNull() || !compType->isArithmeticType())
10079     return InvalidOperands(Loc, LHS, RHS);
10080   if (IsDiv) {
10081     DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
10082     DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc);
10083   }
10084   return compType;
10085 }
10086 
10087 QualType Sema::CheckRemainderOperands(
10088   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
10089   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10090 
10091   if (LHS.get()->getType()->isVectorType() ||
10092       RHS.get()->getType()->isVectorType()) {
10093     if (LHS.get()->getType()->hasIntegerRepresentation() &&
10094         RHS.get()->getType()->hasIntegerRepresentation())
10095       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10096                                  /*AllowBothBool*/getLangOpts().AltiVec,
10097                                  /*AllowBoolConversions*/false);
10098     return InvalidOperands(Loc, LHS, RHS);
10099   }
10100 
10101   QualType compType = UsualArithmeticConversions(
10102       LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
10103   if (LHS.isInvalid() || RHS.isInvalid())
10104     return QualType();
10105 
10106   if (compType.isNull() || !compType->isIntegerType())
10107     return InvalidOperands(Loc, LHS, RHS);
10108   DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
10109   return compType;
10110 }
10111 
10112 /// Diagnose invalid arithmetic on two void pointers.
10113 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
10114                                                 Expr *LHSExpr, Expr *RHSExpr) {
10115   S.Diag(Loc, S.getLangOpts().CPlusPlus
10116                 ? diag::err_typecheck_pointer_arith_void_type
10117                 : diag::ext_gnu_void_ptr)
10118     << 1 /* two pointers */ << LHSExpr->getSourceRange()
10119                             << RHSExpr->getSourceRange();
10120 }
10121 
10122 /// Diagnose invalid arithmetic on a void pointer.
10123 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
10124                                             Expr *Pointer) {
10125   S.Diag(Loc, S.getLangOpts().CPlusPlus
10126                 ? diag::err_typecheck_pointer_arith_void_type
10127                 : diag::ext_gnu_void_ptr)
10128     << 0 /* one pointer */ << Pointer->getSourceRange();
10129 }
10130 
10131 /// Diagnose invalid arithmetic on a null pointer.
10132 ///
10133 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
10134 /// idiom, which we recognize as a GNU extension.
10135 ///
10136 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc,
10137                                             Expr *Pointer, bool IsGNUIdiom) {
10138   if (IsGNUIdiom)
10139     S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
10140       << Pointer->getSourceRange();
10141   else
10142     S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
10143       << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
10144 }
10145 
10146 /// Diagnose invalid arithmetic on two function pointers.
10147 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
10148                                                     Expr *LHS, Expr *RHS) {
10149   assert(LHS->getType()->isAnyPointerType());
10150   assert(RHS->getType()->isAnyPointerType());
10151   S.Diag(Loc, S.getLangOpts().CPlusPlus
10152                 ? diag::err_typecheck_pointer_arith_function_type
10153                 : diag::ext_gnu_ptr_func_arith)
10154     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
10155     // We only show the second type if it differs from the first.
10156     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
10157                                                    RHS->getType())
10158     << RHS->getType()->getPointeeType()
10159     << LHS->getSourceRange() << RHS->getSourceRange();
10160 }
10161 
10162 /// Diagnose invalid arithmetic on a function pointer.
10163 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
10164                                                 Expr *Pointer) {
10165   assert(Pointer->getType()->isAnyPointerType());
10166   S.Diag(Loc, S.getLangOpts().CPlusPlus
10167                 ? diag::err_typecheck_pointer_arith_function_type
10168                 : diag::ext_gnu_ptr_func_arith)
10169     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
10170     << 0 /* one pointer, so only one type */
10171     << Pointer->getSourceRange();
10172 }
10173 
10174 /// Emit error if Operand is incomplete pointer type
10175 ///
10176 /// \returns True if pointer has incomplete type
10177 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
10178                                                  Expr *Operand) {
10179   QualType ResType = Operand->getType();
10180   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10181     ResType = ResAtomicType->getValueType();
10182 
10183   assert(ResType->isAnyPointerType() && !ResType->isDependentType());
10184   QualType PointeeTy = ResType->getPointeeType();
10185   return S.RequireCompleteSizedType(
10186       Loc, PointeeTy,
10187       diag::err_typecheck_arithmetic_incomplete_or_sizeless_type,
10188       Operand->getSourceRange());
10189 }
10190 
10191 /// Check the validity of an arithmetic pointer operand.
10192 ///
10193 /// If the operand has pointer type, this code will check for pointer types
10194 /// which are invalid in arithmetic operations. These will be diagnosed
10195 /// appropriately, including whether or not the use is supported as an
10196 /// extension.
10197 ///
10198 /// \returns True when the operand is valid to use (even if as an extension).
10199 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
10200                                             Expr *Operand) {
10201   QualType ResType = Operand->getType();
10202   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10203     ResType = ResAtomicType->getValueType();
10204 
10205   if (!ResType->isAnyPointerType()) return true;
10206 
10207   QualType PointeeTy = ResType->getPointeeType();
10208   if (PointeeTy->isVoidType()) {
10209     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
10210     return !S.getLangOpts().CPlusPlus;
10211   }
10212   if (PointeeTy->isFunctionType()) {
10213     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
10214     return !S.getLangOpts().CPlusPlus;
10215   }
10216 
10217   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
10218 
10219   return true;
10220 }
10221 
10222 /// Check the validity of a binary arithmetic operation w.r.t. pointer
10223 /// operands.
10224 ///
10225 /// This routine will diagnose any invalid arithmetic on pointer operands much
10226 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
10227 /// for emitting a single diagnostic even for operations where both LHS and RHS
10228 /// are (potentially problematic) pointers.
10229 ///
10230 /// \returns True when the operand is valid to use (even if as an extension).
10231 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
10232                                                 Expr *LHSExpr, Expr *RHSExpr) {
10233   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
10234   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
10235   if (!isLHSPointer && !isRHSPointer) return true;
10236 
10237   QualType LHSPointeeTy, RHSPointeeTy;
10238   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
10239   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
10240 
10241   // if both are pointers check if operation is valid wrt address spaces
10242   if (isLHSPointer && isRHSPointer) {
10243     if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy)) {
10244       S.Diag(Loc,
10245              diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
10246           << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
10247           << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
10248       return false;
10249     }
10250   }
10251 
10252   // Check for arithmetic on pointers to incomplete types.
10253   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
10254   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
10255   if (isLHSVoidPtr || isRHSVoidPtr) {
10256     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
10257     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
10258     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
10259 
10260     return !S.getLangOpts().CPlusPlus;
10261   }
10262 
10263   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
10264   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
10265   if (isLHSFuncPtr || isRHSFuncPtr) {
10266     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
10267     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
10268                                                                 RHSExpr);
10269     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
10270 
10271     return !S.getLangOpts().CPlusPlus;
10272   }
10273 
10274   if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
10275     return false;
10276   if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
10277     return false;
10278 
10279   return true;
10280 }
10281 
10282 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
10283 /// literal.
10284 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
10285                                   Expr *LHSExpr, Expr *RHSExpr) {
10286   StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
10287   Expr* IndexExpr = RHSExpr;
10288   if (!StrExpr) {
10289     StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
10290     IndexExpr = LHSExpr;
10291   }
10292 
10293   bool IsStringPlusInt = StrExpr &&
10294       IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
10295   if (!IsStringPlusInt || IndexExpr->isValueDependent())
10296     return;
10297 
10298   SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
10299   Self.Diag(OpLoc, diag::warn_string_plus_int)
10300       << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
10301 
10302   // Only print a fixit for "str" + int, not for int + "str".
10303   if (IndexExpr == RHSExpr) {
10304     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
10305     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
10306         << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
10307         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
10308         << FixItHint::CreateInsertion(EndLoc, "]");
10309   } else
10310     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
10311 }
10312 
10313 /// Emit a warning when adding a char literal to a string.
10314 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
10315                                    Expr *LHSExpr, Expr *RHSExpr) {
10316   const Expr *StringRefExpr = LHSExpr;
10317   const CharacterLiteral *CharExpr =
10318       dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
10319 
10320   if (!CharExpr) {
10321     CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
10322     StringRefExpr = RHSExpr;
10323   }
10324 
10325   if (!CharExpr || !StringRefExpr)
10326     return;
10327 
10328   const QualType StringType = StringRefExpr->getType();
10329 
10330   // Return if not a PointerType.
10331   if (!StringType->isAnyPointerType())
10332     return;
10333 
10334   // Return if not a CharacterType.
10335   if (!StringType->getPointeeType()->isAnyCharacterType())
10336     return;
10337 
10338   ASTContext &Ctx = Self.getASTContext();
10339   SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
10340 
10341   const QualType CharType = CharExpr->getType();
10342   if (!CharType->isAnyCharacterType() &&
10343       CharType->isIntegerType() &&
10344       llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
10345     Self.Diag(OpLoc, diag::warn_string_plus_char)
10346         << DiagRange << Ctx.CharTy;
10347   } else {
10348     Self.Diag(OpLoc, diag::warn_string_plus_char)
10349         << DiagRange << CharExpr->getType();
10350   }
10351 
10352   // Only print a fixit for str + char, not for char + str.
10353   if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
10354     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
10355     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
10356         << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
10357         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
10358         << FixItHint::CreateInsertion(EndLoc, "]");
10359   } else {
10360     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
10361   }
10362 }
10363 
10364 /// Emit error when two pointers are incompatible.
10365 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
10366                                            Expr *LHSExpr, Expr *RHSExpr) {
10367   assert(LHSExpr->getType()->isAnyPointerType());
10368   assert(RHSExpr->getType()->isAnyPointerType());
10369   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
10370     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
10371     << RHSExpr->getSourceRange();
10372 }
10373 
10374 // C99 6.5.6
10375 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
10376                                      SourceLocation Loc, BinaryOperatorKind Opc,
10377                                      QualType* CompLHSTy) {
10378   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10379 
10380   if (LHS.get()->getType()->isVectorType() ||
10381       RHS.get()->getType()->isVectorType()) {
10382     QualType compType = CheckVectorOperands(
10383         LHS, RHS, Loc, CompLHSTy,
10384         /*AllowBothBool*/getLangOpts().AltiVec,
10385         /*AllowBoolConversions*/getLangOpts().ZVector);
10386     if (CompLHSTy) *CompLHSTy = compType;
10387     return compType;
10388   }
10389 
10390   if (LHS.get()->getType()->isConstantMatrixType() ||
10391       RHS.get()->getType()->isConstantMatrixType()) {
10392     return CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
10393   }
10394 
10395   QualType compType = UsualArithmeticConversions(
10396       LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
10397   if (LHS.isInvalid() || RHS.isInvalid())
10398     return QualType();
10399 
10400   // Diagnose "string literal" '+' int and string '+' "char literal".
10401   if (Opc == BO_Add) {
10402     diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
10403     diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
10404   }
10405 
10406   // handle the common case first (both operands are arithmetic).
10407   if (!compType.isNull() && compType->isArithmeticType()) {
10408     if (CompLHSTy) *CompLHSTy = compType;
10409     return compType;
10410   }
10411 
10412   // Type-checking.  Ultimately the pointer's going to be in PExp;
10413   // note that we bias towards the LHS being the pointer.
10414   Expr *PExp = LHS.get(), *IExp = RHS.get();
10415 
10416   bool isObjCPointer;
10417   if (PExp->getType()->isPointerType()) {
10418     isObjCPointer = false;
10419   } else if (PExp->getType()->isObjCObjectPointerType()) {
10420     isObjCPointer = true;
10421   } else {
10422     std::swap(PExp, IExp);
10423     if (PExp->getType()->isPointerType()) {
10424       isObjCPointer = false;
10425     } else if (PExp->getType()->isObjCObjectPointerType()) {
10426       isObjCPointer = true;
10427     } else {
10428       return InvalidOperands(Loc, LHS, RHS);
10429     }
10430   }
10431   assert(PExp->getType()->isAnyPointerType());
10432 
10433   if (!IExp->getType()->isIntegerType())
10434     return InvalidOperands(Loc, LHS, RHS);
10435 
10436   // Adding to a null pointer results in undefined behavior.
10437   if (PExp->IgnoreParenCasts()->isNullPointerConstant(
10438           Context, Expr::NPC_ValueDependentIsNotNull)) {
10439     // In C++ adding zero to a null pointer is defined.
10440     Expr::EvalResult KnownVal;
10441     if (!getLangOpts().CPlusPlus ||
10442         (!IExp->isValueDependent() &&
10443          (!IExp->EvaluateAsInt(KnownVal, Context) ||
10444           KnownVal.Val.getInt() != 0))) {
10445       // Check the conditions to see if this is the 'p = nullptr + n' idiom.
10446       bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension(
10447           Context, BO_Add, PExp, IExp);
10448       diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
10449     }
10450   }
10451 
10452   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
10453     return QualType();
10454 
10455   if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
10456     return QualType();
10457 
10458   // Check array bounds for pointer arithemtic
10459   CheckArrayAccess(PExp, IExp);
10460 
10461   if (CompLHSTy) {
10462     QualType LHSTy = Context.isPromotableBitField(LHS.get());
10463     if (LHSTy.isNull()) {
10464       LHSTy = LHS.get()->getType();
10465       if (LHSTy->isPromotableIntegerType())
10466         LHSTy = Context.getPromotedIntegerType(LHSTy);
10467     }
10468     *CompLHSTy = LHSTy;
10469   }
10470 
10471   return PExp->getType();
10472 }
10473 
10474 // C99 6.5.6
10475 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
10476                                         SourceLocation Loc,
10477                                         QualType* CompLHSTy) {
10478   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10479 
10480   if (LHS.get()->getType()->isVectorType() ||
10481       RHS.get()->getType()->isVectorType()) {
10482     QualType compType = CheckVectorOperands(
10483         LHS, RHS, Loc, CompLHSTy,
10484         /*AllowBothBool*/getLangOpts().AltiVec,
10485         /*AllowBoolConversions*/getLangOpts().ZVector);
10486     if (CompLHSTy) *CompLHSTy = compType;
10487     return compType;
10488   }
10489 
10490   if (LHS.get()->getType()->isConstantMatrixType() ||
10491       RHS.get()->getType()->isConstantMatrixType()) {
10492     return CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
10493   }
10494 
10495   QualType compType = UsualArithmeticConversions(
10496       LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
10497   if (LHS.isInvalid() || RHS.isInvalid())
10498     return QualType();
10499 
10500   // Enforce type constraints: C99 6.5.6p3.
10501 
10502   // Handle the common case first (both operands are arithmetic).
10503   if (!compType.isNull() && compType->isArithmeticType()) {
10504     if (CompLHSTy) *CompLHSTy = compType;
10505     return compType;
10506   }
10507 
10508   // Either ptr - int   or   ptr - ptr.
10509   if (LHS.get()->getType()->isAnyPointerType()) {
10510     QualType lpointee = LHS.get()->getType()->getPointeeType();
10511 
10512     // Diagnose bad cases where we step over interface counts.
10513     if (LHS.get()->getType()->isObjCObjectPointerType() &&
10514         checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
10515       return QualType();
10516 
10517     // The result type of a pointer-int computation is the pointer type.
10518     if (RHS.get()->getType()->isIntegerType()) {
10519       // Subtracting from a null pointer should produce a warning.
10520       // The last argument to the diagnose call says this doesn't match the
10521       // GNU int-to-pointer idiom.
10522       if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context,
10523                                            Expr::NPC_ValueDependentIsNotNull)) {
10524         // In C++ adding zero to a null pointer is defined.
10525         Expr::EvalResult KnownVal;
10526         if (!getLangOpts().CPlusPlus ||
10527             (!RHS.get()->isValueDependent() &&
10528              (!RHS.get()->EvaluateAsInt(KnownVal, Context) ||
10529               KnownVal.Val.getInt() != 0))) {
10530           diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
10531         }
10532       }
10533 
10534       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
10535         return QualType();
10536 
10537       // Check array bounds for pointer arithemtic
10538       CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
10539                        /*AllowOnePastEnd*/true, /*IndexNegated*/true);
10540 
10541       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
10542       return LHS.get()->getType();
10543     }
10544 
10545     // Handle pointer-pointer subtractions.
10546     if (const PointerType *RHSPTy
10547           = RHS.get()->getType()->getAs<PointerType>()) {
10548       QualType rpointee = RHSPTy->getPointeeType();
10549 
10550       if (getLangOpts().CPlusPlus) {
10551         // Pointee types must be the same: C++ [expr.add]
10552         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
10553           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
10554         }
10555       } else {
10556         // Pointee types must be compatible C99 6.5.6p3
10557         if (!Context.typesAreCompatible(
10558                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
10559                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
10560           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
10561           return QualType();
10562         }
10563       }
10564 
10565       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
10566                                                LHS.get(), RHS.get()))
10567         return QualType();
10568 
10569       // FIXME: Add warnings for nullptr - ptr.
10570 
10571       // The pointee type may have zero size.  As an extension, a structure or
10572       // union may have zero size or an array may have zero length.  In this
10573       // case subtraction does not make sense.
10574       if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
10575         CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
10576         if (ElementSize.isZero()) {
10577           Diag(Loc,diag::warn_sub_ptr_zero_size_types)
10578             << rpointee.getUnqualifiedType()
10579             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10580         }
10581       }
10582 
10583       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
10584       return Context.getPointerDiffType();
10585     }
10586   }
10587 
10588   return InvalidOperands(Loc, LHS, RHS);
10589 }
10590 
10591 static bool isScopedEnumerationType(QualType T) {
10592   if (const EnumType *ET = T->getAs<EnumType>())
10593     return ET->getDecl()->isScoped();
10594   return false;
10595 }
10596 
10597 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
10598                                    SourceLocation Loc, BinaryOperatorKind Opc,
10599                                    QualType LHSType) {
10600   // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
10601   // so skip remaining warnings as we don't want to modify values within Sema.
10602   if (S.getLangOpts().OpenCL)
10603     return;
10604 
10605   // Check right/shifter operand
10606   Expr::EvalResult RHSResult;
10607   if (RHS.get()->isValueDependent() ||
10608       !RHS.get()->EvaluateAsInt(RHSResult, S.Context))
10609     return;
10610   llvm::APSInt Right = RHSResult.Val.getInt();
10611 
10612   if (Right.isNegative()) {
10613     S.DiagRuntimeBehavior(Loc, RHS.get(),
10614                           S.PDiag(diag::warn_shift_negative)
10615                             << RHS.get()->getSourceRange());
10616     return;
10617   }
10618 
10619   QualType LHSExprType = LHS.get()->getType();
10620   uint64_t LeftSize = LHSExprType->isExtIntType()
10621                           ? S.Context.getIntWidth(LHSExprType)
10622                           : S.Context.getTypeSize(LHSExprType);
10623   llvm::APInt LeftBits(Right.getBitWidth(), LeftSize);
10624   if (Right.uge(LeftBits)) {
10625     S.DiagRuntimeBehavior(Loc, RHS.get(),
10626                           S.PDiag(diag::warn_shift_gt_typewidth)
10627                             << RHS.get()->getSourceRange());
10628     return;
10629   }
10630 
10631   if (Opc != BO_Shl)
10632     return;
10633 
10634   // When left shifting an ICE which is signed, we can check for overflow which
10635   // according to C++ standards prior to C++2a has undefined behavior
10636   // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one
10637   // more than the maximum value representable in the result type, so never
10638   // warn for those. (FIXME: Unsigned left-shift overflow in a constant
10639   // expression is still probably a bug.)
10640   Expr::EvalResult LHSResult;
10641   if (LHS.get()->isValueDependent() ||
10642       LHSType->hasUnsignedIntegerRepresentation() ||
10643       !LHS.get()->EvaluateAsInt(LHSResult, S.Context))
10644     return;
10645   llvm::APSInt Left = LHSResult.Val.getInt();
10646 
10647   // If LHS does not have a signed type and non-negative value
10648   // then, the behavior is undefined before C++2a. Warn about it.
10649   if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined() &&
10650       !S.getLangOpts().CPlusPlus20) {
10651     S.DiagRuntimeBehavior(Loc, LHS.get(),
10652                           S.PDiag(diag::warn_shift_lhs_negative)
10653                             << LHS.get()->getSourceRange());
10654     return;
10655   }
10656 
10657   llvm::APInt ResultBits =
10658       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
10659   if (LeftBits.uge(ResultBits))
10660     return;
10661   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
10662   Result = Result.shl(Right);
10663 
10664   // Print the bit representation of the signed integer as an unsigned
10665   // hexadecimal number.
10666   SmallString<40> HexResult;
10667   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
10668 
10669   // If we are only missing a sign bit, this is less likely to result in actual
10670   // bugs -- if the result is cast back to an unsigned type, it will have the
10671   // expected value. Thus we place this behind a different warning that can be
10672   // turned off separately if needed.
10673   if (LeftBits == ResultBits - 1) {
10674     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
10675         << HexResult << LHSType
10676         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10677     return;
10678   }
10679 
10680   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
10681     << HexResult.str() << Result.getMinSignedBits() << LHSType
10682     << Left.getBitWidth() << LHS.get()->getSourceRange()
10683     << RHS.get()->getSourceRange();
10684 }
10685 
10686 /// Return the resulting type when a vector is shifted
10687 ///        by a scalar or vector shift amount.
10688 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
10689                                  SourceLocation Loc, bool IsCompAssign) {
10690   // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
10691   if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
10692       !LHS.get()->getType()->isVectorType()) {
10693     S.Diag(Loc, diag::err_shift_rhs_only_vector)
10694       << RHS.get()->getType() << LHS.get()->getType()
10695       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10696     return QualType();
10697   }
10698 
10699   if (!IsCompAssign) {
10700     LHS = S.UsualUnaryConversions(LHS.get());
10701     if (LHS.isInvalid()) return QualType();
10702   }
10703 
10704   RHS = S.UsualUnaryConversions(RHS.get());
10705   if (RHS.isInvalid()) return QualType();
10706 
10707   QualType LHSType = LHS.get()->getType();
10708   // Note that LHS might be a scalar because the routine calls not only in
10709   // OpenCL case.
10710   const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
10711   QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
10712 
10713   // Note that RHS might not be a vector.
10714   QualType RHSType = RHS.get()->getType();
10715   const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
10716   QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
10717 
10718   // The operands need to be integers.
10719   if (!LHSEleType->isIntegerType()) {
10720     S.Diag(Loc, diag::err_typecheck_expect_int)
10721       << LHS.get()->getType() << LHS.get()->getSourceRange();
10722     return QualType();
10723   }
10724 
10725   if (!RHSEleType->isIntegerType()) {
10726     S.Diag(Loc, diag::err_typecheck_expect_int)
10727       << RHS.get()->getType() << RHS.get()->getSourceRange();
10728     return QualType();
10729   }
10730 
10731   if (!LHSVecTy) {
10732     assert(RHSVecTy);
10733     if (IsCompAssign)
10734       return RHSType;
10735     if (LHSEleType != RHSEleType) {
10736       LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
10737       LHSEleType = RHSEleType;
10738     }
10739     QualType VecTy =
10740         S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
10741     LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
10742     LHSType = VecTy;
10743   } else if (RHSVecTy) {
10744     // OpenCL v1.1 s6.3.j says that for vector types, the operators
10745     // are applied component-wise. So if RHS is a vector, then ensure
10746     // that the number of elements is the same as LHS...
10747     if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
10748       S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
10749         << LHS.get()->getType() << RHS.get()->getType()
10750         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10751       return QualType();
10752     }
10753     if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
10754       const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
10755       const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
10756       if (LHSBT != RHSBT &&
10757           S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
10758         S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
10759             << LHS.get()->getType() << RHS.get()->getType()
10760             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10761       }
10762     }
10763   } else {
10764     // ...else expand RHS to match the number of elements in LHS.
10765     QualType VecTy =
10766       S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
10767     RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
10768   }
10769 
10770   return LHSType;
10771 }
10772 
10773 // C99 6.5.7
10774 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
10775                                   SourceLocation Loc, BinaryOperatorKind Opc,
10776                                   bool IsCompAssign) {
10777   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10778 
10779   // Vector shifts promote their scalar inputs to vector type.
10780   if (LHS.get()->getType()->isVectorType() ||
10781       RHS.get()->getType()->isVectorType()) {
10782     if (LangOpts.ZVector) {
10783       // The shift operators for the z vector extensions work basically
10784       // like general shifts, except that neither the LHS nor the RHS is
10785       // allowed to be a "vector bool".
10786       if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
10787         if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
10788           return InvalidOperands(Loc, LHS, RHS);
10789       if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
10790         if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
10791           return InvalidOperands(Loc, LHS, RHS);
10792     }
10793     return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
10794   }
10795 
10796   // Shifts don't perform usual arithmetic conversions, they just do integer
10797   // promotions on each operand. C99 6.5.7p3
10798 
10799   // For the LHS, do usual unary conversions, but then reset them away
10800   // if this is a compound assignment.
10801   ExprResult OldLHS = LHS;
10802   LHS = UsualUnaryConversions(LHS.get());
10803   if (LHS.isInvalid())
10804     return QualType();
10805   QualType LHSType = LHS.get()->getType();
10806   if (IsCompAssign) LHS = OldLHS;
10807 
10808   // The RHS is simpler.
10809   RHS = UsualUnaryConversions(RHS.get());
10810   if (RHS.isInvalid())
10811     return QualType();
10812   QualType RHSType = RHS.get()->getType();
10813 
10814   // C99 6.5.7p2: Each of the operands shall have integer type.
10815   if (!LHSType->hasIntegerRepresentation() ||
10816       !RHSType->hasIntegerRepresentation())
10817     return InvalidOperands(Loc, LHS, RHS);
10818 
10819   // C++0x: Don't allow scoped enums. FIXME: Use something better than
10820   // hasIntegerRepresentation() above instead of this.
10821   if (isScopedEnumerationType(LHSType) ||
10822       isScopedEnumerationType(RHSType)) {
10823     return InvalidOperands(Loc, LHS, RHS);
10824   }
10825   // Sanity-check shift operands
10826   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
10827 
10828   // "The type of the result is that of the promoted left operand."
10829   return LHSType;
10830 }
10831 
10832 /// Diagnose bad pointer comparisons.
10833 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
10834                                               ExprResult &LHS, ExprResult &RHS,
10835                                               bool IsError) {
10836   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
10837                       : diag::ext_typecheck_comparison_of_distinct_pointers)
10838     << LHS.get()->getType() << RHS.get()->getType()
10839     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10840 }
10841 
10842 /// Returns false if the pointers are converted to a composite type,
10843 /// true otherwise.
10844 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
10845                                            ExprResult &LHS, ExprResult &RHS) {
10846   // C++ [expr.rel]p2:
10847   //   [...] Pointer conversions (4.10) and qualification
10848   //   conversions (4.4) are performed on pointer operands (or on
10849   //   a pointer operand and a null pointer constant) to bring
10850   //   them to their composite pointer type. [...]
10851   //
10852   // C++ [expr.eq]p1 uses the same notion for (in)equality
10853   // comparisons of pointers.
10854 
10855   QualType LHSType = LHS.get()->getType();
10856   QualType RHSType = RHS.get()->getType();
10857   assert(LHSType->isPointerType() || RHSType->isPointerType() ||
10858          LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
10859 
10860   QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
10861   if (T.isNull()) {
10862     if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) &&
10863         (RHSType->isAnyPointerType() || RHSType->isMemberPointerType()))
10864       diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
10865     else
10866       S.InvalidOperands(Loc, LHS, RHS);
10867     return true;
10868   }
10869 
10870   return false;
10871 }
10872 
10873 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
10874                                                     ExprResult &LHS,
10875                                                     ExprResult &RHS,
10876                                                     bool IsError) {
10877   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
10878                       : diag::ext_typecheck_comparison_of_fptr_to_void)
10879     << LHS.get()->getType() << RHS.get()->getType()
10880     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10881 }
10882 
10883 static bool isObjCObjectLiteral(ExprResult &E) {
10884   switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
10885   case Stmt::ObjCArrayLiteralClass:
10886   case Stmt::ObjCDictionaryLiteralClass:
10887   case Stmt::ObjCStringLiteralClass:
10888   case Stmt::ObjCBoxedExprClass:
10889     return true;
10890   default:
10891     // Note that ObjCBoolLiteral is NOT an object literal!
10892     return false;
10893   }
10894 }
10895 
10896 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
10897   const ObjCObjectPointerType *Type =
10898     LHS->getType()->getAs<ObjCObjectPointerType>();
10899 
10900   // If this is not actually an Objective-C object, bail out.
10901   if (!Type)
10902     return false;
10903 
10904   // Get the LHS object's interface type.
10905   QualType InterfaceType = Type->getPointeeType();
10906 
10907   // If the RHS isn't an Objective-C object, bail out.
10908   if (!RHS->getType()->isObjCObjectPointerType())
10909     return false;
10910 
10911   // Try to find the -isEqual: method.
10912   Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
10913   ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
10914                                                       InterfaceType,
10915                                                       /*IsInstance=*/true);
10916   if (!Method) {
10917     if (Type->isObjCIdType()) {
10918       // For 'id', just check the global pool.
10919       Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
10920                                                   /*receiverId=*/true);
10921     } else {
10922       // Check protocols.
10923       Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
10924                                              /*IsInstance=*/true);
10925     }
10926   }
10927 
10928   if (!Method)
10929     return false;
10930 
10931   QualType T = Method->parameters()[0]->getType();
10932   if (!T->isObjCObjectPointerType())
10933     return false;
10934 
10935   QualType R = Method->getReturnType();
10936   if (!R->isScalarType())
10937     return false;
10938 
10939   return true;
10940 }
10941 
10942 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
10943   FromE = FromE->IgnoreParenImpCasts();
10944   switch (FromE->getStmtClass()) {
10945     default:
10946       break;
10947     case Stmt::ObjCStringLiteralClass:
10948       // "string literal"
10949       return LK_String;
10950     case Stmt::ObjCArrayLiteralClass:
10951       // "array literal"
10952       return LK_Array;
10953     case Stmt::ObjCDictionaryLiteralClass:
10954       // "dictionary literal"
10955       return LK_Dictionary;
10956     case Stmt::BlockExprClass:
10957       return LK_Block;
10958     case Stmt::ObjCBoxedExprClass: {
10959       Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
10960       switch (Inner->getStmtClass()) {
10961         case Stmt::IntegerLiteralClass:
10962         case Stmt::FloatingLiteralClass:
10963         case Stmt::CharacterLiteralClass:
10964         case Stmt::ObjCBoolLiteralExprClass:
10965         case Stmt::CXXBoolLiteralExprClass:
10966           // "numeric literal"
10967           return LK_Numeric;
10968         case Stmt::ImplicitCastExprClass: {
10969           CastKind CK = cast<CastExpr>(Inner)->getCastKind();
10970           // Boolean literals can be represented by implicit casts.
10971           if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
10972             return LK_Numeric;
10973           break;
10974         }
10975         default:
10976           break;
10977       }
10978       return LK_Boxed;
10979     }
10980   }
10981   return LK_None;
10982 }
10983 
10984 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
10985                                           ExprResult &LHS, ExprResult &RHS,
10986                                           BinaryOperator::Opcode Opc){
10987   Expr *Literal;
10988   Expr *Other;
10989   if (isObjCObjectLiteral(LHS)) {
10990     Literal = LHS.get();
10991     Other = RHS.get();
10992   } else {
10993     Literal = RHS.get();
10994     Other = LHS.get();
10995   }
10996 
10997   // Don't warn on comparisons against nil.
10998   Other = Other->IgnoreParenCasts();
10999   if (Other->isNullPointerConstant(S.getASTContext(),
11000                                    Expr::NPC_ValueDependentIsNotNull))
11001     return;
11002 
11003   // This should be kept in sync with warn_objc_literal_comparison.
11004   // LK_String should always be after the other literals, since it has its own
11005   // warning flag.
11006   Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
11007   assert(LiteralKind != Sema::LK_Block);
11008   if (LiteralKind == Sema::LK_None) {
11009     llvm_unreachable("Unknown Objective-C object literal kind");
11010   }
11011 
11012   if (LiteralKind == Sema::LK_String)
11013     S.Diag(Loc, diag::warn_objc_string_literal_comparison)
11014       << Literal->getSourceRange();
11015   else
11016     S.Diag(Loc, diag::warn_objc_literal_comparison)
11017       << LiteralKind << Literal->getSourceRange();
11018 
11019   if (BinaryOperator::isEqualityOp(Opc) &&
11020       hasIsEqualMethod(S, LHS.get(), RHS.get())) {
11021     SourceLocation Start = LHS.get()->getBeginLoc();
11022     SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc());
11023     CharSourceRange OpRange =
11024       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
11025 
11026     S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
11027       << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
11028       << FixItHint::CreateReplacement(OpRange, " isEqual:")
11029       << FixItHint::CreateInsertion(End, "]");
11030   }
11031 }
11032 
11033 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
11034 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
11035                                            ExprResult &RHS, SourceLocation Loc,
11036                                            BinaryOperatorKind Opc) {
11037   // Check that left hand side is !something.
11038   UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
11039   if (!UO || UO->getOpcode() != UO_LNot) return;
11040 
11041   // Only check if the right hand side is non-bool arithmetic type.
11042   if (RHS.get()->isKnownToHaveBooleanValue()) return;
11043 
11044   // Make sure that the something in !something is not bool.
11045   Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
11046   if (SubExpr->isKnownToHaveBooleanValue()) return;
11047 
11048   // Emit warning.
11049   bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
11050   S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
11051       << Loc << IsBitwiseOp;
11052 
11053   // First note suggest !(x < y)
11054   SourceLocation FirstOpen = SubExpr->getBeginLoc();
11055   SourceLocation FirstClose = RHS.get()->getEndLoc();
11056   FirstClose = S.getLocForEndOfToken(FirstClose);
11057   if (FirstClose.isInvalid())
11058     FirstOpen = SourceLocation();
11059   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
11060       << IsBitwiseOp
11061       << FixItHint::CreateInsertion(FirstOpen, "(")
11062       << FixItHint::CreateInsertion(FirstClose, ")");
11063 
11064   // Second note suggests (!x) < y
11065   SourceLocation SecondOpen = LHS.get()->getBeginLoc();
11066   SourceLocation SecondClose = LHS.get()->getEndLoc();
11067   SecondClose = S.getLocForEndOfToken(SecondClose);
11068   if (SecondClose.isInvalid())
11069     SecondOpen = SourceLocation();
11070   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
11071       << FixItHint::CreateInsertion(SecondOpen, "(")
11072       << FixItHint::CreateInsertion(SecondClose, ")");
11073 }
11074 
11075 // Returns true if E refers to a non-weak array.
11076 static bool checkForArray(const Expr *E) {
11077   const ValueDecl *D = nullptr;
11078   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
11079     D = DR->getDecl();
11080   } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
11081     if (Mem->isImplicitAccess())
11082       D = Mem->getMemberDecl();
11083   }
11084   if (!D)
11085     return false;
11086   return D->getType()->isArrayType() && !D->isWeak();
11087 }
11088 
11089 /// Diagnose some forms of syntactically-obvious tautological comparison.
11090 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc,
11091                                            Expr *LHS, Expr *RHS,
11092                                            BinaryOperatorKind Opc) {
11093   Expr *LHSStripped = LHS->IgnoreParenImpCasts();
11094   Expr *RHSStripped = RHS->IgnoreParenImpCasts();
11095 
11096   QualType LHSType = LHS->getType();
11097   QualType RHSType = RHS->getType();
11098   if (LHSType->hasFloatingRepresentation() ||
11099       (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
11100       S.inTemplateInstantiation())
11101     return;
11102 
11103   // Comparisons between two array types are ill-formed for operator<=>, so
11104   // we shouldn't emit any additional warnings about it.
11105   if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
11106     return;
11107 
11108   // For non-floating point types, check for self-comparisons of the form
11109   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
11110   // often indicate logic errors in the program.
11111   //
11112   // NOTE: Don't warn about comparison expressions resulting from macro
11113   // expansion. Also don't warn about comparisons which are only self
11114   // comparisons within a template instantiation. The warnings should catch
11115   // obvious cases in the definition of the template anyways. The idea is to
11116   // warn when the typed comparison operator will always evaluate to the same
11117   // result.
11118 
11119   // Used for indexing into %select in warn_comparison_always
11120   enum {
11121     AlwaysConstant,
11122     AlwaysTrue,
11123     AlwaysFalse,
11124     AlwaysEqual, // std::strong_ordering::equal from operator<=>
11125   };
11126 
11127   // C++2a [depr.array.comp]:
11128   //   Equality and relational comparisons ([expr.eq], [expr.rel]) between two
11129   //   operands of array type are deprecated.
11130   if (S.getLangOpts().CPlusPlus20 && LHSStripped->getType()->isArrayType() &&
11131       RHSStripped->getType()->isArrayType()) {
11132     S.Diag(Loc, diag::warn_depr_array_comparison)
11133         << LHS->getSourceRange() << RHS->getSourceRange()
11134         << LHSStripped->getType() << RHSStripped->getType();
11135     // Carry on to produce the tautological comparison warning, if this
11136     // expression is potentially-evaluated, we can resolve the array to a
11137     // non-weak declaration, and so on.
11138   }
11139 
11140   if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) {
11141     if (Expr::isSameComparisonOperand(LHS, RHS)) {
11142       unsigned Result;
11143       switch (Opc) {
11144       case BO_EQ:
11145       case BO_LE:
11146       case BO_GE:
11147         Result = AlwaysTrue;
11148         break;
11149       case BO_NE:
11150       case BO_LT:
11151       case BO_GT:
11152         Result = AlwaysFalse;
11153         break;
11154       case BO_Cmp:
11155         Result = AlwaysEqual;
11156         break;
11157       default:
11158         Result = AlwaysConstant;
11159         break;
11160       }
11161       S.DiagRuntimeBehavior(Loc, nullptr,
11162                             S.PDiag(diag::warn_comparison_always)
11163                                 << 0 /*self-comparison*/
11164                                 << Result);
11165     } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) {
11166       // What is it always going to evaluate to?
11167       unsigned Result;
11168       switch (Opc) {
11169       case BO_EQ: // e.g. array1 == array2
11170         Result = AlwaysFalse;
11171         break;
11172       case BO_NE: // e.g. array1 != array2
11173         Result = AlwaysTrue;
11174         break;
11175       default: // e.g. array1 <= array2
11176         // The best we can say is 'a constant'
11177         Result = AlwaysConstant;
11178         break;
11179       }
11180       S.DiagRuntimeBehavior(Loc, nullptr,
11181                             S.PDiag(diag::warn_comparison_always)
11182                                 << 1 /*array comparison*/
11183                                 << Result);
11184     }
11185   }
11186 
11187   if (isa<CastExpr>(LHSStripped))
11188     LHSStripped = LHSStripped->IgnoreParenCasts();
11189   if (isa<CastExpr>(RHSStripped))
11190     RHSStripped = RHSStripped->IgnoreParenCasts();
11191 
11192   // Warn about comparisons against a string constant (unless the other
11193   // operand is null); the user probably wants string comparison function.
11194   Expr *LiteralString = nullptr;
11195   Expr *LiteralStringStripped = nullptr;
11196   if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
11197       !RHSStripped->isNullPointerConstant(S.Context,
11198                                           Expr::NPC_ValueDependentIsNull)) {
11199     LiteralString = LHS;
11200     LiteralStringStripped = LHSStripped;
11201   } else if ((isa<StringLiteral>(RHSStripped) ||
11202               isa<ObjCEncodeExpr>(RHSStripped)) &&
11203              !LHSStripped->isNullPointerConstant(S.Context,
11204                                           Expr::NPC_ValueDependentIsNull)) {
11205     LiteralString = RHS;
11206     LiteralStringStripped = RHSStripped;
11207   }
11208 
11209   if (LiteralString) {
11210     S.DiagRuntimeBehavior(Loc, nullptr,
11211                           S.PDiag(diag::warn_stringcompare)
11212                               << isa<ObjCEncodeExpr>(LiteralStringStripped)
11213                               << LiteralString->getSourceRange());
11214   }
11215 }
11216 
11217 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) {
11218   switch (CK) {
11219   default: {
11220 #ifndef NDEBUG
11221     llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
11222                  << "\n";
11223 #endif
11224     llvm_unreachable("unhandled cast kind");
11225   }
11226   case CK_UserDefinedConversion:
11227     return ICK_Identity;
11228   case CK_LValueToRValue:
11229     return ICK_Lvalue_To_Rvalue;
11230   case CK_ArrayToPointerDecay:
11231     return ICK_Array_To_Pointer;
11232   case CK_FunctionToPointerDecay:
11233     return ICK_Function_To_Pointer;
11234   case CK_IntegralCast:
11235     return ICK_Integral_Conversion;
11236   case CK_FloatingCast:
11237     return ICK_Floating_Conversion;
11238   case CK_IntegralToFloating:
11239   case CK_FloatingToIntegral:
11240     return ICK_Floating_Integral;
11241   case CK_IntegralComplexCast:
11242   case CK_FloatingComplexCast:
11243   case CK_FloatingComplexToIntegralComplex:
11244   case CK_IntegralComplexToFloatingComplex:
11245     return ICK_Complex_Conversion;
11246   case CK_FloatingComplexToReal:
11247   case CK_FloatingRealToComplex:
11248   case CK_IntegralComplexToReal:
11249   case CK_IntegralRealToComplex:
11250     return ICK_Complex_Real;
11251   }
11252 }
11253 
11254 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E,
11255                                              QualType FromType,
11256                                              SourceLocation Loc) {
11257   // Check for a narrowing implicit conversion.
11258   StandardConversionSequence SCS;
11259   SCS.setAsIdentityConversion();
11260   SCS.setToType(0, FromType);
11261   SCS.setToType(1, ToType);
11262   if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
11263     SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
11264 
11265   APValue PreNarrowingValue;
11266   QualType PreNarrowingType;
11267   switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
11268                                PreNarrowingType,
11269                                /*IgnoreFloatToIntegralConversion*/ true)) {
11270   case NK_Dependent_Narrowing:
11271     // Implicit conversion to a narrower type, but the expression is
11272     // value-dependent so we can't tell whether it's actually narrowing.
11273   case NK_Not_Narrowing:
11274     return false;
11275 
11276   case NK_Constant_Narrowing:
11277     // Implicit conversion to a narrower type, and the value is not a constant
11278     // expression.
11279     S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
11280         << /*Constant*/ 1
11281         << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
11282     return true;
11283 
11284   case NK_Variable_Narrowing:
11285     // Implicit conversion to a narrower type, and the value is not a constant
11286     // expression.
11287   case NK_Type_Narrowing:
11288     S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
11289         << /*Constant*/ 0 << FromType << ToType;
11290     // TODO: It's not a constant expression, but what if the user intended it
11291     // to be? Can we produce notes to help them figure out why it isn't?
11292     return true;
11293   }
11294   llvm_unreachable("unhandled case in switch");
11295 }
11296 
11297 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S,
11298                                                          ExprResult &LHS,
11299                                                          ExprResult &RHS,
11300                                                          SourceLocation Loc) {
11301   QualType LHSType = LHS.get()->getType();
11302   QualType RHSType = RHS.get()->getType();
11303   // Dig out the original argument type and expression before implicit casts
11304   // were applied. These are the types/expressions we need to check the
11305   // [expr.spaceship] requirements against.
11306   ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
11307   ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
11308   QualType LHSStrippedType = LHSStripped.get()->getType();
11309   QualType RHSStrippedType = RHSStripped.get()->getType();
11310 
11311   // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
11312   // other is not, the program is ill-formed.
11313   if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
11314     S.InvalidOperands(Loc, LHSStripped, RHSStripped);
11315     return QualType();
11316   }
11317 
11318   // FIXME: Consider combining this with checkEnumArithmeticConversions.
11319   int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
11320                     RHSStrippedType->isEnumeralType();
11321   if (NumEnumArgs == 1) {
11322     bool LHSIsEnum = LHSStrippedType->isEnumeralType();
11323     QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
11324     if (OtherTy->hasFloatingRepresentation()) {
11325       S.InvalidOperands(Loc, LHSStripped, RHSStripped);
11326       return QualType();
11327     }
11328   }
11329   if (NumEnumArgs == 2) {
11330     // C++2a [expr.spaceship]p5: If both operands have the same enumeration
11331     // type E, the operator yields the result of converting the operands
11332     // to the underlying type of E and applying <=> to the converted operands.
11333     if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
11334       S.InvalidOperands(Loc, LHS, RHS);
11335       return QualType();
11336     }
11337     QualType IntType =
11338         LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType();
11339     assert(IntType->isArithmeticType());
11340 
11341     // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
11342     // promote the boolean type, and all other promotable integer types, to
11343     // avoid this.
11344     if (IntType->isPromotableIntegerType())
11345       IntType = S.Context.getPromotedIntegerType(IntType);
11346 
11347     LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
11348     RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
11349     LHSType = RHSType = IntType;
11350   }
11351 
11352   // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
11353   // usual arithmetic conversions are applied to the operands.
11354   QualType Type =
11355       S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison);
11356   if (LHS.isInvalid() || RHS.isInvalid())
11357     return QualType();
11358   if (Type.isNull())
11359     return S.InvalidOperands(Loc, LHS, RHS);
11360 
11361   Optional<ComparisonCategoryType> CCT =
11362       getComparisonCategoryForBuiltinCmp(Type);
11363   if (!CCT)
11364     return S.InvalidOperands(Loc, LHS, RHS);
11365 
11366   bool HasNarrowing = checkThreeWayNarrowingConversion(
11367       S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc());
11368   HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType,
11369                                                    RHS.get()->getBeginLoc());
11370   if (HasNarrowing)
11371     return QualType();
11372 
11373   assert(!Type.isNull() && "composite type for <=> has not been set");
11374 
11375   return S.CheckComparisonCategoryType(
11376       *CCT, Loc, Sema::ComparisonCategoryUsage::OperatorInExpression);
11377 }
11378 
11379 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS,
11380                                                  ExprResult &RHS,
11381                                                  SourceLocation Loc,
11382                                                  BinaryOperatorKind Opc) {
11383   if (Opc == BO_Cmp)
11384     return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
11385 
11386   // C99 6.5.8p3 / C99 6.5.9p4
11387   QualType Type =
11388       S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison);
11389   if (LHS.isInvalid() || RHS.isInvalid())
11390     return QualType();
11391   if (Type.isNull())
11392     return S.InvalidOperands(Loc, LHS, RHS);
11393   assert(Type->isArithmeticType() || Type->isEnumeralType());
11394 
11395   if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc))
11396     return S.InvalidOperands(Loc, LHS, RHS);
11397 
11398   // Check for comparisons of floating point operands using != and ==.
11399   if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc))
11400     S.CheckFloatComparison(Loc, LHS.get(), RHS.get());
11401 
11402   // The result of comparisons is 'bool' in C++, 'int' in C.
11403   return S.Context.getLogicalOperationType();
11404 }
11405 
11406 void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) {
11407   if (!NullE.get()->getType()->isAnyPointerType())
11408     return;
11409   int NullValue = PP.isMacroDefined("NULL") ? 0 : 1;
11410   if (!E.get()->getType()->isAnyPointerType() &&
11411       E.get()->isNullPointerConstant(Context,
11412                                      Expr::NPC_ValueDependentIsNotNull) ==
11413         Expr::NPCK_ZeroExpression) {
11414     if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) {
11415       if (CL->getValue() == 0)
11416         Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
11417             << NullValue
11418             << FixItHint::CreateReplacement(E.get()->getExprLoc(),
11419                                             NullValue ? "NULL" : "(void *)0");
11420     } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) {
11421         TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
11422         QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType();
11423         if (T == Context.CharTy)
11424           Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
11425               << NullValue
11426               << FixItHint::CreateReplacement(E.get()->getExprLoc(),
11427                                               NullValue ? "NULL" : "(void *)0");
11428       }
11429   }
11430 }
11431 
11432 // C99 6.5.8, C++ [expr.rel]
11433 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
11434                                     SourceLocation Loc,
11435                                     BinaryOperatorKind Opc) {
11436   bool IsRelational = BinaryOperator::isRelationalOp(Opc);
11437   bool IsThreeWay = Opc == BO_Cmp;
11438   bool IsOrdered = IsRelational || IsThreeWay;
11439   auto IsAnyPointerType = [](ExprResult E) {
11440     QualType Ty = E.get()->getType();
11441     return Ty->isPointerType() || Ty->isMemberPointerType();
11442   };
11443 
11444   // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
11445   // type, array-to-pointer, ..., conversions are performed on both operands to
11446   // bring them to their composite type.
11447   // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
11448   // any type-related checks.
11449   if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
11450     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
11451     if (LHS.isInvalid())
11452       return QualType();
11453     RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
11454     if (RHS.isInvalid())
11455       return QualType();
11456   } else {
11457     LHS = DefaultLvalueConversion(LHS.get());
11458     if (LHS.isInvalid())
11459       return QualType();
11460     RHS = DefaultLvalueConversion(RHS.get());
11461     if (RHS.isInvalid())
11462       return QualType();
11463   }
11464 
11465   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true);
11466   if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) {
11467     CheckPtrComparisonWithNullChar(LHS, RHS);
11468     CheckPtrComparisonWithNullChar(RHS, LHS);
11469   }
11470 
11471   // Handle vector comparisons separately.
11472   if (LHS.get()->getType()->isVectorType() ||
11473       RHS.get()->getType()->isVectorType())
11474     return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
11475 
11476   diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
11477   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
11478 
11479   QualType LHSType = LHS.get()->getType();
11480   QualType RHSType = RHS.get()->getType();
11481   if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
11482       (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
11483     return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
11484 
11485   const Expr::NullPointerConstantKind LHSNullKind =
11486       LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
11487   const Expr::NullPointerConstantKind RHSNullKind =
11488       RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
11489   bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
11490   bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
11491 
11492   auto computeResultTy = [&]() {
11493     if (Opc != BO_Cmp)
11494       return Context.getLogicalOperationType();
11495     assert(getLangOpts().CPlusPlus);
11496     assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
11497 
11498     QualType CompositeTy = LHS.get()->getType();
11499     assert(!CompositeTy->isReferenceType());
11500 
11501     Optional<ComparisonCategoryType> CCT =
11502         getComparisonCategoryForBuiltinCmp(CompositeTy);
11503     if (!CCT)
11504       return InvalidOperands(Loc, LHS, RHS);
11505 
11506     if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) {
11507       // P0946R0: Comparisons between a null pointer constant and an object
11508       // pointer result in std::strong_equality, which is ill-formed under
11509       // P1959R0.
11510       Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero)
11511           << (LHSIsNull ? LHS.get()->getSourceRange()
11512                         : RHS.get()->getSourceRange());
11513       return QualType();
11514     }
11515 
11516     return CheckComparisonCategoryType(
11517         *CCT, Loc, ComparisonCategoryUsage::OperatorInExpression);
11518   };
11519 
11520   if (!IsOrdered && LHSIsNull != RHSIsNull) {
11521     bool IsEquality = Opc == BO_EQ;
11522     if (RHSIsNull)
11523       DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
11524                                    RHS.get()->getSourceRange());
11525     else
11526       DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
11527                                    LHS.get()->getSourceRange());
11528   }
11529 
11530   if ((LHSType->isIntegerType() && !LHSIsNull) ||
11531       (RHSType->isIntegerType() && !RHSIsNull)) {
11532     // Skip normal pointer conversion checks in this case; we have better
11533     // diagnostics for this below.
11534   } else if (getLangOpts().CPlusPlus) {
11535     // Equality comparison of a function pointer to a void pointer is invalid,
11536     // but we allow it as an extension.
11537     // FIXME: If we really want to allow this, should it be part of composite
11538     // pointer type computation so it works in conditionals too?
11539     if (!IsOrdered &&
11540         ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
11541          (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
11542       // This is a gcc extension compatibility comparison.
11543       // In a SFINAE context, we treat this as a hard error to maintain
11544       // conformance with the C++ standard.
11545       diagnoseFunctionPointerToVoidComparison(
11546           *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
11547 
11548       if (isSFINAEContext())
11549         return QualType();
11550 
11551       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
11552       return computeResultTy();
11553     }
11554 
11555     // C++ [expr.eq]p2:
11556     //   If at least one operand is a pointer [...] bring them to their
11557     //   composite pointer type.
11558     // C++ [expr.spaceship]p6
11559     //  If at least one of the operands is of pointer type, [...] bring them
11560     //  to their composite pointer type.
11561     // C++ [expr.rel]p2:
11562     //   If both operands are pointers, [...] bring them to their composite
11563     //   pointer type.
11564     // For <=>, the only valid non-pointer types are arrays and functions, and
11565     // we already decayed those, so this is really the same as the relational
11566     // comparison rule.
11567     if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
11568             (IsOrdered ? 2 : 1) &&
11569         (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
11570                                          RHSType->isObjCObjectPointerType()))) {
11571       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
11572         return QualType();
11573       return computeResultTy();
11574     }
11575   } else if (LHSType->isPointerType() &&
11576              RHSType->isPointerType()) { // C99 6.5.8p2
11577     // All of the following pointer-related warnings are GCC extensions, except
11578     // when handling null pointer constants.
11579     QualType LCanPointeeTy =
11580       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
11581     QualType RCanPointeeTy =
11582       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
11583 
11584     // C99 6.5.9p2 and C99 6.5.8p2
11585     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
11586                                    RCanPointeeTy.getUnqualifiedType())) {
11587       // Valid unless a relational comparison of function pointers
11588       if (IsRelational && LCanPointeeTy->isFunctionType()) {
11589         Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
11590           << LHSType << RHSType << LHS.get()->getSourceRange()
11591           << RHS.get()->getSourceRange();
11592       }
11593     } else if (!IsRelational &&
11594                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
11595       // Valid unless comparison between non-null pointer and function pointer
11596       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
11597           && !LHSIsNull && !RHSIsNull)
11598         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
11599                                                 /*isError*/false);
11600     } else {
11601       // Invalid
11602       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
11603     }
11604     if (LCanPointeeTy != RCanPointeeTy) {
11605       // Treat NULL constant as a special case in OpenCL.
11606       if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
11607         if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy)) {
11608           Diag(Loc,
11609                diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
11610               << LHSType << RHSType << 0 /* comparison */
11611               << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11612         }
11613       }
11614       LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
11615       LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
11616       CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
11617                                                : CK_BitCast;
11618       if (LHSIsNull && !RHSIsNull)
11619         LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
11620       else
11621         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
11622     }
11623     return computeResultTy();
11624   }
11625 
11626   if (getLangOpts().CPlusPlus) {
11627     // C++ [expr.eq]p4:
11628     //   Two operands of type std::nullptr_t or one operand of type
11629     //   std::nullptr_t and the other a null pointer constant compare equal.
11630     if (!IsOrdered && LHSIsNull && RHSIsNull) {
11631       if (LHSType->isNullPtrType()) {
11632         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11633         return computeResultTy();
11634       }
11635       if (RHSType->isNullPtrType()) {
11636         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11637         return computeResultTy();
11638       }
11639     }
11640 
11641     // Comparison of Objective-C pointers and block pointers against nullptr_t.
11642     // These aren't covered by the composite pointer type rules.
11643     if (!IsOrdered && RHSType->isNullPtrType() &&
11644         (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
11645       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11646       return computeResultTy();
11647     }
11648     if (!IsOrdered && LHSType->isNullPtrType() &&
11649         (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
11650       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11651       return computeResultTy();
11652     }
11653 
11654     if (IsRelational &&
11655         ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
11656          (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
11657       // HACK: Relational comparison of nullptr_t against a pointer type is
11658       // invalid per DR583, but we allow it within std::less<> and friends,
11659       // since otherwise common uses of it break.
11660       // FIXME: Consider removing this hack once LWG fixes std::less<> and
11661       // friends to have std::nullptr_t overload candidates.
11662       DeclContext *DC = CurContext;
11663       if (isa<FunctionDecl>(DC))
11664         DC = DC->getParent();
11665       if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
11666         if (CTSD->isInStdNamespace() &&
11667             llvm::StringSwitch<bool>(CTSD->getName())
11668                 .Cases("less", "less_equal", "greater", "greater_equal", true)
11669                 .Default(false)) {
11670           if (RHSType->isNullPtrType())
11671             RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11672           else
11673             LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11674           return computeResultTy();
11675         }
11676       }
11677     }
11678 
11679     // C++ [expr.eq]p2:
11680     //   If at least one operand is a pointer to member, [...] bring them to
11681     //   their composite pointer type.
11682     if (!IsOrdered &&
11683         (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
11684       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
11685         return QualType();
11686       else
11687         return computeResultTy();
11688     }
11689   }
11690 
11691   // Handle block pointer types.
11692   if (!IsOrdered && LHSType->isBlockPointerType() &&
11693       RHSType->isBlockPointerType()) {
11694     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
11695     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
11696 
11697     if (!LHSIsNull && !RHSIsNull &&
11698         !Context.typesAreCompatible(lpointee, rpointee)) {
11699       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
11700         << LHSType << RHSType << LHS.get()->getSourceRange()
11701         << RHS.get()->getSourceRange();
11702     }
11703     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
11704     return computeResultTy();
11705   }
11706 
11707   // Allow block pointers to be compared with null pointer constants.
11708   if (!IsOrdered
11709       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
11710           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
11711     if (!LHSIsNull && !RHSIsNull) {
11712       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
11713              ->getPointeeType()->isVoidType())
11714             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
11715                 ->getPointeeType()->isVoidType())))
11716         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
11717           << LHSType << RHSType << LHS.get()->getSourceRange()
11718           << RHS.get()->getSourceRange();
11719     }
11720     if (LHSIsNull && !RHSIsNull)
11721       LHS = ImpCastExprToType(LHS.get(), RHSType,
11722                               RHSType->isPointerType() ? CK_BitCast
11723                                 : CK_AnyPointerToBlockPointerCast);
11724     else
11725       RHS = ImpCastExprToType(RHS.get(), LHSType,
11726                               LHSType->isPointerType() ? CK_BitCast
11727                                 : CK_AnyPointerToBlockPointerCast);
11728     return computeResultTy();
11729   }
11730 
11731   if (LHSType->isObjCObjectPointerType() ||
11732       RHSType->isObjCObjectPointerType()) {
11733     const PointerType *LPT = LHSType->getAs<PointerType>();
11734     const PointerType *RPT = RHSType->getAs<PointerType>();
11735     if (LPT || RPT) {
11736       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
11737       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
11738 
11739       if (!LPtrToVoid && !RPtrToVoid &&
11740           !Context.typesAreCompatible(LHSType, RHSType)) {
11741         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
11742                                           /*isError*/false);
11743       }
11744       // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than
11745       // the RHS, but we have test coverage for this behavior.
11746       // FIXME: Consider using convertPointersToCompositeType in C++.
11747       if (LHSIsNull && !RHSIsNull) {
11748         Expr *E = LHS.get();
11749         if (getLangOpts().ObjCAutoRefCount)
11750           CheckObjCConversion(SourceRange(), RHSType, E,
11751                               CCK_ImplicitConversion);
11752         LHS = ImpCastExprToType(E, RHSType,
11753                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
11754       }
11755       else {
11756         Expr *E = RHS.get();
11757         if (getLangOpts().ObjCAutoRefCount)
11758           CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion,
11759                               /*Diagnose=*/true,
11760                               /*DiagnoseCFAudited=*/false, Opc);
11761         RHS = ImpCastExprToType(E, LHSType,
11762                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
11763       }
11764       return computeResultTy();
11765     }
11766     if (LHSType->isObjCObjectPointerType() &&
11767         RHSType->isObjCObjectPointerType()) {
11768       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
11769         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
11770                                           /*isError*/false);
11771       if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
11772         diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
11773 
11774       if (LHSIsNull && !RHSIsNull)
11775         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
11776       else
11777         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
11778       return computeResultTy();
11779     }
11780 
11781     if (!IsOrdered && LHSType->isBlockPointerType() &&
11782         RHSType->isBlockCompatibleObjCPointerType(Context)) {
11783       LHS = ImpCastExprToType(LHS.get(), RHSType,
11784                               CK_BlockPointerToObjCPointerCast);
11785       return computeResultTy();
11786     } else if (!IsOrdered &&
11787                LHSType->isBlockCompatibleObjCPointerType(Context) &&
11788                RHSType->isBlockPointerType()) {
11789       RHS = ImpCastExprToType(RHS.get(), LHSType,
11790                               CK_BlockPointerToObjCPointerCast);
11791       return computeResultTy();
11792     }
11793   }
11794   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
11795       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
11796     unsigned DiagID = 0;
11797     bool isError = false;
11798     if (LangOpts.DebuggerSupport) {
11799       // Under a debugger, allow the comparison of pointers to integers,
11800       // since users tend to want to compare addresses.
11801     } else if ((LHSIsNull && LHSType->isIntegerType()) ||
11802                (RHSIsNull && RHSType->isIntegerType())) {
11803       if (IsOrdered) {
11804         isError = getLangOpts().CPlusPlus;
11805         DiagID =
11806           isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
11807                   : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
11808       }
11809     } else if (getLangOpts().CPlusPlus) {
11810       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
11811       isError = true;
11812     } else if (IsOrdered)
11813       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
11814     else
11815       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
11816 
11817     if (DiagID) {
11818       Diag(Loc, DiagID)
11819         << LHSType << RHSType << LHS.get()->getSourceRange()
11820         << RHS.get()->getSourceRange();
11821       if (isError)
11822         return QualType();
11823     }
11824 
11825     if (LHSType->isIntegerType())
11826       LHS = ImpCastExprToType(LHS.get(), RHSType,
11827                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
11828     else
11829       RHS = ImpCastExprToType(RHS.get(), LHSType,
11830                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
11831     return computeResultTy();
11832   }
11833 
11834   // Handle block pointers.
11835   if (!IsOrdered && RHSIsNull
11836       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
11837     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11838     return computeResultTy();
11839   }
11840   if (!IsOrdered && LHSIsNull
11841       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
11842     LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11843     return computeResultTy();
11844   }
11845 
11846   if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) {
11847     if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
11848       return computeResultTy();
11849     }
11850 
11851     if (LHSType->isQueueT() && RHSType->isQueueT()) {
11852       return computeResultTy();
11853     }
11854 
11855     if (LHSIsNull && RHSType->isQueueT()) {
11856       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11857       return computeResultTy();
11858     }
11859 
11860     if (LHSType->isQueueT() && RHSIsNull) {
11861       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11862       return computeResultTy();
11863     }
11864   }
11865 
11866   return InvalidOperands(Loc, LHS, RHS);
11867 }
11868 
11869 // Return a signed ext_vector_type that is of identical size and number of
11870 // elements. For floating point vectors, return an integer type of identical
11871 // size and number of elements. In the non ext_vector_type case, search from
11872 // the largest type to the smallest type to avoid cases where long long == long,
11873 // where long gets picked over long long.
11874 QualType Sema::GetSignedVectorType(QualType V) {
11875   const VectorType *VTy = V->castAs<VectorType>();
11876   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
11877 
11878   if (isa<ExtVectorType>(VTy)) {
11879     if (TypeSize == Context.getTypeSize(Context.CharTy))
11880       return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
11881     else if (TypeSize == Context.getTypeSize(Context.ShortTy))
11882       return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
11883     else if (TypeSize == Context.getTypeSize(Context.IntTy))
11884       return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
11885     else if (TypeSize == Context.getTypeSize(Context.LongTy))
11886       return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
11887     assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
11888            "Unhandled vector element size in vector compare");
11889     return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
11890   }
11891 
11892   if (TypeSize == Context.getTypeSize(Context.LongLongTy))
11893     return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
11894                                  VectorType::GenericVector);
11895   else if (TypeSize == Context.getTypeSize(Context.LongTy))
11896     return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
11897                                  VectorType::GenericVector);
11898   else if (TypeSize == Context.getTypeSize(Context.IntTy))
11899     return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
11900                                  VectorType::GenericVector);
11901   else if (TypeSize == Context.getTypeSize(Context.ShortTy))
11902     return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
11903                                  VectorType::GenericVector);
11904   assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
11905          "Unhandled vector element size in vector compare");
11906   return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
11907                                VectorType::GenericVector);
11908 }
11909 
11910 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
11911 /// operates on extended vector types.  Instead of producing an IntTy result,
11912 /// like a scalar comparison, a vector comparison produces a vector of integer
11913 /// types.
11914 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
11915                                           SourceLocation Loc,
11916                                           BinaryOperatorKind Opc) {
11917   if (Opc == BO_Cmp) {
11918     Diag(Loc, diag::err_three_way_vector_comparison);
11919     return QualType();
11920   }
11921 
11922   // Check to make sure we're operating on vectors of the same type and width,
11923   // Allowing one side to be a scalar of element type.
11924   QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
11925                               /*AllowBothBool*/true,
11926                               /*AllowBoolConversions*/getLangOpts().ZVector);
11927   if (vType.isNull())
11928     return vType;
11929 
11930   QualType LHSType = LHS.get()->getType();
11931 
11932   // If AltiVec, the comparison results in a numeric type, i.e.
11933   // bool for C++, int for C
11934   if (getLangOpts().AltiVec &&
11935       vType->castAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
11936     return Context.getLogicalOperationType();
11937 
11938   // For non-floating point types, check for self-comparisons of the form
11939   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
11940   // often indicate logic errors in the program.
11941   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
11942 
11943   // Check for comparisons of floating point operands using != and ==.
11944   if (BinaryOperator::isEqualityOp(Opc) &&
11945       LHSType->hasFloatingRepresentation()) {
11946     assert(RHS.get()->getType()->hasFloatingRepresentation());
11947     CheckFloatComparison(Loc, LHS.get(), RHS.get());
11948   }
11949 
11950   // Return a signed type for the vector.
11951   return GetSignedVectorType(vType);
11952 }
11953 
11954 static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS,
11955                                     const ExprResult &XorRHS,
11956                                     const SourceLocation Loc) {
11957   // Do not diagnose macros.
11958   if (Loc.isMacroID())
11959     return;
11960 
11961   bool Negative = false;
11962   bool ExplicitPlus = false;
11963   const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get());
11964   const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get());
11965 
11966   if (!LHSInt)
11967     return;
11968   if (!RHSInt) {
11969     // Check negative literals.
11970     if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) {
11971       UnaryOperatorKind Opc = UO->getOpcode();
11972       if (Opc != UO_Minus && Opc != UO_Plus)
11973         return;
11974       RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr());
11975       if (!RHSInt)
11976         return;
11977       Negative = (Opc == UO_Minus);
11978       ExplicitPlus = !Negative;
11979     } else {
11980       return;
11981     }
11982   }
11983 
11984   const llvm::APInt &LeftSideValue = LHSInt->getValue();
11985   llvm::APInt RightSideValue = RHSInt->getValue();
11986   if (LeftSideValue != 2 && LeftSideValue != 10)
11987     return;
11988 
11989   if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth())
11990     return;
11991 
11992   CharSourceRange ExprRange = CharSourceRange::getCharRange(
11993       LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation()));
11994   llvm::StringRef ExprStr =
11995       Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts());
11996 
11997   CharSourceRange XorRange =
11998       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
11999   llvm::StringRef XorStr =
12000       Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts());
12001   // Do not diagnose if xor keyword/macro is used.
12002   if (XorStr == "xor")
12003     return;
12004 
12005   std::string LHSStr = std::string(Lexer::getSourceText(
12006       CharSourceRange::getTokenRange(LHSInt->getSourceRange()),
12007       S.getSourceManager(), S.getLangOpts()));
12008   std::string RHSStr = std::string(Lexer::getSourceText(
12009       CharSourceRange::getTokenRange(RHSInt->getSourceRange()),
12010       S.getSourceManager(), S.getLangOpts()));
12011 
12012   if (Negative) {
12013     RightSideValue = -RightSideValue;
12014     RHSStr = "-" + RHSStr;
12015   } else if (ExplicitPlus) {
12016     RHSStr = "+" + RHSStr;
12017   }
12018 
12019   StringRef LHSStrRef = LHSStr;
12020   StringRef RHSStrRef = RHSStr;
12021   // Do not diagnose literals with digit separators, binary, hexadecimal, octal
12022   // literals.
12023   if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") ||
12024       RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") ||
12025       LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") ||
12026       RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") ||
12027       (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) ||
12028       (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) ||
12029       LHSStrRef.find('\'') != StringRef::npos ||
12030       RHSStrRef.find('\'') != StringRef::npos)
12031     return;
12032 
12033   bool SuggestXor = S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor");
12034   const llvm::APInt XorValue = LeftSideValue ^ RightSideValue;
12035   int64_t RightSideIntValue = RightSideValue.getSExtValue();
12036   if (LeftSideValue == 2 && RightSideIntValue >= 0) {
12037     std::string SuggestedExpr = "1 << " + RHSStr;
12038     bool Overflow = false;
12039     llvm::APInt One = (LeftSideValue - 1);
12040     llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow);
12041     if (Overflow) {
12042       if (RightSideIntValue < 64)
12043         S.Diag(Loc, diag::warn_xor_used_as_pow_base)
12044             << ExprStr << XorValue.toString(10, true) << ("1LL << " + RHSStr)
12045             << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr);
12046       else if (RightSideIntValue == 64)
12047         S.Diag(Loc, diag::warn_xor_used_as_pow) << ExprStr << XorValue.toString(10, true);
12048       else
12049         return;
12050     } else {
12051       S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra)
12052           << ExprStr << XorValue.toString(10, true) << SuggestedExpr
12053           << PowValue.toString(10, true)
12054           << FixItHint::CreateReplacement(
12055                  ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr);
12056     }
12057 
12058     S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0x2 ^ " + RHSStr) << SuggestXor;
12059   } else if (LeftSideValue == 10) {
12060     std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue);
12061     S.Diag(Loc, diag::warn_xor_used_as_pow_base)
12062         << ExprStr << XorValue.toString(10, true) << SuggestedValue
12063         << FixItHint::CreateReplacement(ExprRange, SuggestedValue);
12064     S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0xA ^ " + RHSStr) << SuggestXor;
12065   }
12066 }
12067 
12068 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
12069                                           SourceLocation Loc) {
12070   // Ensure that either both operands are of the same vector type, or
12071   // one operand is of a vector type and the other is of its element type.
12072   QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
12073                                        /*AllowBothBool*/true,
12074                                        /*AllowBoolConversions*/false);
12075   if (vType.isNull())
12076     return InvalidOperands(Loc, LHS, RHS);
12077   if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
12078       !getLangOpts().OpenCLCPlusPlus && vType->hasFloatingRepresentation())
12079     return InvalidOperands(Loc, LHS, RHS);
12080   // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
12081   //        usage of the logical operators && and || with vectors in C. This
12082   //        check could be notionally dropped.
12083   if (!getLangOpts().CPlusPlus &&
12084       !(isa<ExtVectorType>(vType->getAs<VectorType>())))
12085     return InvalidLogicalVectorOperands(Loc, LHS, RHS);
12086 
12087   return GetSignedVectorType(LHS.get()->getType());
12088 }
12089 
12090 QualType Sema::CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS,
12091                                               SourceLocation Loc,
12092                                               bool IsCompAssign) {
12093   if (!IsCompAssign) {
12094     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
12095     if (LHS.isInvalid())
12096       return QualType();
12097   }
12098   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
12099   if (RHS.isInvalid())
12100     return QualType();
12101 
12102   // For conversion purposes, we ignore any qualifiers.
12103   // For example, "const float" and "float" are equivalent.
12104   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
12105   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
12106 
12107   const MatrixType *LHSMatType = LHSType->getAs<MatrixType>();
12108   const MatrixType *RHSMatType = RHSType->getAs<MatrixType>();
12109   assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
12110 
12111   if (Context.hasSameType(LHSType, RHSType))
12112     return LHSType;
12113 
12114   // Type conversion may change LHS/RHS. Keep copies to the original results, in
12115   // case we have to return InvalidOperands.
12116   ExprResult OriginalLHS = LHS;
12117   ExprResult OriginalRHS = RHS;
12118   if (LHSMatType && !RHSMatType) {
12119     RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType());
12120     if (!RHS.isInvalid())
12121       return LHSType;
12122 
12123     return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
12124   }
12125 
12126   if (!LHSMatType && RHSMatType) {
12127     LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType());
12128     if (!LHS.isInvalid())
12129       return RHSType;
12130     return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
12131   }
12132 
12133   return InvalidOperands(Loc, LHS, RHS);
12134 }
12135 
12136 QualType Sema::CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS,
12137                                            SourceLocation Loc,
12138                                            bool IsCompAssign) {
12139   if (!IsCompAssign) {
12140     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
12141     if (LHS.isInvalid())
12142       return QualType();
12143   }
12144   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
12145   if (RHS.isInvalid())
12146     return QualType();
12147 
12148   auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>();
12149   auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>();
12150   assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
12151 
12152   if (LHSMatType && RHSMatType) {
12153     if (LHSMatType->getNumColumns() != RHSMatType->getNumRows())
12154       return InvalidOperands(Loc, LHS, RHS);
12155 
12156     if (!Context.hasSameType(LHSMatType->getElementType(),
12157                              RHSMatType->getElementType()))
12158       return InvalidOperands(Loc, LHS, RHS);
12159 
12160     return Context.getConstantMatrixType(LHSMatType->getElementType(),
12161                                          LHSMatType->getNumRows(),
12162                                          RHSMatType->getNumColumns());
12163   }
12164   return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
12165 }
12166 
12167 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
12168                                            SourceLocation Loc,
12169                                            BinaryOperatorKind Opc) {
12170   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
12171 
12172   bool IsCompAssign =
12173       Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
12174 
12175   if (LHS.get()->getType()->isVectorType() ||
12176       RHS.get()->getType()->isVectorType()) {
12177     if (LHS.get()->getType()->hasIntegerRepresentation() &&
12178         RHS.get()->getType()->hasIntegerRepresentation())
12179       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
12180                         /*AllowBothBool*/true,
12181                         /*AllowBoolConversions*/getLangOpts().ZVector);
12182     return InvalidOperands(Loc, LHS, RHS);
12183   }
12184 
12185   if (Opc == BO_And)
12186     diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
12187 
12188   if (LHS.get()->getType()->hasFloatingRepresentation() ||
12189       RHS.get()->getType()->hasFloatingRepresentation())
12190     return InvalidOperands(Loc, LHS, RHS);
12191 
12192   ExprResult LHSResult = LHS, RHSResult = RHS;
12193   QualType compType = UsualArithmeticConversions(
12194       LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp);
12195   if (LHSResult.isInvalid() || RHSResult.isInvalid())
12196     return QualType();
12197   LHS = LHSResult.get();
12198   RHS = RHSResult.get();
12199 
12200   if (Opc == BO_Xor)
12201     diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc);
12202 
12203   if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
12204     return compType;
12205   return InvalidOperands(Loc, LHS, RHS);
12206 }
12207 
12208 // C99 6.5.[13,14]
12209 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
12210                                            SourceLocation Loc,
12211                                            BinaryOperatorKind Opc) {
12212   // Check vector operands differently.
12213   if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
12214     return CheckVectorLogicalOperands(LHS, RHS, Loc);
12215 
12216   bool EnumConstantInBoolContext = false;
12217   for (const ExprResult &HS : {LHS, RHS}) {
12218     if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) {
12219       const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl());
12220       if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1)
12221         EnumConstantInBoolContext = true;
12222     }
12223   }
12224 
12225   if (EnumConstantInBoolContext)
12226     Diag(Loc, diag::warn_enum_constant_in_bool_context);
12227 
12228   // Diagnose cases where the user write a logical and/or but probably meant a
12229   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
12230   // is a constant.
12231   if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() &&
12232       !LHS.get()->getType()->isBooleanType() &&
12233       RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
12234       // Don't warn in macros or template instantiations.
12235       !Loc.isMacroID() && !inTemplateInstantiation()) {
12236     // If the RHS can be constant folded, and if it constant folds to something
12237     // that isn't 0 or 1 (which indicate a potential logical operation that
12238     // happened to fold to true/false) then warn.
12239     // Parens on the RHS are ignored.
12240     Expr::EvalResult EVResult;
12241     if (RHS.get()->EvaluateAsInt(EVResult, Context)) {
12242       llvm::APSInt Result = EVResult.Val.getInt();
12243       if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
12244            !RHS.get()->getExprLoc().isMacroID()) ||
12245           (Result != 0 && Result != 1)) {
12246         Diag(Loc, diag::warn_logical_instead_of_bitwise)
12247           << RHS.get()->getSourceRange()
12248           << (Opc == BO_LAnd ? "&&" : "||");
12249         // Suggest replacing the logical operator with the bitwise version
12250         Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
12251             << (Opc == BO_LAnd ? "&" : "|")
12252             << FixItHint::CreateReplacement(SourceRange(
12253                                                  Loc, getLocForEndOfToken(Loc)),
12254                                             Opc == BO_LAnd ? "&" : "|");
12255         if (Opc == BO_LAnd)
12256           // Suggest replacing "Foo() && kNonZero" with "Foo()"
12257           Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
12258               << FixItHint::CreateRemoval(
12259                      SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()),
12260                                  RHS.get()->getEndLoc()));
12261       }
12262     }
12263   }
12264 
12265   if (!Context.getLangOpts().CPlusPlus) {
12266     // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
12267     // not operate on the built-in scalar and vector float types.
12268     if (Context.getLangOpts().OpenCL &&
12269         Context.getLangOpts().OpenCLVersion < 120) {
12270       if (LHS.get()->getType()->isFloatingType() ||
12271           RHS.get()->getType()->isFloatingType())
12272         return InvalidOperands(Loc, LHS, RHS);
12273     }
12274 
12275     LHS = UsualUnaryConversions(LHS.get());
12276     if (LHS.isInvalid())
12277       return QualType();
12278 
12279     RHS = UsualUnaryConversions(RHS.get());
12280     if (RHS.isInvalid())
12281       return QualType();
12282 
12283     if (!LHS.get()->getType()->isScalarType() ||
12284         !RHS.get()->getType()->isScalarType())
12285       return InvalidOperands(Loc, LHS, RHS);
12286 
12287     return Context.IntTy;
12288   }
12289 
12290   // The following is safe because we only use this method for
12291   // non-overloadable operands.
12292 
12293   // C++ [expr.log.and]p1
12294   // C++ [expr.log.or]p1
12295   // The operands are both contextually converted to type bool.
12296   ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
12297   if (LHSRes.isInvalid())
12298     return InvalidOperands(Loc, LHS, RHS);
12299   LHS = LHSRes;
12300 
12301   ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
12302   if (RHSRes.isInvalid())
12303     return InvalidOperands(Loc, LHS, RHS);
12304   RHS = RHSRes;
12305 
12306   // C++ [expr.log.and]p2
12307   // C++ [expr.log.or]p2
12308   // The result is a bool.
12309   return Context.BoolTy;
12310 }
12311 
12312 static bool IsReadonlyMessage(Expr *E, Sema &S) {
12313   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
12314   if (!ME) return false;
12315   if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
12316   ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
12317       ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
12318   if (!Base) return false;
12319   return Base->getMethodDecl() != nullptr;
12320 }
12321 
12322 /// Is the given expression (which must be 'const') a reference to a
12323 /// variable which was originally non-const, but which has become
12324 /// 'const' due to being captured within a block?
12325 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
12326 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
12327   assert(E->isLValue() && E->getType().isConstQualified());
12328   E = E->IgnoreParens();
12329 
12330   // Must be a reference to a declaration from an enclosing scope.
12331   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
12332   if (!DRE) return NCCK_None;
12333   if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
12334 
12335   // The declaration must be a variable which is not declared 'const'.
12336   VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
12337   if (!var) return NCCK_None;
12338   if (var->getType().isConstQualified()) return NCCK_None;
12339   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
12340 
12341   // Decide whether the first capture was for a block or a lambda.
12342   DeclContext *DC = S.CurContext, *Prev = nullptr;
12343   // Decide whether the first capture was for a block or a lambda.
12344   while (DC) {
12345     // For init-capture, it is possible that the variable belongs to the
12346     // template pattern of the current context.
12347     if (auto *FD = dyn_cast<FunctionDecl>(DC))
12348       if (var->isInitCapture() &&
12349           FD->getTemplateInstantiationPattern() == var->getDeclContext())
12350         break;
12351     if (DC == var->getDeclContext())
12352       break;
12353     Prev = DC;
12354     DC = DC->getParent();
12355   }
12356   // Unless we have an init-capture, we've gone one step too far.
12357   if (!var->isInitCapture())
12358     DC = Prev;
12359   return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
12360 }
12361 
12362 static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
12363   Ty = Ty.getNonReferenceType();
12364   if (IsDereference && Ty->isPointerType())
12365     Ty = Ty->getPointeeType();
12366   return !Ty.isConstQualified();
12367 }
12368 
12369 // Update err_typecheck_assign_const and note_typecheck_assign_const
12370 // when this enum is changed.
12371 enum {
12372   ConstFunction,
12373   ConstVariable,
12374   ConstMember,
12375   ConstMethod,
12376   NestedConstMember,
12377   ConstUnknown,  // Keep as last element
12378 };
12379 
12380 /// Emit the "read-only variable not assignable" error and print notes to give
12381 /// more information about why the variable is not assignable, such as pointing
12382 /// to the declaration of a const variable, showing that a method is const, or
12383 /// that the function is returning a const reference.
12384 static void DiagnoseConstAssignment(Sema &S, const Expr *E,
12385                                     SourceLocation Loc) {
12386   SourceRange ExprRange = E->getSourceRange();
12387 
12388   // Only emit one error on the first const found.  All other consts will emit
12389   // a note to the error.
12390   bool DiagnosticEmitted = false;
12391 
12392   // Track if the current expression is the result of a dereference, and if the
12393   // next checked expression is the result of a dereference.
12394   bool IsDereference = false;
12395   bool NextIsDereference = false;
12396 
12397   // Loop to process MemberExpr chains.
12398   while (true) {
12399     IsDereference = NextIsDereference;
12400 
12401     E = E->IgnoreImplicit()->IgnoreParenImpCasts();
12402     if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
12403       NextIsDereference = ME->isArrow();
12404       const ValueDecl *VD = ME->getMemberDecl();
12405       if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
12406         // Mutable fields can be modified even if the class is const.
12407         if (Field->isMutable()) {
12408           assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
12409           break;
12410         }
12411 
12412         if (!IsTypeModifiable(Field->getType(), IsDereference)) {
12413           if (!DiagnosticEmitted) {
12414             S.Diag(Loc, diag::err_typecheck_assign_const)
12415                 << ExprRange << ConstMember << false /*static*/ << Field
12416                 << Field->getType();
12417             DiagnosticEmitted = true;
12418           }
12419           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
12420               << ConstMember << false /*static*/ << Field << Field->getType()
12421               << Field->getSourceRange();
12422         }
12423         E = ME->getBase();
12424         continue;
12425       } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
12426         if (VDecl->getType().isConstQualified()) {
12427           if (!DiagnosticEmitted) {
12428             S.Diag(Loc, diag::err_typecheck_assign_const)
12429                 << ExprRange << ConstMember << true /*static*/ << VDecl
12430                 << VDecl->getType();
12431             DiagnosticEmitted = true;
12432           }
12433           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
12434               << ConstMember << true /*static*/ << VDecl << VDecl->getType()
12435               << VDecl->getSourceRange();
12436         }
12437         // Static fields do not inherit constness from parents.
12438         break;
12439       }
12440       break; // End MemberExpr
12441     } else if (const ArraySubscriptExpr *ASE =
12442                    dyn_cast<ArraySubscriptExpr>(E)) {
12443       E = ASE->getBase()->IgnoreParenImpCasts();
12444       continue;
12445     } else if (const ExtVectorElementExpr *EVE =
12446                    dyn_cast<ExtVectorElementExpr>(E)) {
12447       E = EVE->getBase()->IgnoreParenImpCasts();
12448       continue;
12449     }
12450     break;
12451   }
12452 
12453   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
12454     // Function calls
12455     const FunctionDecl *FD = CE->getDirectCallee();
12456     if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
12457       if (!DiagnosticEmitted) {
12458         S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
12459                                                       << ConstFunction << FD;
12460         DiagnosticEmitted = true;
12461       }
12462       S.Diag(FD->getReturnTypeSourceRange().getBegin(),
12463              diag::note_typecheck_assign_const)
12464           << ConstFunction << FD << FD->getReturnType()
12465           << FD->getReturnTypeSourceRange();
12466     }
12467   } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
12468     // Point to variable declaration.
12469     if (const ValueDecl *VD = DRE->getDecl()) {
12470       if (!IsTypeModifiable(VD->getType(), IsDereference)) {
12471         if (!DiagnosticEmitted) {
12472           S.Diag(Loc, diag::err_typecheck_assign_const)
12473               << ExprRange << ConstVariable << VD << VD->getType();
12474           DiagnosticEmitted = true;
12475         }
12476         S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
12477             << ConstVariable << VD << VD->getType() << VD->getSourceRange();
12478       }
12479     }
12480   } else if (isa<CXXThisExpr>(E)) {
12481     if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
12482       if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
12483         if (MD->isConst()) {
12484           if (!DiagnosticEmitted) {
12485             S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
12486                                                           << ConstMethod << MD;
12487             DiagnosticEmitted = true;
12488           }
12489           S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
12490               << ConstMethod << MD << MD->getSourceRange();
12491         }
12492       }
12493     }
12494   }
12495 
12496   if (DiagnosticEmitted)
12497     return;
12498 
12499   // Can't determine a more specific message, so display the generic error.
12500   S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
12501 }
12502 
12503 enum OriginalExprKind {
12504   OEK_Variable,
12505   OEK_Member,
12506   OEK_LValue
12507 };
12508 
12509 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD,
12510                                          const RecordType *Ty,
12511                                          SourceLocation Loc, SourceRange Range,
12512                                          OriginalExprKind OEK,
12513                                          bool &DiagnosticEmitted) {
12514   std::vector<const RecordType *> RecordTypeList;
12515   RecordTypeList.push_back(Ty);
12516   unsigned NextToCheckIndex = 0;
12517   // We walk the record hierarchy breadth-first to ensure that we print
12518   // diagnostics in field nesting order.
12519   while (RecordTypeList.size() > NextToCheckIndex) {
12520     bool IsNested = NextToCheckIndex > 0;
12521     for (const FieldDecl *Field :
12522          RecordTypeList[NextToCheckIndex]->getDecl()->fields()) {
12523       // First, check every field for constness.
12524       QualType FieldTy = Field->getType();
12525       if (FieldTy.isConstQualified()) {
12526         if (!DiagnosticEmitted) {
12527           S.Diag(Loc, diag::err_typecheck_assign_const)
12528               << Range << NestedConstMember << OEK << VD
12529               << IsNested << Field;
12530           DiagnosticEmitted = true;
12531         }
12532         S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
12533             << NestedConstMember << IsNested << Field
12534             << FieldTy << Field->getSourceRange();
12535       }
12536 
12537       // Then we append it to the list to check next in order.
12538       FieldTy = FieldTy.getCanonicalType();
12539       if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) {
12540         if (llvm::find(RecordTypeList, FieldRecTy) == RecordTypeList.end())
12541           RecordTypeList.push_back(FieldRecTy);
12542       }
12543     }
12544     ++NextToCheckIndex;
12545   }
12546 }
12547 
12548 /// Emit an error for the case where a record we are trying to assign to has a
12549 /// const-qualified field somewhere in its hierarchy.
12550 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
12551                                          SourceLocation Loc) {
12552   QualType Ty = E->getType();
12553   assert(Ty->isRecordType() && "lvalue was not record?");
12554   SourceRange Range = E->getSourceRange();
12555   const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>();
12556   bool DiagEmitted = false;
12557 
12558   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
12559     DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
12560             Range, OEK_Member, DiagEmitted);
12561   else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
12562     DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
12563             Range, OEK_Variable, DiagEmitted);
12564   else
12565     DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
12566             Range, OEK_LValue, DiagEmitted);
12567   if (!DiagEmitted)
12568     DiagnoseConstAssignment(S, E, Loc);
12569 }
12570 
12571 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
12572 /// emit an error and return true.  If so, return false.
12573 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
12574   assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
12575 
12576   S.CheckShadowingDeclModification(E, Loc);
12577 
12578   SourceLocation OrigLoc = Loc;
12579   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
12580                                                               &Loc);
12581   if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
12582     IsLV = Expr::MLV_InvalidMessageExpression;
12583   if (IsLV == Expr::MLV_Valid)
12584     return false;
12585 
12586   unsigned DiagID = 0;
12587   bool NeedType = false;
12588   switch (IsLV) { // C99 6.5.16p2
12589   case Expr::MLV_ConstQualified:
12590     // Use a specialized diagnostic when we're assigning to an object
12591     // from an enclosing function or block.
12592     if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
12593       if (NCCK == NCCK_Block)
12594         DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
12595       else
12596         DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
12597       break;
12598     }
12599 
12600     // In ARC, use some specialized diagnostics for occasions where we
12601     // infer 'const'.  These are always pseudo-strong variables.
12602     if (S.getLangOpts().ObjCAutoRefCount) {
12603       DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
12604       if (declRef && isa<VarDecl>(declRef->getDecl())) {
12605         VarDecl *var = cast<VarDecl>(declRef->getDecl());
12606 
12607         // Use the normal diagnostic if it's pseudo-__strong but the
12608         // user actually wrote 'const'.
12609         if (var->isARCPseudoStrong() &&
12610             (!var->getTypeSourceInfo() ||
12611              !var->getTypeSourceInfo()->getType().isConstQualified())) {
12612           // There are three pseudo-strong cases:
12613           //  - self
12614           ObjCMethodDecl *method = S.getCurMethodDecl();
12615           if (method && var == method->getSelfDecl()) {
12616             DiagID = method->isClassMethod()
12617               ? diag::err_typecheck_arc_assign_self_class_method
12618               : diag::err_typecheck_arc_assign_self;
12619 
12620           //  - Objective-C externally_retained attribute.
12621           } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
12622                      isa<ParmVarDecl>(var)) {
12623             DiagID = diag::err_typecheck_arc_assign_externally_retained;
12624 
12625           //  - fast enumeration variables
12626           } else {
12627             DiagID = diag::err_typecheck_arr_assign_enumeration;
12628           }
12629 
12630           SourceRange Assign;
12631           if (Loc != OrigLoc)
12632             Assign = SourceRange(OrigLoc, OrigLoc);
12633           S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
12634           // We need to preserve the AST regardless, so migration tool
12635           // can do its job.
12636           return false;
12637         }
12638       }
12639     }
12640 
12641     // If none of the special cases above are triggered, then this is a
12642     // simple const assignment.
12643     if (DiagID == 0) {
12644       DiagnoseConstAssignment(S, E, Loc);
12645       return true;
12646     }
12647 
12648     break;
12649   case Expr::MLV_ConstAddrSpace:
12650     DiagnoseConstAssignment(S, E, Loc);
12651     return true;
12652   case Expr::MLV_ConstQualifiedField:
12653     DiagnoseRecursiveConstFields(S, E, Loc);
12654     return true;
12655   case Expr::MLV_ArrayType:
12656   case Expr::MLV_ArrayTemporary:
12657     DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
12658     NeedType = true;
12659     break;
12660   case Expr::MLV_NotObjectType:
12661     DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
12662     NeedType = true;
12663     break;
12664   case Expr::MLV_LValueCast:
12665     DiagID = diag::err_typecheck_lvalue_casts_not_supported;
12666     break;
12667   case Expr::MLV_Valid:
12668     llvm_unreachable("did not take early return for MLV_Valid");
12669   case Expr::MLV_InvalidExpression:
12670   case Expr::MLV_MemberFunction:
12671   case Expr::MLV_ClassTemporary:
12672     DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
12673     break;
12674   case Expr::MLV_IncompleteType:
12675   case Expr::MLV_IncompleteVoidType:
12676     return S.RequireCompleteType(Loc, E->getType(),
12677              diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
12678   case Expr::MLV_DuplicateVectorComponents:
12679     DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
12680     break;
12681   case Expr::MLV_NoSetterProperty:
12682     llvm_unreachable("readonly properties should be processed differently");
12683   case Expr::MLV_InvalidMessageExpression:
12684     DiagID = diag::err_readonly_message_assignment;
12685     break;
12686   case Expr::MLV_SubObjCPropertySetting:
12687     DiagID = diag::err_no_subobject_property_setting;
12688     break;
12689   }
12690 
12691   SourceRange Assign;
12692   if (Loc != OrigLoc)
12693     Assign = SourceRange(OrigLoc, OrigLoc);
12694   if (NeedType)
12695     S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
12696   else
12697     S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
12698   return true;
12699 }
12700 
12701 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
12702                                          SourceLocation Loc,
12703                                          Sema &Sema) {
12704   if (Sema.inTemplateInstantiation())
12705     return;
12706   if (Sema.isUnevaluatedContext())
12707     return;
12708   if (Loc.isInvalid() || Loc.isMacroID())
12709     return;
12710   if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
12711     return;
12712 
12713   // C / C++ fields
12714   MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
12715   MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
12716   if (ML && MR) {
12717     if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
12718       return;
12719     const ValueDecl *LHSDecl =
12720         cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl());
12721     const ValueDecl *RHSDecl =
12722         cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl());
12723     if (LHSDecl != RHSDecl)
12724       return;
12725     if (LHSDecl->getType().isVolatileQualified())
12726       return;
12727     if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
12728       if (RefTy->getPointeeType().isVolatileQualified())
12729         return;
12730 
12731     Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
12732   }
12733 
12734   // Objective-C instance variables
12735   ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
12736   ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
12737   if (OL && OR && OL->getDecl() == OR->getDecl()) {
12738     DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
12739     DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
12740     if (RL && RR && RL->getDecl() == RR->getDecl())
12741       Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
12742   }
12743 }
12744 
12745 // C99 6.5.16.1
12746 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
12747                                        SourceLocation Loc,
12748                                        QualType CompoundType) {
12749   assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
12750 
12751   // Verify that LHS is a modifiable lvalue, and emit error if not.
12752   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
12753     return QualType();
12754 
12755   QualType LHSType = LHSExpr->getType();
12756   QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
12757                                              CompoundType;
12758   // OpenCL v1.2 s6.1.1.1 p2:
12759   // The half data type can only be used to declare a pointer to a buffer that
12760   // contains half values
12761   if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
12762     LHSType->isHalfType()) {
12763     Diag(Loc, diag::err_opencl_half_load_store) << 1
12764         << LHSType.getUnqualifiedType();
12765     return QualType();
12766   }
12767 
12768   AssignConvertType ConvTy;
12769   if (CompoundType.isNull()) {
12770     Expr *RHSCheck = RHS.get();
12771 
12772     CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
12773 
12774     QualType LHSTy(LHSType);
12775     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
12776     if (RHS.isInvalid())
12777       return QualType();
12778     // Special case of NSObject attributes on c-style pointer types.
12779     if (ConvTy == IncompatiblePointer &&
12780         ((Context.isObjCNSObjectType(LHSType) &&
12781           RHSType->isObjCObjectPointerType()) ||
12782          (Context.isObjCNSObjectType(RHSType) &&
12783           LHSType->isObjCObjectPointerType())))
12784       ConvTy = Compatible;
12785 
12786     if (ConvTy == Compatible &&
12787         LHSType->isObjCObjectType())
12788         Diag(Loc, diag::err_objc_object_assignment)
12789           << LHSType;
12790 
12791     // If the RHS is a unary plus or minus, check to see if they = and + are
12792     // right next to each other.  If so, the user may have typo'd "x =+ 4"
12793     // instead of "x += 4".
12794     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
12795       RHSCheck = ICE->getSubExpr();
12796     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
12797       if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
12798           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
12799           // Only if the two operators are exactly adjacent.
12800           Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
12801           // And there is a space or other character before the subexpr of the
12802           // unary +/-.  We don't want to warn on "x=-1".
12803           Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() &&
12804           UO->getSubExpr()->getBeginLoc().isFileID()) {
12805         Diag(Loc, diag::warn_not_compound_assign)
12806           << (UO->getOpcode() == UO_Plus ? "+" : "-")
12807           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
12808       }
12809     }
12810 
12811     if (ConvTy == Compatible) {
12812       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
12813         // Warn about retain cycles where a block captures the LHS, but
12814         // not if the LHS is a simple variable into which the block is
12815         // being stored...unless that variable can be captured by reference!
12816         const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
12817         const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
12818         if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
12819           checkRetainCycles(LHSExpr, RHS.get());
12820       }
12821 
12822       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
12823           LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
12824         // It is safe to assign a weak reference into a strong variable.
12825         // Although this code can still have problems:
12826         //   id x = self.weakProp;
12827         //   id y = self.weakProp;
12828         // we do not warn to warn spuriously when 'x' and 'y' are on separate
12829         // paths through the function. This should be revisited if
12830         // -Wrepeated-use-of-weak is made flow-sensitive.
12831         // For ObjCWeak only, we do not warn if the assign is to a non-weak
12832         // variable, which will be valid for the current autorelease scope.
12833         if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
12834                              RHS.get()->getBeginLoc()))
12835           getCurFunction()->markSafeWeakUse(RHS.get());
12836 
12837       } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
12838         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
12839       }
12840     }
12841   } else {
12842     // Compound assignment "x += y"
12843     ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
12844   }
12845 
12846   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
12847                                RHS.get(), AA_Assigning))
12848     return QualType();
12849 
12850   CheckForNullPointerDereference(*this, LHSExpr);
12851 
12852   if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) {
12853     if (CompoundType.isNull()) {
12854       // C++2a [expr.ass]p5:
12855       //   A simple-assignment whose left operand is of a volatile-qualified
12856       //   type is deprecated unless the assignment is either a discarded-value
12857       //   expression or an unevaluated operand
12858       ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr);
12859     } else {
12860       // C++2a [expr.ass]p6:
12861       //   [Compound-assignment] expressions are deprecated if E1 has
12862       //   volatile-qualified type
12863       Diag(Loc, diag::warn_deprecated_compound_assign_volatile) << LHSType;
12864     }
12865   }
12866 
12867   // C99 6.5.16p3: The type of an assignment expression is the type of the
12868   // left operand unless the left operand has qualified type, in which case
12869   // it is the unqualified version of the type of the left operand.
12870   // C99 6.5.16.1p2: In simple assignment, the value of the right operand
12871   // is converted to the type of the assignment expression (above).
12872   // C++ 5.17p1: the type of the assignment expression is that of its left
12873   // operand.
12874   return (getLangOpts().CPlusPlus
12875           ? LHSType : LHSType.getUnqualifiedType());
12876 }
12877 
12878 // Only ignore explicit casts to void.
12879 static bool IgnoreCommaOperand(const Expr *E) {
12880   E = E->IgnoreParens();
12881 
12882   if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
12883     if (CE->getCastKind() == CK_ToVoid) {
12884       return true;
12885     }
12886 
12887     // static_cast<void> on a dependent type will not show up as CK_ToVoid.
12888     if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
12889         CE->getSubExpr()->getType()->isDependentType()) {
12890       return true;
12891     }
12892   }
12893 
12894   return false;
12895 }
12896 
12897 // Look for instances where it is likely the comma operator is confused with
12898 // another operator.  There is a whitelist of acceptable expressions for the
12899 // left hand side of the comma operator, otherwise emit a warning.
12900 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
12901   // No warnings in macros
12902   if (Loc.isMacroID())
12903     return;
12904 
12905   // Don't warn in template instantiations.
12906   if (inTemplateInstantiation())
12907     return;
12908 
12909   // Scope isn't fine-grained enough to whitelist the specific cases, so
12910   // instead, skip more than needed, then call back into here with the
12911   // CommaVisitor in SemaStmt.cpp.
12912   // The whitelisted locations are the initialization and increment portions
12913   // of a for loop.  The additional checks are on the condition of
12914   // if statements, do/while loops, and for loops.
12915   // Differences in scope flags for C89 mode requires the extra logic.
12916   const unsigned ForIncrementFlags =
12917       getLangOpts().C99 || getLangOpts().CPlusPlus
12918           ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope
12919           : Scope::ContinueScope | Scope::BreakScope;
12920   const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
12921   const unsigned ScopeFlags = getCurScope()->getFlags();
12922   if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
12923       (ScopeFlags & ForInitFlags) == ForInitFlags)
12924     return;
12925 
12926   // If there are multiple comma operators used together, get the RHS of the
12927   // of the comma operator as the LHS.
12928   while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
12929     if (BO->getOpcode() != BO_Comma)
12930       break;
12931     LHS = BO->getRHS();
12932   }
12933 
12934   // Only allow some expressions on LHS to not warn.
12935   if (IgnoreCommaOperand(LHS))
12936     return;
12937 
12938   Diag(Loc, diag::warn_comma_operator);
12939   Diag(LHS->getBeginLoc(), diag::note_cast_to_void)
12940       << LHS->getSourceRange()
12941       << FixItHint::CreateInsertion(LHS->getBeginLoc(),
12942                                     LangOpts.CPlusPlus ? "static_cast<void>("
12943                                                        : "(void)(")
12944       << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()),
12945                                     ")");
12946 }
12947 
12948 // C99 6.5.17
12949 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
12950                                    SourceLocation Loc) {
12951   LHS = S.CheckPlaceholderExpr(LHS.get());
12952   RHS = S.CheckPlaceholderExpr(RHS.get());
12953   if (LHS.isInvalid() || RHS.isInvalid())
12954     return QualType();
12955 
12956   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
12957   // operands, but not unary promotions.
12958   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
12959 
12960   // So we treat the LHS as a ignored value, and in C++ we allow the
12961   // containing site to determine what should be done with the RHS.
12962   LHS = S.IgnoredValueConversions(LHS.get());
12963   if (LHS.isInvalid())
12964     return QualType();
12965 
12966   S.DiagnoseUnusedExprResult(LHS.get());
12967 
12968   if (!S.getLangOpts().CPlusPlus) {
12969     RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
12970     if (RHS.isInvalid())
12971       return QualType();
12972     if (!RHS.get()->getType()->isVoidType())
12973       S.RequireCompleteType(Loc, RHS.get()->getType(),
12974                             diag::err_incomplete_type);
12975   }
12976 
12977   if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
12978     S.DiagnoseCommaOperator(LHS.get(), Loc);
12979 
12980   return RHS.get()->getType();
12981 }
12982 
12983 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
12984 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
12985 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
12986                                                ExprValueKind &VK,
12987                                                ExprObjectKind &OK,
12988                                                SourceLocation OpLoc,
12989                                                bool IsInc, bool IsPrefix) {
12990   if (Op->isTypeDependent())
12991     return S.Context.DependentTy;
12992 
12993   QualType ResType = Op->getType();
12994   // Atomic types can be used for increment / decrement where the non-atomic
12995   // versions can, so ignore the _Atomic() specifier for the purpose of
12996   // checking.
12997   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
12998     ResType = ResAtomicType->getValueType();
12999 
13000   assert(!ResType.isNull() && "no type for increment/decrement expression");
13001 
13002   if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
13003     // Decrement of bool is not allowed.
13004     if (!IsInc) {
13005       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
13006       return QualType();
13007     }
13008     // Increment of bool sets it to true, but is deprecated.
13009     S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
13010                                               : diag::warn_increment_bool)
13011       << Op->getSourceRange();
13012   } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
13013     // Error on enum increments and decrements in C++ mode
13014     S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
13015     return QualType();
13016   } else if (ResType->isRealType()) {
13017     // OK!
13018   } else if (ResType->isPointerType()) {
13019     // C99 6.5.2.4p2, 6.5.6p2
13020     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
13021       return QualType();
13022   } else if (ResType->isObjCObjectPointerType()) {
13023     // On modern runtimes, ObjC pointer arithmetic is forbidden.
13024     // Otherwise, we just need a complete type.
13025     if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
13026         checkArithmeticOnObjCPointer(S, OpLoc, Op))
13027       return QualType();
13028   } else if (ResType->isAnyComplexType()) {
13029     // C99 does not support ++/-- on complex types, we allow as an extension.
13030     S.Diag(OpLoc, diag::ext_integer_increment_complex)
13031       << ResType << Op->getSourceRange();
13032   } else if (ResType->isPlaceholderType()) {
13033     ExprResult PR = S.CheckPlaceholderExpr(Op);
13034     if (PR.isInvalid()) return QualType();
13035     return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
13036                                           IsInc, IsPrefix);
13037   } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
13038     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
13039   } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
13040              (ResType->castAs<VectorType>()->getVectorKind() !=
13041               VectorType::AltiVecBool)) {
13042     // The z vector extensions allow ++ and -- for non-bool vectors.
13043   } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
13044             ResType->castAs<VectorType>()->getElementType()->isIntegerType()) {
13045     // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
13046   } else {
13047     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
13048       << ResType << int(IsInc) << Op->getSourceRange();
13049     return QualType();
13050   }
13051   // At this point, we know we have a real, complex or pointer type.
13052   // Now make sure the operand is a modifiable lvalue.
13053   if (CheckForModifiableLvalue(Op, OpLoc, S))
13054     return QualType();
13055   if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) {
13056     // C++2a [expr.pre.inc]p1, [expr.post.inc]p1:
13057     //   An operand with volatile-qualified type is deprecated
13058     S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile)
13059         << IsInc << ResType;
13060   }
13061   // In C++, a prefix increment is the same type as the operand. Otherwise
13062   // (in C or with postfix), the increment is the unqualified type of the
13063   // operand.
13064   if (IsPrefix && S.getLangOpts().CPlusPlus) {
13065     VK = VK_LValue;
13066     OK = Op->getObjectKind();
13067     return ResType;
13068   } else {
13069     VK = VK_RValue;
13070     return ResType.getUnqualifiedType();
13071   }
13072 }
13073 
13074 
13075 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
13076 /// This routine allows us to typecheck complex/recursive expressions
13077 /// where the declaration is needed for type checking. We only need to
13078 /// handle cases when the expression references a function designator
13079 /// or is an lvalue. Here are some examples:
13080 ///  - &(x) => x
13081 ///  - &*****f => f for f a function designator.
13082 ///  - &s.xx => s
13083 ///  - &s.zz[1].yy -> s, if zz is an array
13084 ///  - *(x + 1) -> x, if x is an array
13085 ///  - &"123"[2] -> 0
13086 ///  - & __real__ x -> x
13087 ///
13088 /// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to
13089 /// members.
13090 static ValueDecl *getPrimaryDecl(Expr *E) {
13091   switch (E->getStmtClass()) {
13092   case Stmt::DeclRefExprClass:
13093     return cast<DeclRefExpr>(E)->getDecl();
13094   case Stmt::MemberExprClass:
13095     // If this is an arrow operator, the address is an offset from
13096     // the base's value, so the object the base refers to is
13097     // irrelevant.
13098     if (cast<MemberExpr>(E)->isArrow())
13099       return nullptr;
13100     // Otherwise, the expression refers to a part of the base
13101     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
13102   case Stmt::ArraySubscriptExprClass: {
13103     // FIXME: This code shouldn't be necessary!  We should catch the implicit
13104     // promotion of register arrays earlier.
13105     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
13106     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
13107       if (ICE->getSubExpr()->getType()->isArrayType())
13108         return getPrimaryDecl(ICE->getSubExpr());
13109     }
13110     return nullptr;
13111   }
13112   case Stmt::UnaryOperatorClass: {
13113     UnaryOperator *UO = cast<UnaryOperator>(E);
13114 
13115     switch(UO->getOpcode()) {
13116     case UO_Real:
13117     case UO_Imag:
13118     case UO_Extension:
13119       return getPrimaryDecl(UO->getSubExpr());
13120     default:
13121       return nullptr;
13122     }
13123   }
13124   case Stmt::ParenExprClass:
13125     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
13126   case Stmt::ImplicitCastExprClass:
13127     // If the result of an implicit cast is an l-value, we care about
13128     // the sub-expression; otherwise, the result here doesn't matter.
13129     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
13130   case Stmt::CXXUuidofExprClass:
13131     return cast<CXXUuidofExpr>(E)->getGuidDecl();
13132   default:
13133     return nullptr;
13134   }
13135 }
13136 
13137 namespace {
13138 enum {
13139   AO_Bit_Field = 0,
13140   AO_Vector_Element = 1,
13141   AO_Property_Expansion = 2,
13142   AO_Register_Variable = 3,
13143   AO_Matrix_Element = 4,
13144   AO_No_Error = 5
13145 };
13146 }
13147 /// Diagnose invalid operand for address of operations.
13148 ///
13149 /// \param Type The type of operand which cannot have its address taken.
13150 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
13151                                          Expr *E, unsigned Type) {
13152   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
13153 }
13154 
13155 /// CheckAddressOfOperand - The operand of & must be either a function
13156 /// designator or an lvalue designating an object. If it is an lvalue, the
13157 /// object cannot be declared with storage class register or be a bit field.
13158 /// Note: The usual conversions are *not* applied to the operand of the &
13159 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
13160 /// In C++, the operand might be an overloaded function name, in which case
13161 /// we allow the '&' but retain the overloaded-function type.
13162 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
13163   if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
13164     if (PTy->getKind() == BuiltinType::Overload) {
13165       Expr *E = OrigOp.get()->IgnoreParens();
13166       if (!isa<OverloadExpr>(E)) {
13167         assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
13168         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
13169           << OrigOp.get()->getSourceRange();
13170         return QualType();
13171       }
13172 
13173       OverloadExpr *Ovl = cast<OverloadExpr>(E);
13174       if (isa<UnresolvedMemberExpr>(Ovl))
13175         if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
13176           Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
13177             << OrigOp.get()->getSourceRange();
13178           return QualType();
13179         }
13180 
13181       return Context.OverloadTy;
13182     }
13183 
13184     if (PTy->getKind() == BuiltinType::UnknownAny)
13185       return Context.UnknownAnyTy;
13186 
13187     if (PTy->getKind() == BuiltinType::BoundMember) {
13188       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
13189         << OrigOp.get()->getSourceRange();
13190       return QualType();
13191     }
13192 
13193     OrigOp = CheckPlaceholderExpr(OrigOp.get());
13194     if (OrigOp.isInvalid()) return QualType();
13195   }
13196 
13197   if (OrigOp.get()->isTypeDependent())
13198     return Context.DependentTy;
13199 
13200   assert(!OrigOp.get()->getType()->isPlaceholderType());
13201 
13202   // Make sure to ignore parentheses in subsequent checks
13203   Expr *op = OrigOp.get()->IgnoreParens();
13204 
13205   // In OpenCL captures for blocks called as lambda functions
13206   // are located in the private address space. Blocks used in
13207   // enqueue_kernel can be located in a different address space
13208   // depending on a vendor implementation. Thus preventing
13209   // taking an address of the capture to avoid invalid AS casts.
13210   if (LangOpts.OpenCL) {
13211     auto* VarRef = dyn_cast<DeclRefExpr>(op);
13212     if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
13213       Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
13214       return QualType();
13215     }
13216   }
13217 
13218   if (getLangOpts().C99) {
13219     // Implement C99-only parts of addressof rules.
13220     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
13221       if (uOp->getOpcode() == UO_Deref)
13222         // Per C99 6.5.3.2, the address of a deref always returns a valid result
13223         // (assuming the deref expression is valid).
13224         return uOp->getSubExpr()->getType();
13225     }
13226     // Technically, there should be a check for array subscript
13227     // expressions here, but the result of one is always an lvalue anyway.
13228   }
13229   ValueDecl *dcl = getPrimaryDecl(op);
13230 
13231   if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
13232     if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
13233                                            op->getBeginLoc()))
13234       return QualType();
13235 
13236   Expr::LValueClassification lval = op->ClassifyLValue(Context);
13237   unsigned AddressOfError = AO_No_Error;
13238 
13239   if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
13240     bool sfinae = (bool)isSFINAEContext();
13241     Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
13242                                   : diag::ext_typecheck_addrof_temporary)
13243       << op->getType() << op->getSourceRange();
13244     if (sfinae)
13245       return QualType();
13246     // Materialize the temporary as an lvalue so that we can take its address.
13247     OrigOp = op =
13248         CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
13249   } else if (isa<ObjCSelectorExpr>(op)) {
13250     return Context.getPointerType(op->getType());
13251   } else if (lval == Expr::LV_MemberFunction) {
13252     // If it's an instance method, make a member pointer.
13253     // The expression must have exactly the form &A::foo.
13254 
13255     // If the underlying expression isn't a decl ref, give up.
13256     if (!isa<DeclRefExpr>(op)) {
13257       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
13258         << OrigOp.get()->getSourceRange();
13259       return QualType();
13260     }
13261     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
13262     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
13263 
13264     // The id-expression was parenthesized.
13265     if (OrigOp.get() != DRE) {
13266       Diag(OpLoc, diag::err_parens_pointer_member_function)
13267         << OrigOp.get()->getSourceRange();
13268 
13269     // The method was named without a qualifier.
13270     } else if (!DRE->getQualifier()) {
13271       if (MD->getParent()->getName().empty())
13272         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
13273           << op->getSourceRange();
13274       else {
13275         SmallString<32> Str;
13276         StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
13277         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
13278           << op->getSourceRange()
13279           << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
13280       }
13281     }
13282 
13283     // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
13284     if (isa<CXXDestructorDecl>(MD))
13285       Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
13286 
13287     QualType MPTy = Context.getMemberPointerType(
13288         op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
13289     // Under the MS ABI, lock down the inheritance model now.
13290     if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13291       (void)isCompleteType(OpLoc, MPTy);
13292     return MPTy;
13293   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
13294     // C99 6.5.3.2p1
13295     // The operand must be either an l-value or a function designator
13296     if (!op->getType()->isFunctionType()) {
13297       // Use a special diagnostic for loads from property references.
13298       if (isa<PseudoObjectExpr>(op)) {
13299         AddressOfError = AO_Property_Expansion;
13300       } else {
13301         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
13302           << op->getType() << op->getSourceRange();
13303         return QualType();
13304       }
13305     }
13306   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
13307     // The operand cannot be a bit-field
13308     AddressOfError = AO_Bit_Field;
13309   } else if (op->getObjectKind() == OK_VectorComponent) {
13310     // The operand cannot be an element of a vector
13311     AddressOfError = AO_Vector_Element;
13312   } else if (op->getObjectKind() == OK_MatrixComponent) {
13313     // The operand cannot be an element of a matrix.
13314     AddressOfError = AO_Matrix_Element;
13315   } else if (dcl) { // C99 6.5.3.2p1
13316     // We have an lvalue with a decl. Make sure the decl is not declared
13317     // with the register storage-class specifier.
13318     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
13319       // in C++ it is not error to take address of a register
13320       // variable (c++03 7.1.1P3)
13321       if (vd->getStorageClass() == SC_Register &&
13322           !getLangOpts().CPlusPlus) {
13323         AddressOfError = AO_Register_Variable;
13324       }
13325     } else if (isa<MSPropertyDecl>(dcl)) {
13326       AddressOfError = AO_Property_Expansion;
13327     } else if (isa<FunctionTemplateDecl>(dcl)) {
13328       return Context.OverloadTy;
13329     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
13330       // Okay: we can take the address of a field.
13331       // Could be a pointer to member, though, if there is an explicit
13332       // scope qualifier for the class.
13333       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
13334         DeclContext *Ctx = dcl->getDeclContext();
13335         if (Ctx && Ctx->isRecord()) {
13336           if (dcl->getType()->isReferenceType()) {
13337             Diag(OpLoc,
13338                  diag::err_cannot_form_pointer_to_member_of_reference_type)
13339               << dcl->getDeclName() << dcl->getType();
13340             return QualType();
13341           }
13342 
13343           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
13344             Ctx = Ctx->getParent();
13345 
13346           QualType MPTy = Context.getMemberPointerType(
13347               op->getType(),
13348               Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
13349           // Under the MS ABI, lock down the inheritance model now.
13350           if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13351             (void)isCompleteType(OpLoc, MPTy);
13352           return MPTy;
13353         }
13354       }
13355     } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) &&
13356                !isa<BindingDecl>(dcl) && !isa<MSGuidDecl>(dcl))
13357       llvm_unreachable("Unknown/unexpected decl type");
13358   }
13359 
13360   if (AddressOfError != AO_No_Error) {
13361     diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
13362     return QualType();
13363   }
13364 
13365   if (lval == Expr::LV_IncompleteVoidType) {
13366     // Taking the address of a void variable is technically illegal, but we
13367     // allow it in cases which are otherwise valid.
13368     // Example: "extern void x; void* y = &x;".
13369     Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
13370   }
13371 
13372   // If the operand has type "type", the result has type "pointer to type".
13373   if (op->getType()->isObjCObjectType())
13374     return Context.getObjCObjectPointerType(op->getType());
13375 
13376   CheckAddressOfPackedMember(op);
13377 
13378   return Context.getPointerType(op->getType());
13379 }
13380 
13381 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
13382   const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
13383   if (!DRE)
13384     return;
13385   const Decl *D = DRE->getDecl();
13386   if (!D)
13387     return;
13388   const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
13389   if (!Param)
13390     return;
13391   if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
13392     if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
13393       return;
13394   if (FunctionScopeInfo *FD = S.getCurFunction())
13395     if (!FD->ModifiedNonNullParams.count(Param))
13396       FD->ModifiedNonNullParams.insert(Param);
13397 }
13398 
13399 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
13400 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
13401                                         SourceLocation OpLoc) {
13402   if (Op->isTypeDependent())
13403     return S.Context.DependentTy;
13404 
13405   ExprResult ConvResult = S.UsualUnaryConversions(Op);
13406   if (ConvResult.isInvalid())
13407     return QualType();
13408   Op = ConvResult.get();
13409   QualType OpTy = Op->getType();
13410   QualType Result;
13411 
13412   if (isa<CXXReinterpretCastExpr>(Op)) {
13413     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
13414     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
13415                                      Op->getSourceRange());
13416   }
13417 
13418   if (const PointerType *PT = OpTy->getAs<PointerType>())
13419   {
13420     Result = PT->getPointeeType();
13421   }
13422   else if (const ObjCObjectPointerType *OPT =
13423              OpTy->getAs<ObjCObjectPointerType>())
13424     Result = OPT->getPointeeType();
13425   else {
13426     ExprResult PR = S.CheckPlaceholderExpr(Op);
13427     if (PR.isInvalid()) return QualType();
13428     if (PR.get() != Op)
13429       return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
13430   }
13431 
13432   if (Result.isNull()) {
13433     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
13434       << OpTy << Op->getSourceRange();
13435     return QualType();
13436   }
13437 
13438   // Note that per both C89 and C99, indirection is always legal, even if Result
13439   // is an incomplete type or void.  It would be possible to warn about
13440   // dereferencing a void pointer, but it's completely well-defined, and such a
13441   // warning is unlikely to catch any mistakes. In C++, indirection is not valid
13442   // for pointers to 'void' but is fine for any other pointer type:
13443   //
13444   // C++ [expr.unary.op]p1:
13445   //   [...] the expression to which [the unary * operator] is applied shall
13446   //   be a pointer to an object type, or a pointer to a function type
13447   if (S.getLangOpts().CPlusPlus && Result->isVoidType())
13448     S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
13449       << OpTy << Op->getSourceRange();
13450 
13451   // Dereferences are usually l-values...
13452   VK = VK_LValue;
13453 
13454   // ...except that certain expressions are never l-values in C.
13455   if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
13456     VK = VK_RValue;
13457 
13458   return Result;
13459 }
13460 
13461 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
13462   BinaryOperatorKind Opc;
13463   switch (Kind) {
13464   default: llvm_unreachable("Unknown binop!");
13465   case tok::periodstar:           Opc = BO_PtrMemD; break;
13466   case tok::arrowstar:            Opc = BO_PtrMemI; break;
13467   case tok::star:                 Opc = BO_Mul; break;
13468   case tok::slash:                Opc = BO_Div; break;
13469   case tok::percent:              Opc = BO_Rem; break;
13470   case tok::plus:                 Opc = BO_Add; break;
13471   case tok::minus:                Opc = BO_Sub; break;
13472   case tok::lessless:             Opc = BO_Shl; break;
13473   case tok::greatergreater:       Opc = BO_Shr; break;
13474   case tok::lessequal:            Opc = BO_LE; break;
13475   case tok::less:                 Opc = BO_LT; break;
13476   case tok::greaterequal:         Opc = BO_GE; break;
13477   case tok::greater:              Opc = BO_GT; break;
13478   case tok::exclaimequal:         Opc = BO_NE; break;
13479   case tok::equalequal:           Opc = BO_EQ; break;
13480   case tok::spaceship:            Opc = BO_Cmp; break;
13481   case tok::amp:                  Opc = BO_And; break;
13482   case tok::caret:                Opc = BO_Xor; break;
13483   case tok::pipe:                 Opc = BO_Or; break;
13484   case tok::ampamp:               Opc = BO_LAnd; break;
13485   case tok::pipepipe:             Opc = BO_LOr; break;
13486   case tok::equal:                Opc = BO_Assign; break;
13487   case tok::starequal:            Opc = BO_MulAssign; break;
13488   case tok::slashequal:           Opc = BO_DivAssign; break;
13489   case tok::percentequal:         Opc = BO_RemAssign; break;
13490   case tok::plusequal:            Opc = BO_AddAssign; break;
13491   case tok::minusequal:           Opc = BO_SubAssign; break;
13492   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
13493   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
13494   case tok::ampequal:             Opc = BO_AndAssign; break;
13495   case tok::caretequal:           Opc = BO_XorAssign; break;
13496   case tok::pipeequal:            Opc = BO_OrAssign; break;
13497   case tok::comma:                Opc = BO_Comma; break;
13498   }
13499   return Opc;
13500 }
13501 
13502 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
13503   tok::TokenKind Kind) {
13504   UnaryOperatorKind Opc;
13505   switch (Kind) {
13506   default: llvm_unreachable("Unknown unary op!");
13507   case tok::plusplus:     Opc = UO_PreInc; break;
13508   case tok::minusminus:   Opc = UO_PreDec; break;
13509   case tok::amp:          Opc = UO_AddrOf; break;
13510   case tok::star:         Opc = UO_Deref; break;
13511   case tok::plus:         Opc = UO_Plus; break;
13512   case tok::minus:        Opc = UO_Minus; break;
13513   case tok::tilde:        Opc = UO_Not; break;
13514   case tok::exclaim:      Opc = UO_LNot; break;
13515   case tok::kw___real:    Opc = UO_Real; break;
13516   case tok::kw___imag:    Opc = UO_Imag; break;
13517   case tok::kw___extension__: Opc = UO_Extension; break;
13518   }
13519   return Opc;
13520 }
13521 
13522 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
13523 /// This warning suppressed in the event of macro expansions.
13524 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
13525                                    SourceLocation OpLoc, bool IsBuiltin) {
13526   if (S.inTemplateInstantiation())
13527     return;
13528   if (S.isUnevaluatedContext())
13529     return;
13530   if (OpLoc.isInvalid() || OpLoc.isMacroID())
13531     return;
13532   LHSExpr = LHSExpr->IgnoreParenImpCasts();
13533   RHSExpr = RHSExpr->IgnoreParenImpCasts();
13534   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
13535   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
13536   if (!LHSDeclRef || !RHSDeclRef ||
13537       LHSDeclRef->getLocation().isMacroID() ||
13538       RHSDeclRef->getLocation().isMacroID())
13539     return;
13540   const ValueDecl *LHSDecl =
13541     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
13542   const ValueDecl *RHSDecl =
13543     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
13544   if (LHSDecl != RHSDecl)
13545     return;
13546   if (LHSDecl->getType().isVolatileQualified())
13547     return;
13548   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
13549     if (RefTy->getPointeeType().isVolatileQualified())
13550       return;
13551 
13552   S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
13553                           : diag::warn_self_assignment_overloaded)
13554       << LHSDeclRef->getType() << LHSExpr->getSourceRange()
13555       << RHSExpr->getSourceRange();
13556 }
13557 
13558 /// Check if a bitwise-& is performed on an Objective-C pointer.  This
13559 /// is usually indicative of introspection within the Objective-C pointer.
13560 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
13561                                           SourceLocation OpLoc) {
13562   if (!S.getLangOpts().ObjC)
13563     return;
13564 
13565   const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
13566   const Expr *LHS = L.get();
13567   const Expr *RHS = R.get();
13568 
13569   if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
13570     ObjCPointerExpr = LHS;
13571     OtherExpr = RHS;
13572   }
13573   else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
13574     ObjCPointerExpr = RHS;
13575     OtherExpr = LHS;
13576   }
13577 
13578   // This warning is deliberately made very specific to reduce false
13579   // positives with logic that uses '&' for hashing.  This logic mainly
13580   // looks for code trying to introspect into tagged pointers, which
13581   // code should generally never do.
13582   if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
13583     unsigned Diag = diag::warn_objc_pointer_masking;
13584     // Determine if we are introspecting the result of performSelectorXXX.
13585     const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
13586     // Special case messages to -performSelector and friends, which
13587     // can return non-pointer values boxed in a pointer value.
13588     // Some clients may wish to silence warnings in this subcase.
13589     if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
13590       Selector S = ME->getSelector();
13591       StringRef SelArg0 = S.getNameForSlot(0);
13592       if (SelArg0.startswith("performSelector"))
13593         Diag = diag::warn_objc_pointer_masking_performSelector;
13594     }
13595 
13596     S.Diag(OpLoc, Diag)
13597       << ObjCPointerExpr->getSourceRange();
13598   }
13599 }
13600 
13601 static NamedDecl *getDeclFromExpr(Expr *E) {
13602   if (!E)
13603     return nullptr;
13604   if (auto *DRE = dyn_cast<DeclRefExpr>(E))
13605     return DRE->getDecl();
13606   if (auto *ME = dyn_cast<MemberExpr>(E))
13607     return ME->getMemberDecl();
13608   if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
13609     return IRE->getDecl();
13610   return nullptr;
13611 }
13612 
13613 // This helper function promotes a binary operator's operands (which are of a
13614 // half vector type) to a vector of floats and then truncates the result to
13615 // a vector of either half or short.
13616 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS,
13617                                       BinaryOperatorKind Opc, QualType ResultTy,
13618                                       ExprValueKind VK, ExprObjectKind OK,
13619                                       bool IsCompAssign, SourceLocation OpLoc,
13620                                       FPOptions FPFeatures) {
13621   auto &Context = S.getASTContext();
13622   assert((isVector(ResultTy, Context.HalfTy) ||
13623           isVector(ResultTy, Context.ShortTy)) &&
13624          "Result must be a vector of half or short");
13625   assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
13626          isVector(RHS.get()->getType(), Context.HalfTy) &&
13627          "both operands expected to be a half vector");
13628 
13629   RHS = convertVector(RHS.get(), Context.FloatTy, S);
13630   QualType BinOpResTy = RHS.get()->getType();
13631 
13632   // If Opc is a comparison, ResultType is a vector of shorts. In that case,
13633   // change BinOpResTy to a vector of ints.
13634   if (isVector(ResultTy, Context.ShortTy))
13635     BinOpResTy = S.GetSignedVectorType(BinOpResTy);
13636 
13637   if (IsCompAssign)
13638     return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc,
13639                                           ResultTy, VK, OK, OpLoc, FPFeatures,
13640                                           BinOpResTy, BinOpResTy);
13641 
13642   LHS = convertVector(LHS.get(), Context.FloatTy, S);
13643   auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc,
13644                                     BinOpResTy, VK, OK, OpLoc, FPFeatures);
13645   return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S);
13646 }
13647 
13648 static std::pair<ExprResult, ExprResult>
13649 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr,
13650                            Expr *RHSExpr) {
13651   ExprResult LHS = LHSExpr, RHS = RHSExpr;
13652   if (!S.getLangOpts().CPlusPlus) {
13653     // C cannot handle TypoExpr nodes on either side of a binop because it
13654     // doesn't handle dependent types properly, so make sure any TypoExprs have
13655     // been dealt with before checking the operands.
13656     LHS = S.CorrectDelayedTyposInExpr(LHS);
13657     RHS = S.CorrectDelayedTyposInExpr(
13658         RHS, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false,
13659         [Opc, LHS](Expr *E) {
13660           if (Opc != BO_Assign)
13661             return ExprResult(E);
13662           // Avoid correcting the RHS to the same Expr as the LHS.
13663           Decl *D = getDeclFromExpr(E);
13664           return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
13665         });
13666   }
13667   return std::make_pair(LHS, RHS);
13668 }
13669 
13670 /// Returns true if conversion between vectors of halfs and vectors of floats
13671 /// is needed.
13672 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
13673                                      Expr *E0, Expr *E1 = nullptr) {
13674   if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType ||
13675       Ctx.getTargetInfo().useFP16ConversionIntrinsics())
13676     return false;
13677 
13678   auto HasVectorOfHalfType = [&Ctx](Expr *E) {
13679     QualType Ty = E->IgnoreImplicit()->getType();
13680 
13681     // Don't promote half precision neon vectors like float16x4_t in arm_neon.h
13682     // to vectors of floats. Although the element type of the vectors is __fp16,
13683     // the vectors shouldn't be treated as storage-only types. See the
13684     // discussion here: https://reviews.llvm.org/rG825235c140e7
13685     if (const VectorType *VT = Ty->getAs<VectorType>()) {
13686       if (VT->getVectorKind() == VectorType::NeonVector)
13687         return false;
13688       return VT->getElementType().getCanonicalType() == Ctx.HalfTy;
13689     }
13690     return false;
13691   };
13692 
13693   return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1));
13694 }
13695 
13696 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
13697 /// operator @p Opc at location @c TokLoc. This routine only supports
13698 /// built-in operations; ActOnBinOp handles overloaded operators.
13699 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
13700                                     BinaryOperatorKind Opc,
13701                                     Expr *LHSExpr, Expr *RHSExpr) {
13702   if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
13703     // The syntax only allows initializer lists on the RHS of assignment,
13704     // so we don't need to worry about accepting invalid code for
13705     // non-assignment operators.
13706     // C++11 5.17p9:
13707     //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
13708     //   of x = {} is x = T().
13709     InitializationKind Kind = InitializationKind::CreateDirectList(
13710         RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
13711     InitializedEntity Entity =
13712         InitializedEntity::InitializeTemporary(LHSExpr->getType());
13713     InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
13714     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
13715     if (Init.isInvalid())
13716       return Init;
13717     RHSExpr = Init.get();
13718   }
13719 
13720   ExprResult LHS = LHSExpr, RHS = RHSExpr;
13721   QualType ResultTy;     // Result type of the binary operator.
13722   // The following two variables are used for compound assignment operators
13723   QualType CompLHSTy;    // Type of LHS after promotions for computation
13724   QualType CompResultTy; // Type of computation result
13725   ExprValueKind VK = VK_RValue;
13726   ExprObjectKind OK = OK_Ordinary;
13727   bool ConvertHalfVec = false;
13728 
13729   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
13730   if (!LHS.isUsable() || !RHS.isUsable())
13731     return ExprError();
13732 
13733   if (getLangOpts().OpenCL) {
13734     QualType LHSTy = LHSExpr->getType();
13735     QualType RHSTy = RHSExpr->getType();
13736     // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
13737     // the ATOMIC_VAR_INIT macro.
13738     if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
13739       SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
13740       if (BO_Assign == Opc)
13741         Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
13742       else
13743         ResultTy = InvalidOperands(OpLoc, LHS, RHS);
13744       return ExprError();
13745     }
13746 
13747     // OpenCL special types - image, sampler, pipe, and blocks are to be used
13748     // only with a builtin functions and therefore should be disallowed here.
13749     if (LHSTy->isImageType() || RHSTy->isImageType() ||
13750         LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
13751         LHSTy->isPipeType() || RHSTy->isPipeType() ||
13752         LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
13753       ResultTy = InvalidOperands(OpLoc, LHS, RHS);
13754       return ExprError();
13755     }
13756   }
13757 
13758   switch (Opc) {
13759   case BO_Assign:
13760     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
13761     if (getLangOpts().CPlusPlus &&
13762         LHS.get()->getObjectKind() != OK_ObjCProperty) {
13763       VK = LHS.get()->getValueKind();
13764       OK = LHS.get()->getObjectKind();
13765     }
13766     if (!ResultTy.isNull()) {
13767       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
13768       DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
13769 
13770       // Avoid copying a block to the heap if the block is assigned to a local
13771       // auto variable that is declared in the same scope as the block. This
13772       // optimization is unsafe if the local variable is declared in an outer
13773       // scope. For example:
13774       //
13775       // BlockTy b;
13776       // {
13777       //   b = ^{...};
13778       // }
13779       // // It is unsafe to invoke the block here if it wasn't copied to the
13780       // // heap.
13781       // b();
13782 
13783       if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens()))
13784         if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
13785           if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
13786             if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD))
13787               BE->getBlockDecl()->setCanAvoidCopyToHeap();
13788 
13789       if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion())
13790         checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(),
13791                               NTCUC_Assignment, NTCUK_Copy);
13792     }
13793     RecordModifiableNonNullParam(*this, LHS.get());
13794     break;
13795   case BO_PtrMemD:
13796   case BO_PtrMemI:
13797     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
13798                                             Opc == BO_PtrMemI);
13799     break;
13800   case BO_Mul:
13801   case BO_Div:
13802     ConvertHalfVec = true;
13803     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
13804                                            Opc == BO_Div);
13805     break;
13806   case BO_Rem:
13807     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
13808     break;
13809   case BO_Add:
13810     ConvertHalfVec = true;
13811     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
13812     break;
13813   case BO_Sub:
13814     ConvertHalfVec = true;
13815     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
13816     break;
13817   case BO_Shl:
13818   case BO_Shr:
13819     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
13820     break;
13821   case BO_LE:
13822   case BO_LT:
13823   case BO_GE:
13824   case BO_GT:
13825     ConvertHalfVec = true;
13826     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
13827     break;
13828   case BO_EQ:
13829   case BO_NE:
13830     ConvertHalfVec = true;
13831     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
13832     break;
13833   case BO_Cmp:
13834     ConvertHalfVec = true;
13835     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
13836     assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
13837     break;
13838   case BO_And:
13839     checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
13840     LLVM_FALLTHROUGH;
13841   case BO_Xor:
13842   case BO_Or:
13843     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
13844     break;
13845   case BO_LAnd:
13846   case BO_LOr:
13847     ConvertHalfVec = true;
13848     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
13849     break;
13850   case BO_MulAssign:
13851   case BO_DivAssign:
13852     ConvertHalfVec = true;
13853     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
13854                                                Opc == BO_DivAssign);
13855     CompLHSTy = CompResultTy;
13856     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13857       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13858     break;
13859   case BO_RemAssign:
13860     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
13861     CompLHSTy = CompResultTy;
13862     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13863       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13864     break;
13865   case BO_AddAssign:
13866     ConvertHalfVec = true;
13867     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
13868     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13869       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13870     break;
13871   case BO_SubAssign:
13872     ConvertHalfVec = true;
13873     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
13874     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13875       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13876     break;
13877   case BO_ShlAssign:
13878   case BO_ShrAssign:
13879     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
13880     CompLHSTy = CompResultTy;
13881     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13882       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13883     break;
13884   case BO_AndAssign:
13885   case BO_OrAssign: // fallthrough
13886     DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
13887     LLVM_FALLTHROUGH;
13888   case BO_XorAssign:
13889     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
13890     CompLHSTy = CompResultTy;
13891     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13892       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13893     break;
13894   case BO_Comma:
13895     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
13896     if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
13897       VK = RHS.get()->getValueKind();
13898       OK = RHS.get()->getObjectKind();
13899     }
13900     break;
13901   }
13902   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
13903     return ExprError();
13904 
13905   // Some of the binary operations require promoting operands of half vector to
13906   // float vectors and truncating the result back to half vector. For now, we do
13907   // this only when HalfArgsAndReturn is set (that is, when the target is arm or
13908   // arm64).
13909   assert(isVector(RHS.get()->getType(), Context.HalfTy) ==
13910          isVector(LHS.get()->getType(), Context.HalfTy) &&
13911          "both sides are half vectors or neither sides are");
13912   ConvertHalfVec =
13913       needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get());
13914 
13915   // Check for array bounds violations for both sides of the BinaryOperator
13916   CheckArrayAccess(LHS.get());
13917   CheckArrayAccess(RHS.get());
13918 
13919   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
13920     NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
13921                                                  &Context.Idents.get("object_setClass"),
13922                                                  SourceLocation(), LookupOrdinaryName);
13923     if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
13924       SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc());
13925       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign)
13926           << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(),
13927                                         "object_setClass(")
13928           << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc),
13929                                           ",")
13930           << FixItHint::CreateInsertion(RHSLocEnd, ")");
13931     }
13932     else
13933       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
13934   }
13935   else if (const ObjCIvarRefExpr *OIRE =
13936            dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
13937     DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
13938 
13939   // Opc is not a compound assignment if CompResultTy is null.
13940   if (CompResultTy.isNull()) {
13941     if (ConvertHalfVec)
13942       return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
13943                                  OpLoc, CurFPFeatures);
13944     return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy,
13945                                   VK, OK, OpLoc, CurFPFeatures);
13946   }
13947 
13948   // Handle compound assignments.
13949   if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
13950       OK_ObjCProperty) {
13951     VK = VK_LValue;
13952     OK = LHS.get()->getObjectKind();
13953   }
13954 
13955   // The LHS is not converted to the result type for fixed-point compound
13956   // assignment as the common type is computed on demand. Reset the CompLHSTy
13957   // to the LHS type we would have gotten after unary conversions.
13958   if (CompResultTy->isFixedPointType())
13959     CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType();
13960 
13961   if (ConvertHalfVec)
13962     return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
13963                                OpLoc, CurFPFeatures);
13964 
13965   return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc,
13966                                         ResultTy, VK, OK, OpLoc, CurFPFeatures,
13967                                         CompLHSTy, CompResultTy);
13968 }
13969 
13970 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
13971 /// operators are mixed in a way that suggests that the programmer forgot that
13972 /// comparison operators have higher precedence. The most typical example of
13973 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
13974 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
13975                                       SourceLocation OpLoc, Expr *LHSExpr,
13976                                       Expr *RHSExpr) {
13977   BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
13978   BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
13979 
13980   // Check that one of the sides is a comparison operator and the other isn't.
13981   bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
13982   bool isRightComp = RHSBO && RHSBO->isComparisonOp();
13983   if (isLeftComp == isRightComp)
13984     return;
13985 
13986   // Bitwise operations are sometimes used as eager logical ops.
13987   // Don't diagnose this.
13988   bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
13989   bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
13990   if (isLeftBitwise || isRightBitwise)
13991     return;
13992 
13993   SourceRange DiagRange = isLeftComp
13994                               ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
13995                               : SourceRange(OpLoc, RHSExpr->getEndLoc());
13996   StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
13997   SourceRange ParensRange =
13998       isLeftComp
13999           ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
14000           : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
14001 
14002   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
14003     << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
14004   SuggestParentheses(Self, OpLoc,
14005     Self.PDiag(diag::note_precedence_silence) << OpStr,
14006     (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
14007   SuggestParentheses(Self, OpLoc,
14008     Self.PDiag(diag::note_precedence_bitwise_first)
14009       << BinaryOperator::getOpcodeStr(Opc),
14010     ParensRange);
14011 }
14012 
14013 /// It accepts a '&&' expr that is inside a '||' one.
14014 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
14015 /// in parentheses.
14016 static void
14017 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
14018                                        BinaryOperator *Bop) {
14019   assert(Bop->getOpcode() == BO_LAnd);
14020   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
14021       << Bop->getSourceRange() << OpLoc;
14022   SuggestParentheses(Self, Bop->getOperatorLoc(),
14023     Self.PDiag(diag::note_precedence_silence)
14024       << Bop->getOpcodeStr(),
14025     Bop->getSourceRange());
14026 }
14027 
14028 /// Returns true if the given expression can be evaluated as a constant
14029 /// 'true'.
14030 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
14031   bool Res;
14032   return !E->isValueDependent() &&
14033          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
14034 }
14035 
14036 /// Returns true if the given expression can be evaluated as a constant
14037 /// 'false'.
14038 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
14039   bool Res;
14040   return !E->isValueDependent() &&
14041          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
14042 }
14043 
14044 /// Look for '&&' in the left hand of a '||' expr.
14045 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
14046                                              Expr *LHSExpr, Expr *RHSExpr) {
14047   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
14048     if (Bop->getOpcode() == BO_LAnd) {
14049       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
14050       if (EvaluatesAsFalse(S, RHSExpr))
14051         return;
14052       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
14053       if (!EvaluatesAsTrue(S, Bop->getLHS()))
14054         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
14055     } else if (Bop->getOpcode() == BO_LOr) {
14056       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
14057         // If it's "a || b && 1 || c" we didn't warn earlier for
14058         // "a || b && 1", but warn now.
14059         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
14060           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
14061       }
14062     }
14063   }
14064 }
14065 
14066 /// Look for '&&' in the right hand of a '||' expr.
14067 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
14068                                              Expr *LHSExpr, Expr *RHSExpr) {
14069   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
14070     if (Bop->getOpcode() == BO_LAnd) {
14071       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
14072       if (EvaluatesAsFalse(S, LHSExpr))
14073         return;
14074       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
14075       if (!EvaluatesAsTrue(S, Bop->getRHS()))
14076         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
14077     }
14078   }
14079 }
14080 
14081 /// Look for bitwise op in the left or right hand of a bitwise op with
14082 /// lower precedence and emit a diagnostic together with a fixit hint that wraps
14083 /// the '&' expression in parentheses.
14084 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
14085                                          SourceLocation OpLoc, Expr *SubExpr) {
14086   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
14087     if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
14088       S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
14089         << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
14090         << Bop->getSourceRange() << OpLoc;
14091       SuggestParentheses(S, Bop->getOperatorLoc(),
14092         S.PDiag(diag::note_precedence_silence)
14093           << Bop->getOpcodeStr(),
14094         Bop->getSourceRange());
14095     }
14096   }
14097 }
14098 
14099 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
14100                                     Expr *SubExpr, StringRef Shift) {
14101   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
14102     if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
14103       StringRef Op = Bop->getOpcodeStr();
14104       S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
14105           << Bop->getSourceRange() << OpLoc << Shift << Op;
14106       SuggestParentheses(S, Bop->getOperatorLoc(),
14107           S.PDiag(diag::note_precedence_silence) << Op,
14108           Bop->getSourceRange());
14109     }
14110   }
14111 }
14112 
14113 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
14114                                  Expr *LHSExpr, Expr *RHSExpr) {
14115   CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
14116   if (!OCE)
14117     return;
14118 
14119   FunctionDecl *FD = OCE->getDirectCallee();
14120   if (!FD || !FD->isOverloadedOperator())
14121     return;
14122 
14123   OverloadedOperatorKind Kind = FD->getOverloadedOperator();
14124   if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
14125     return;
14126 
14127   S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
14128       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
14129       << (Kind == OO_LessLess);
14130   SuggestParentheses(S, OCE->getOperatorLoc(),
14131                      S.PDiag(diag::note_precedence_silence)
14132                          << (Kind == OO_LessLess ? "<<" : ">>"),
14133                      OCE->getSourceRange());
14134   SuggestParentheses(
14135       S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first),
14136       SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc()));
14137 }
14138 
14139 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
14140 /// precedence.
14141 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
14142                                     SourceLocation OpLoc, Expr *LHSExpr,
14143                                     Expr *RHSExpr){
14144   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
14145   if (BinaryOperator::isBitwiseOp(Opc))
14146     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
14147 
14148   // Diagnose "arg1 & arg2 | arg3"
14149   if ((Opc == BO_Or || Opc == BO_Xor) &&
14150       !OpLoc.isMacroID()/* Don't warn in macros. */) {
14151     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
14152     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
14153   }
14154 
14155   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
14156   // We don't warn for 'assert(a || b && "bad")' since this is safe.
14157   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
14158     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
14159     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
14160   }
14161 
14162   if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
14163       || Opc == BO_Shr) {
14164     StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
14165     DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
14166     DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
14167   }
14168 
14169   // Warn on overloaded shift operators and comparisons, such as:
14170   // cout << 5 == 4;
14171   if (BinaryOperator::isComparisonOp(Opc))
14172     DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
14173 }
14174 
14175 // Binary Operators.  'Tok' is the token for the operator.
14176 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
14177                             tok::TokenKind Kind,
14178                             Expr *LHSExpr, Expr *RHSExpr) {
14179   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
14180   assert(LHSExpr && "ActOnBinOp(): missing left expression");
14181   assert(RHSExpr && "ActOnBinOp(): missing right expression");
14182 
14183   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
14184   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
14185 
14186   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
14187 }
14188 
14189 /// Build an overloaded binary operator expression in the given scope.
14190 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
14191                                        BinaryOperatorKind Opc,
14192                                        Expr *LHS, Expr *RHS) {
14193   switch (Opc) {
14194   case BO_Assign:
14195   case BO_DivAssign:
14196   case BO_RemAssign:
14197   case BO_SubAssign:
14198   case BO_AndAssign:
14199   case BO_OrAssign:
14200   case BO_XorAssign:
14201     DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
14202     CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
14203     break;
14204   default:
14205     break;
14206   }
14207 
14208   // Find all of the overloaded operators visible from this
14209   // point. We perform both an operator-name lookup from the local
14210   // scope and an argument-dependent lookup based on the types of
14211   // the arguments.
14212   UnresolvedSet<16> Functions;
14213   OverloadedOperatorKind OverOp
14214     = BinaryOperator::getOverloadedOperator(Opc);
14215   if (Sc && OverOp != OO_None && OverOp != OO_Equal)
14216     S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
14217                                    RHS->getType(), Functions);
14218 
14219   // In C++20 onwards, we may have a second operator to look up.
14220   if (S.getLangOpts().CPlusPlus20) {
14221     if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp))
14222       S.LookupOverloadedOperatorName(ExtraOp, Sc, LHS->getType(),
14223                                      RHS->getType(), Functions);
14224   }
14225 
14226   // Build the (potentially-overloaded, potentially-dependent)
14227   // binary operation.
14228   return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
14229 }
14230 
14231 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
14232                             BinaryOperatorKind Opc,
14233                             Expr *LHSExpr, Expr *RHSExpr) {
14234   ExprResult LHS, RHS;
14235   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
14236   if (!LHS.isUsable() || !RHS.isUsable())
14237     return ExprError();
14238   LHSExpr = LHS.get();
14239   RHSExpr = RHS.get();
14240 
14241   // We want to end up calling one of checkPseudoObjectAssignment
14242   // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
14243   // both expressions are overloadable or either is type-dependent),
14244   // or CreateBuiltinBinOp (in any other case).  We also want to get
14245   // any placeholder types out of the way.
14246 
14247   // Handle pseudo-objects in the LHS.
14248   if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
14249     // Assignments with a pseudo-object l-value need special analysis.
14250     if (pty->getKind() == BuiltinType::PseudoObject &&
14251         BinaryOperator::isAssignmentOp(Opc))
14252       return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
14253 
14254     // Don't resolve overloads if the other type is overloadable.
14255     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
14256       // We can't actually test that if we still have a placeholder,
14257       // though.  Fortunately, none of the exceptions we see in that
14258       // code below are valid when the LHS is an overload set.  Note
14259       // that an overload set can be dependently-typed, but it never
14260       // instantiates to having an overloadable type.
14261       ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
14262       if (resolvedRHS.isInvalid()) return ExprError();
14263       RHSExpr = resolvedRHS.get();
14264 
14265       if (RHSExpr->isTypeDependent() ||
14266           RHSExpr->getType()->isOverloadableType())
14267         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14268     }
14269 
14270     // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
14271     // template, diagnose the missing 'template' keyword instead of diagnosing
14272     // an invalid use of a bound member function.
14273     //
14274     // Note that "A::x < b" might be valid if 'b' has an overloadable type due
14275     // to C++1z [over.over]/1.4, but we already checked for that case above.
14276     if (Opc == BO_LT && inTemplateInstantiation() &&
14277         (pty->getKind() == BuiltinType::BoundMember ||
14278          pty->getKind() == BuiltinType::Overload)) {
14279       auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
14280       if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
14281           std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) {
14282             return isa<FunctionTemplateDecl>(ND);
14283           })) {
14284         Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
14285                                 : OE->getNameLoc(),
14286              diag::err_template_kw_missing)
14287           << OE->getName().getAsString() << "";
14288         return ExprError();
14289       }
14290     }
14291 
14292     ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
14293     if (LHS.isInvalid()) return ExprError();
14294     LHSExpr = LHS.get();
14295   }
14296 
14297   // Handle pseudo-objects in the RHS.
14298   if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
14299     // An overload in the RHS can potentially be resolved by the type
14300     // being assigned to.
14301     if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
14302       if (getLangOpts().CPlusPlus &&
14303           (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
14304            LHSExpr->getType()->isOverloadableType()))
14305         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14306 
14307       return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
14308     }
14309 
14310     // Don't resolve overloads if the other type is overloadable.
14311     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
14312         LHSExpr->getType()->isOverloadableType())
14313       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14314 
14315     ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
14316     if (!resolvedRHS.isUsable()) return ExprError();
14317     RHSExpr = resolvedRHS.get();
14318   }
14319 
14320   if (getLangOpts().CPlusPlus) {
14321     // If either expression is type-dependent, always build an
14322     // overloaded op.
14323     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
14324       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14325 
14326     // Otherwise, build an overloaded op if either expression has an
14327     // overloadable type.
14328     if (LHSExpr->getType()->isOverloadableType() ||
14329         RHSExpr->getType()->isOverloadableType())
14330       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14331   }
14332 
14333   // Build a built-in binary operation.
14334   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
14335 }
14336 
14337 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
14338   if (T.isNull() || T->isDependentType())
14339     return false;
14340 
14341   if (!T->isPromotableIntegerType())
14342     return true;
14343 
14344   return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
14345 }
14346 
14347 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
14348                                       UnaryOperatorKind Opc,
14349                                       Expr *InputExpr) {
14350   ExprResult Input = InputExpr;
14351   ExprValueKind VK = VK_RValue;
14352   ExprObjectKind OK = OK_Ordinary;
14353   QualType resultType;
14354   bool CanOverflow = false;
14355 
14356   bool ConvertHalfVec = false;
14357   if (getLangOpts().OpenCL) {
14358     QualType Ty = InputExpr->getType();
14359     // The only legal unary operation for atomics is '&'.
14360     if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
14361     // OpenCL special types - image, sampler, pipe, and blocks are to be used
14362     // only with a builtin functions and therefore should be disallowed here.
14363         (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
14364         || Ty->isBlockPointerType())) {
14365       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14366                        << InputExpr->getType()
14367                        << Input.get()->getSourceRange());
14368     }
14369   }
14370 
14371   switch (Opc) {
14372   case UO_PreInc:
14373   case UO_PreDec:
14374   case UO_PostInc:
14375   case UO_PostDec:
14376     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
14377                                                 OpLoc,
14378                                                 Opc == UO_PreInc ||
14379                                                 Opc == UO_PostInc,
14380                                                 Opc == UO_PreInc ||
14381                                                 Opc == UO_PreDec);
14382     CanOverflow = isOverflowingIntegerType(Context, resultType);
14383     break;
14384   case UO_AddrOf:
14385     resultType = CheckAddressOfOperand(Input, OpLoc);
14386     CheckAddressOfNoDeref(InputExpr);
14387     RecordModifiableNonNullParam(*this, InputExpr);
14388     break;
14389   case UO_Deref: {
14390     Input = DefaultFunctionArrayLvalueConversion(Input.get());
14391     if (Input.isInvalid()) return ExprError();
14392     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
14393     break;
14394   }
14395   case UO_Plus:
14396   case UO_Minus:
14397     CanOverflow = Opc == UO_Minus &&
14398                   isOverflowingIntegerType(Context, Input.get()->getType());
14399     Input = UsualUnaryConversions(Input.get());
14400     if (Input.isInvalid()) return ExprError();
14401     // Unary plus and minus require promoting an operand of half vector to a
14402     // float vector and truncating the result back to a half vector. For now, we
14403     // do this only when HalfArgsAndReturns is set (that is, when the target is
14404     // arm or arm64).
14405     ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get());
14406 
14407     // If the operand is a half vector, promote it to a float vector.
14408     if (ConvertHalfVec)
14409       Input = convertVector(Input.get(), Context.FloatTy, *this);
14410     resultType = Input.get()->getType();
14411     if (resultType->isDependentType())
14412       break;
14413     if (resultType->isArithmeticType()) // C99 6.5.3.3p1
14414       break;
14415     else if (resultType->isVectorType() &&
14416              // The z vector extensions don't allow + or - with bool vectors.
14417              (!Context.getLangOpts().ZVector ||
14418               resultType->castAs<VectorType>()->getVectorKind() !=
14419               VectorType::AltiVecBool))
14420       break;
14421     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
14422              Opc == UO_Plus &&
14423              resultType->isPointerType())
14424       break;
14425 
14426     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14427       << resultType << Input.get()->getSourceRange());
14428 
14429   case UO_Not: // bitwise complement
14430     Input = UsualUnaryConversions(Input.get());
14431     if (Input.isInvalid())
14432       return ExprError();
14433     resultType = Input.get()->getType();
14434     if (resultType->isDependentType())
14435       break;
14436     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
14437     if (resultType->isComplexType() || resultType->isComplexIntegerType())
14438       // C99 does not support '~' for complex conjugation.
14439       Diag(OpLoc, diag::ext_integer_complement_complex)
14440           << resultType << Input.get()->getSourceRange();
14441     else if (resultType->hasIntegerRepresentation())
14442       break;
14443     else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
14444       // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
14445       // on vector float types.
14446       QualType T = resultType->castAs<ExtVectorType>()->getElementType();
14447       if (!T->isIntegerType())
14448         return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14449                           << resultType << Input.get()->getSourceRange());
14450     } else {
14451       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14452                        << resultType << Input.get()->getSourceRange());
14453     }
14454     break;
14455 
14456   case UO_LNot: // logical negation
14457     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
14458     Input = DefaultFunctionArrayLvalueConversion(Input.get());
14459     if (Input.isInvalid()) return ExprError();
14460     resultType = Input.get()->getType();
14461 
14462     // Though we still have to promote half FP to float...
14463     if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
14464       Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
14465       resultType = Context.FloatTy;
14466     }
14467 
14468     if (resultType->isDependentType())
14469       break;
14470     if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
14471       // C99 6.5.3.3p1: ok, fallthrough;
14472       if (Context.getLangOpts().CPlusPlus) {
14473         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
14474         // operand contextually converted to bool.
14475         Input = ImpCastExprToType(Input.get(), Context.BoolTy,
14476                                   ScalarTypeToBooleanCastKind(resultType));
14477       } else if (Context.getLangOpts().OpenCL &&
14478                  Context.getLangOpts().OpenCLVersion < 120) {
14479         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
14480         // operate on scalar float types.
14481         if (!resultType->isIntegerType() && !resultType->isPointerType())
14482           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14483                            << resultType << Input.get()->getSourceRange());
14484       }
14485     } else if (resultType->isExtVectorType()) {
14486       if (Context.getLangOpts().OpenCL &&
14487           Context.getLangOpts().OpenCLVersion < 120 &&
14488           !Context.getLangOpts().OpenCLCPlusPlus) {
14489         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
14490         // operate on vector float types.
14491         QualType T = resultType->castAs<ExtVectorType>()->getElementType();
14492         if (!T->isIntegerType())
14493           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14494                            << resultType << Input.get()->getSourceRange());
14495       }
14496       // Vector logical not returns the signed variant of the operand type.
14497       resultType = GetSignedVectorType(resultType);
14498       break;
14499     } else if (Context.getLangOpts().CPlusPlus && resultType->isVectorType()) {
14500       const VectorType *VTy = resultType->castAs<VectorType>();
14501       if (VTy->getVectorKind() != VectorType::GenericVector)
14502         return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14503                          << resultType << Input.get()->getSourceRange());
14504 
14505       // Vector logical not returns the signed variant of the operand type.
14506       resultType = GetSignedVectorType(resultType);
14507       break;
14508     } else {
14509       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14510         << resultType << Input.get()->getSourceRange());
14511     }
14512 
14513     // LNot always has type int. C99 6.5.3.3p5.
14514     // In C++, it's bool. C++ 5.3.1p8
14515     resultType = Context.getLogicalOperationType();
14516     break;
14517   case UO_Real:
14518   case UO_Imag:
14519     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
14520     // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
14521     // complex l-values to ordinary l-values and all other values to r-values.
14522     if (Input.isInvalid()) return ExprError();
14523     if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
14524       if (Input.get()->getValueKind() != VK_RValue &&
14525           Input.get()->getObjectKind() == OK_Ordinary)
14526         VK = Input.get()->getValueKind();
14527     } else if (!getLangOpts().CPlusPlus) {
14528       // In C, a volatile scalar is read by __imag. In C++, it is not.
14529       Input = DefaultLvalueConversion(Input.get());
14530     }
14531     break;
14532   case UO_Extension:
14533     resultType = Input.get()->getType();
14534     VK = Input.get()->getValueKind();
14535     OK = Input.get()->getObjectKind();
14536     break;
14537   case UO_Coawait:
14538     // It's unnecessary to represent the pass-through operator co_await in the
14539     // AST; just return the input expression instead.
14540     assert(!Input.get()->getType()->isDependentType() &&
14541                    "the co_await expression must be non-dependant before "
14542                    "building operator co_await");
14543     return Input;
14544   }
14545   if (resultType.isNull() || Input.isInvalid())
14546     return ExprError();
14547 
14548   // Check for array bounds violations in the operand of the UnaryOperator,
14549   // except for the '*' and '&' operators that have to be handled specially
14550   // by CheckArrayAccess (as there are special cases like &array[arraysize]
14551   // that are explicitly defined as valid by the standard).
14552   if (Opc != UO_AddrOf && Opc != UO_Deref)
14553     CheckArrayAccess(Input.get());
14554 
14555   auto *UO = UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK,
14556                                    OK, OpLoc, CanOverflow, CurFPFeatures);
14557 
14558   if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) &&
14559       !isa<ArrayType>(UO->getType().getDesugaredType(Context)))
14560     ExprEvalContexts.back().PossibleDerefs.insert(UO);
14561 
14562   // Convert the result back to a half vector.
14563   if (ConvertHalfVec)
14564     return convertVector(UO, Context.HalfTy, *this);
14565   return UO;
14566 }
14567 
14568 /// Determine whether the given expression is a qualified member
14569 /// access expression, of a form that could be turned into a pointer to member
14570 /// with the address-of operator.
14571 bool Sema::isQualifiedMemberAccess(Expr *E) {
14572   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
14573     if (!DRE->getQualifier())
14574       return false;
14575 
14576     ValueDecl *VD = DRE->getDecl();
14577     if (!VD->isCXXClassMember())
14578       return false;
14579 
14580     if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
14581       return true;
14582     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
14583       return Method->isInstance();
14584 
14585     return false;
14586   }
14587 
14588   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
14589     if (!ULE->getQualifier())
14590       return false;
14591 
14592     for (NamedDecl *D : ULE->decls()) {
14593       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
14594         if (Method->isInstance())
14595           return true;
14596       } else {
14597         // Overload set does not contain methods.
14598         break;
14599       }
14600     }
14601 
14602     return false;
14603   }
14604 
14605   return false;
14606 }
14607 
14608 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
14609                               UnaryOperatorKind Opc, Expr *Input) {
14610   // First things first: handle placeholders so that the
14611   // overloaded-operator check considers the right type.
14612   if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
14613     // Increment and decrement of pseudo-object references.
14614     if (pty->getKind() == BuiltinType::PseudoObject &&
14615         UnaryOperator::isIncrementDecrementOp(Opc))
14616       return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
14617 
14618     // extension is always a builtin operator.
14619     if (Opc == UO_Extension)
14620       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
14621 
14622     // & gets special logic for several kinds of placeholder.
14623     // The builtin code knows what to do.
14624     if (Opc == UO_AddrOf &&
14625         (pty->getKind() == BuiltinType::Overload ||
14626          pty->getKind() == BuiltinType::UnknownAny ||
14627          pty->getKind() == BuiltinType::BoundMember))
14628       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
14629 
14630     // Anything else needs to be handled now.
14631     ExprResult Result = CheckPlaceholderExpr(Input);
14632     if (Result.isInvalid()) return ExprError();
14633     Input = Result.get();
14634   }
14635 
14636   if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
14637       UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
14638       !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
14639     // Find all of the overloaded operators visible from this
14640     // point. We perform both an operator-name lookup from the local
14641     // scope and an argument-dependent lookup based on the types of
14642     // the arguments.
14643     UnresolvedSet<16> Functions;
14644     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
14645     if (S && OverOp != OO_None)
14646       LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
14647                                    Functions);
14648 
14649     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
14650   }
14651 
14652   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
14653 }
14654 
14655 // Unary Operators.  'Tok' is the token for the operator.
14656 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
14657                               tok::TokenKind Op, Expr *Input) {
14658   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
14659 }
14660 
14661 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
14662 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
14663                                 LabelDecl *TheDecl) {
14664   TheDecl->markUsed(Context);
14665   // Create the AST node.  The address of a label always has type 'void*'.
14666   return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
14667                                      Context.getPointerType(Context.VoidTy));
14668 }
14669 
14670 void Sema::ActOnStartStmtExpr() {
14671   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
14672 }
14673 
14674 void Sema::ActOnStmtExprError() {
14675   // Note that function is also called by TreeTransform when leaving a
14676   // StmtExpr scope without rebuilding anything.
14677 
14678   DiscardCleanupsInEvaluationContext();
14679   PopExpressionEvaluationContext();
14680 }
14681 
14682 ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt,
14683                                SourceLocation RPLoc) {
14684   return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S));
14685 }
14686 
14687 ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
14688                                SourceLocation RPLoc, unsigned TemplateDepth) {
14689   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
14690   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
14691 
14692   if (hasAnyUnrecoverableErrorsInThisFunction())
14693     DiscardCleanupsInEvaluationContext();
14694   assert(!Cleanup.exprNeedsCleanups() &&
14695          "cleanups within StmtExpr not correctly bound!");
14696   PopExpressionEvaluationContext();
14697 
14698   // FIXME: there are a variety of strange constraints to enforce here, for
14699   // example, it is not possible to goto into a stmt expression apparently.
14700   // More semantic analysis is needed.
14701 
14702   // If there are sub-stmts in the compound stmt, take the type of the last one
14703   // as the type of the stmtexpr.
14704   QualType Ty = Context.VoidTy;
14705   bool StmtExprMayBindToTemp = false;
14706   if (!Compound->body_empty()) {
14707     // For GCC compatibility we get the last Stmt excluding trailing NullStmts.
14708     if (const auto *LastStmt =
14709             dyn_cast<ValueStmt>(Compound->getStmtExprResult())) {
14710       if (const Expr *Value = LastStmt->getExprStmt()) {
14711         StmtExprMayBindToTemp = true;
14712         Ty = Value->getType();
14713       }
14714     }
14715   }
14716 
14717   // FIXME: Check that expression type is complete/non-abstract; statement
14718   // expressions are not lvalues.
14719   Expr *ResStmtExpr =
14720       new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth);
14721   if (StmtExprMayBindToTemp)
14722     return MaybeBindToTemporary(ResStmtExpr);
14723   return ResStmtExpr;
14724 }
14725 
14726 ExprResult Sema::ActOnStmtExprResult(ExprResult ER) {
14727   if (ER.isInvalid())
14728     return ExprError();
14729 
14730   // Do function/array conversion on the last expression, but not
14731   // lvalue-to-rvalue.  However, initialize an unqualified type.
14732   ER = DefaultFunctionArrayConversion(ER.get());
14733   if (ER.isInvalid())
14734     return ExprError();
14735   Expr *E = ER.get();
14736 
14737   if (E->isTypeDependent())
14738     return E;
14739 
14740   // In ARC, if the final expression ends in a consume, splice
14741   // the consume out and bind it later.  In the alternate case
14742   // (when dealing with a retainable type), the result
14743   // initialization will create a produce.  In both cases the
14744   // result will be +1, and we'll need to balance that out with
14745   // a bind.
14746   auto *Cast = dyn_cast<ImplicitCastExpr>(E);
14747   if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
14748     return Cast->getSubExpr();
14749 
14750   // FIXME: Provide a better location for the initialization.
14751   return PerformCopyInitialization(
14752       InitializedEntity::InitializeStmtExprResult(
14753           E->getBeginLoc(), E->getType().getUnqualifiedType()),
14754       SourceLocation(), E);
14755 }
14756 
14757 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
14758                                       TypeSourceInfo *TInfo,
14759                                       ArrayRef<OffsetOfComponent> Components,
14760                                       SourceLocation RParenLoc) {
14761   QualType ArgTy = TInfo->getType();
14762   bool Dependent = ArgTy->isDependentType();
14763   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
14764 
14765   // We must have at least one component that refers to the type, and the first
14766   // one is known to be a field designator.  Verify that the ArgTy represents
14767   // a struct/union/class.
14768   if (!Dependent && !ArgTy->isRecordType())
14769     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
14770                        << ArgTy << TypeRange);
14771 
14772   // Type must be complete per C99 7.17p3 because a declaring a variable
14773   // with an incomplete type would be ill-formed.
14774   if (!Dependent
14775       && RequireCompleteType(BuiltinLoc, ArgTy,
14776                              diag::err_offsetof_incomplete_type, TypeRange))
14777     return ExprError();
14778 
14779   bool DidWarnAboutNonPOD = false;
14780   QualType CurrentType = ArgTy;
14781   SmallVector<OffsetOfNode, 4> Comps;
14782   SmallVector<Expr*, 4> Exprs;
14783   for (const OffsetOfComponent &OC : Components) {
14784     if (OC.isBrackets) {
14785       // Offset of an array sub-field.  TODO: Should we allow vector elements?
14786       if (!CurrentType->isDependentType()) {
14787         const ArrayType *AT = Context.getAsArrayType(CurrentType);
14788         if(!AT)
14789           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
14790                            << CurrentType);
14791         CurrentType = AT->getElementType();
14792       } else
14793         CurrentType = Context.DependentTy;
14794 
14795       ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
14796       if (IdxRval.isInvalid())
14797         return ExprError();
14798       Expr *Idx = IdxRval.get();
14799 
14800       // The expression must be an integral expression.
14801       // FIXME: An integral constant expression?
14802       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
14803           !Idx->getType()->isIntegerType())
14804         return ExprError(
14805             Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer)
14806             << Idx->getSourceRange());
14807 
14808       // Record this array index.
14809       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
14810       Exprs.push_back(Idx);
14811       continue;
14812     }
14813 
14814     // Offset of a field.
14815     if (CurrentType->isDependentType()) {
14816       // We have the offset of a field, but we can't look into the dependent
14817       // type. Just record the identifier of the field.
14818       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
14819       CurrentType = Context.DependentTy;
14820       continue;
14821     }
14822 
14823     // We need to have a complete type to look into.
14824     if (RequireCompleteType(OC.LocStart, CurrentType,
14825                             diag::err_offsetof_incomplete_type))
14826       return ExprError();
14827 
14828     // Look for the designated field.
14829     const RecordType *RC = CurrentType->getAs<RecordType>();
14830     if (!RC)
14831       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
14832                        << CurrentType);
14833     RecordDecl *RD = RC->getDecl();
14834 
14835     // C++ [lib.support.types]p5:
14836     //   The macro offsetof accepts a restricted set of type arguments in this
14837     //   International Standard. type shall be a POD structure or a POD union
14838     //   (clause 9).
14839     // C++11 [support.types]p4:
14840     //   If type is not a standard-layout class (Clause 9), the results are
14841     //   undefined.
14842     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
14843       bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
14844       unsigned DiagID =
14845         LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
14846                             : diag::ext_offsetof_non_pod_type;
14847 
14848       if (!IsSafe && !DidWarnAboutNonPOD &&
14849           DiagRuntimeBehavior(BuiltinLoc, nullptr,
14850                               PDiag(DiagID)
14851                               << SourceRange(Components[0].LocStart, OC.LocEnd)
14852                               << CurrentType))
14853         DidWarnAboutNonPOD = true;
14854     }
14855 
14856     // Look for the field.
14857     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
14858     LookupQualifiedName(R, RD);
14859     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
14860     IndirectFieldDecl *IndirectMemberDecl = nullptr;
14861     if (!MemberDecl) {
14862       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
14863         MemberDecl = IndirectMemberDecl->getAnonField();
14864     }
14865 
14866     if (!MemberDecl)
14867       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
14868                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
14869                                                               OC.LocEnd));
14870 
14871     // C99 7.17p3:
14872     //   (If the specified member is a bit-field, the behavior is undefined.)
14873     //
14874     // We diagnose this as an error.
14875     if (MemberDecl->isBitField()) {
14876       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
14877         << MemberDecl->getDeclName()
14878         << SourceRange(BuiltinLoc, RParenLoc);
14879       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
14880       return ExprError();
14881     }
14882 
14883     RecordDecl *Parent = MemberDecl->getParent();
14884     if (IndirectMemberDecl)
14885       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
14886 
14887     // If the member was found in a base class, introduce OffsetOfNodes for
14888     // the base class indirections.
14889     CXXBasePaths Paths;
14890     if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
14891                       Paths)) {
14892       if (Paths.getDetectedVirtual()) {
14893         Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
14894           << MemberDecl->getDeclName()
14895           << SourceRange(BuiltinLoc, RParenLoc);
14896         return ExprError();
14897       }
14898 
14899       CXXBasePath &Path = Paths.front();
14900       for (const CXXBasePathElement &B : Path)
14901         Comps.push_back(OffsetOfNode(B.Base));
14902     }
14903 
14904     if (IndirectMemberDecl) {
14905       for (auto *FI : IndirectMemberDecl->chain()) {
14906         assert(isa<FieldDecl>(FI));
14907         Comps.push_back(OffsetOfNode(OC.LocStart,
14908                                      cast<FieldDecl>(FI), OC.LocEnd));
14909       }
14910     } else
14911       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
14912 
14913     CurrentType = MemberDecl->getType().getNonReferenceType();
14914   }
14915 
14916   return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
14917                               Comps, Exprs, RParenLoc);
14918 }
14919 
14920 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
14921                                       SourceLocation BuiltinLoc,
14922                                       SourceLocation TypeLoc,
14923                                       ParsedType ParsedArgTy,
14924                                       ArrayRef<OffsetOfComponent> Components,
14925                                       SourceLocation RParenLoc) {
14926 
14927   TypeSourceInfo *ArgTInfo;
14928   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
14929   if (ArgTy.isNull())
14930     return ExprError();
14931 
14932   if (!ArgTInfo)
14933     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
14934 
14935   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
14936 }
14937 
14938 
14939 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
14940                                  Expr *CondExpr,
14941                                  Expr *LHSExpr, Expr *RHSExpr,
14942                                  SourceLocation RPLoc) {
14943   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
14944 
14945   ExprValueKind VK = VK_RValue;
14946   ExprObjectKind OK = OK_Ordinary;
14947   QualType resType;
14948   bool CondIsTrue = false;
14949   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
14950     resType = Context.DependentTy;
14951   } else {
14952     // The conditional expression is required to be a constant expression.
14953     llvm::APSInt condEval(32);
14954     ExprResult CondICE
14955       = VerifyIntegerConstantExpression(CondExpr, &condEval,
14956           diag::err_typecheck_choose_expr_requires_constant, false);
14957     if (CondICE.isInvalid())
14958       return ExprError();
14959     CondExpr = CondICE.get();
14960     CondIsTrue = condEval.getZExtValue();
14961 
14962     // If the condition is > zero, then the AST type is the same as the LHSExpr.
14963     Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
14964 
14965     resType = ActiveExpr->getType();
14966     VK = ActiveExpr->getValueKind();
14967     OK = ActiveExpr->getObjectKind();
14968   }
14969 
14970   return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
14971                                   resType, VK, OK, RPLoc, CondIsTrue);
14972 }
14973 
14974 //===----------------------------------------------------------------------===//
14975 // Clang Extensions.
14976 //===----------------------------------------------------------------------===//
14977 
14978 /// ActOnBlockStart - This callback is invoked when a block literal is started.
14979 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
14980   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
14981 
14982   if (LangOpts.CPlusPlus) {
14983     MangleNumberingContext *MCtx;
14984     Decl *ManglingContextDecl;
14985     std::tie(MCtx, ManglingContextDecl) =
14986         getCurrentMangleNumberContext(Block->getDeclContext());
14987     if (MCtx) {
14988       unsigned ManglingNumber = MCtx->getManglingNumber(Block);
14989       Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
14990     }
14991   }
14992 
14993   PushBlockScope(CurScope, Block);
14994   CurContext->addDecl(Block);
14995   if (CurScope)
14996     PushDeclContext(CurScope, Block);
14997   else
14998     CurContext = Block;
14999 
15000   getCurBlock()->HasImplicitReturnType = true;
15001 
15002   // Enter a new evaluation context to insulate the block from any
15003   // cleanups from the enclosing full-expression.
15004   PushExpressionEvaluationContext(
15005       ExpressionEvaluationContext::PotentiallyEvaluated);
15006 }
15007 
15008 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
15009                                Scope *CurScope) {
15010   assert(ParamInfo.getIdentifier() == nullptr &&
15011          "block-id should have no identifier!");
15012   assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteralContext);
15013   BlockScopeInfo *CurBlock = getCurBlock();
15014 
15015   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
15016   QualType T = Sig->getType();
15017 
15018   // FIXME: We should allow unexpanded parameter packs here, but that would,
15019   // in turn, make the block expression contain unexpanded parameter packs.
15020   if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
15021     // Drop the parameters.
15022     FunctionProtoType::ExtProtoInfo EPI;
15023     EPI.HasTrailingReturn = false;
15024     EPI.TypeQuals.addConst();
15025     T = Context.getFunctionType(Context.DependentTy, None, EPI);
15026     Sig = Context.getTrivialTypeSourceInfo(T);
15027   }
15028 
15029   // GetTypeForDeclarator always produces a function type for a block
15030   // literal signature.  Furthermore, it is always a FunctionProtoType
15031   // unless the function was written with a typedef.
15032   assert(T->isFunctionType() &&
15033          "GetTypeForDeclarator made a non-function block signature");
15034 
15035   // Look for an explicit signature in that function type.
15036   FunctionProtoTypeLoc ExplicitSignature;
15037 
15038   if ((ExplicitSignature = Sig->getTypeLoc()
15039                                .getAsAdjusted<FunctionProtoTypeLoc>())) {
15040 
15041     // Check whether that explicit signature was synthesized by
15042     // GetTypeForDeclarator.  If so, don't save that as part of the
15043     // written signature.
15044     if (ExplicitSignature.getLocalRangeBegin() ==
15045         ExplicitSignature.getLocalRangeEnd()) {
15046       // This would be much cheaper if we stored TypeLocs instead of
15047       // TypeSourceInfos.
15048       TypeLoc Result = ExplicitSignature.getReturnLoc();
15049       unsigned Size = Result.getFullDataSize();
15050       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
15051       Sig->getTypeLoc().initializeFullCopy(Result, Size);
15052 
15053       ExplicitSignature = FunctionProtoTypeLoc();
15054     }
15055   }
15056 
15057   CurBlock->TheDecl->setSignatureAsWritten(Sig);
15058   CurBlock->FunctionType = T;
15059 
15060   const FunctionType *Fn = T->getAs<FunctionType>();
15061   QualType RetTy = Fn->getReturnType();
15062   bool isVariadic =
15063     (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
15064 
15065   CurBlock->TheDecl->setIsVariadic(isVariadic);
15066 
15067   // Context.DependentTy is used as a placeholder for a missing block
15068   // return type.  TODO:  what should we do with declarators like:
15069   //   ^ * { ... }
15070   // If the answer is "apply template argument deduction"....
15071   if (RetTy != Context.DependentTy) {
15072     CurBlock->ReturnType = RetTy;
15073     CurBlock->TheDecl->setBlockMissingReturnType(false);
15074     CurBlock->HasImplicitReturnType = false;
15075   }
15076 
15077   // Push block parameters from the declarator if we had them.
15078   SmallVector<ParmVarDecl*, 8> Params;
15079   if (ExplicitSignature) {
15080     for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
15081       ParmVarDecl *Param = ExplicitSignature.getParam(I);
15082       if (Param->getIdentifier() == nullptr && !Param->isImplicit() &&
15083           !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) {
15084         // Diagnose this as an extension in C17 and earlier.
15085         if (!getLangOpts().C2x)
15086           Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x);
15087       }
15088       Params.push_back(Param);
15089     }
15090 
15091   // Fake up parameter variables if we have a typedef, like
15092   //   ^ fntype { ... }
15093   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
15094     for (const auto &I : Fn->param_types()) {
15095       ParmVarDecl *Param = BuildParmVarDeclForTypedef(
15096           CurBlock->TheDecl, ParamInfo.getBeginLoc(), I);
15097       Params.push_back(Param);
15098     }
15099   }
15100 
15101   // Set the parameters on the block decl.
15102   if (!Params.empty()) {
15103     CurBlock->TheDecl->setParams(Params);
15104     CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
15105                              /*CheckParameterNames=*/false);
15106   }
15107 
15108   // Finally we can process decl attributes.
15109   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
15110 
15111   // Put the parameter variables in scope.
15112   for (auto AI : CurBlock->TheDecl->parameters()) {
15113     AI->setOwningFunction(CurBlock->TheDecl);
15114 
15115     // If this has an identifier, add it to the scope stack.
15116     if (AI->getIdentifier()) {
15117       CheckShadow(CurBlock->TheScope, AI);
15118 
15119       PushOnScopeChains(AI, CurBlock->TheScope);
15120     }
15121   }
15122 }
15123 
15124 /// ActOnBlockError - If there is an error parsing a block, this callback
15125 /// is invoked to pop the information about the block from the action impl.
15126 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
15127   // Leave the expression-evaluation context.
15128   DiscardCleanupsInEvaluationContext();
15129   PopExpressionEvaluationContext();
15130 
15131   // Pop off CurBlock, handle nested blocks.
15132   PopDeclContext();
15133   PopFunctionScopeInfo();
15134 }
15135 
15136 /// ActOnBlockStmtExpr - This is called when the body of a block statement
15137 /// literal was successfully completed.  ^(int x){...}
15138 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
15139                                     Stmt *Body, Scope *CurScope) {
15140   // If blocks are disabled, emit an error.
15141   if (!LangOpts.Blocks)
15142     Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
15143 
15144   // Leave the expression-evaluation context.
15145   if (hasAnyUnrecoverableErrorsInThisFunction())
15146     DiscardCleanupsInEvaluationContext();
15147   assert(!Cleanup.exprNeedsCleanups() &&
15148          "cleanups within block not correctly bound!");
15149   PopExpressionEvaluationContext();
15150 
15151   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
15152   BlockDecl *BD = BSI->TheDecl;
15153 
15154   if (BSI->HasImplicitReturnType)
15155     deduceClosureReturnType(*BSI);
15156 
15157   QualType RetTy = Context.VoidTy;
15158   if (!BSI->ReturnType.isNull())
15159     RetTy = BSI->ReturnType;
15160 
15161   bool NoReturn = BD->hasAttr<NoReturnAttr>();
15162   QualType BlockTy;
15163 
15164   // If the user wrote a function type in some form, try to use that.
15165   if (!BSI->FunctionType.isNull()) {
15166     const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>();
15167 
15168     FunctionType::ExtInfo Ext = FTy->getExtInfo();
15169     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
15170 
15171     // Turn protoless block types into nullary block types.
15172     if (isa<FunctionNoProtoType>(FTy)) {
15173       FunctionProtoType::ExtProtoInfo EPI;
15174       EPI.ExtInfo = Ext;
15175       BlockTy = Context.getFunctionType(RetTy, None, EPI);
15176 
15177     // Otherwise, if we don't need to change anything about the function type,
15178     // preserve its sugar structure.
15179     } else if (FTy->getReturnType() == RetTy &&
15180                (!NoReturn || FTy->getNoReturnAttr())) {
15181       BlockTy = BSI->FunctionType;
15182 
15183     // Otherwise, make the minimal modifications to the function type.
15184     } else {
15185       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
15186       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
15187       EPI.TypeQuals = Qualifiers();
15188       EPI.ExtInfo = Ext;
15189       BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
15190     }
15191 
15192   // If we don't have a function type, just build one from nothing.
15193   } else {
15194     FunctionProtoType::ExtProtoInfo EPI;
15195     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
15196     BlockTy = Context.getFunctionType(RetTy, None, EPI);
15197   }
15198 
15199   DiagnoseUnusedParameters(BD->parameters());
15200   BlockTy = Context.getBlockPointerType(BlockTy);
15201 
15202   // If needed, diagnose invalid gotos and switches in the block.
15203   if (getCurFunction()->NeedsScopeChecking() &&
15204       !PP.isCodeCompletionEnabled())
15205     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
15206 
15207   BD->setBody(cast<CompoundStmt>(Body));
15208 
15209   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
15210     DiagnoseUnguardedAvailabilityViolations(BD);
15211 
15212   // Try to apply the named return value optimization. We have to check again
15213   // if we can do this, though, because blocks keep return statements around
15214   // to deduce an implicit return type.
15215   if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
15216       !BD->isDependentContext())
15217     computeNRVO(Body, BSI);
15218 
15219   if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() ||
15220       RetTy.hasNonTrivialToPrimitiveCopyCUnion())
15221     checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn,
15222                           NTCUK_Destruct|NTCUK_Copy);
15223 
15224   PopDeclContext();
15225 
15226   // Pop the block scope now but keep it alive to the end of this function.
15227   AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
15228   PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy);
15229 
15230   // Set the captured variables on the block.
15231   SmallVector<BlockDecl::Capture, 4> Captures;
15232   for (Capture &Cap : BSI->Captures) {
15233     if (Cap.isInvalid() || Cap.isThisCapture())
15234       continue;
15235 
15236     VarDecl *Var = Cap.getVariable();
15237     Expr *CopyExpr = nullptr;
15238     if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) {
15239       if (const RecordType *Record =
15240               Cap.getCaptureType()->getAs<RecordType>()) {
15241         // The capture logic needs the destructor, so make sure we mark it.
15242         // Usually this is unnecessary because most local variables have
15243         // their destructors marked at declaration time, but parameters are
15244         // an exception because it's technically only the call site that
15245         // actually requires the destructor.
15246         if (isa<ParmVarDecl>(Var))
15247           FinalizeVarWithDestructor(Var, Record);
15248 
15249         // Enter a separate potentially-evaluated context while building block
15250         // initializers to isolate their cleanups from those of the block
15251         // itself.
15252         // FIXME: Is this appropriate even when the block itself occurs in an
15253         // unevaluated operand?
15254         EnterExpressionEvaluationContext EvalContext(
15255             *this, ExpressionEvaluationContext::PotentiallyEvaluated);
15256 
15257         SourceLocation Loc = Cap.getLocation();
15258 
15259         ExprResult Result = BuildDeclarationNameExpr(
15260             CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
15261 
15262         // According to the blocks spec, the capture of a variable from
15263         // the stack requires a const copy constructor.  This is not true
15264         // of the copy/move done to move a __block variable to the heap.
15265         if (!Result.isInvalid() &&
15266             !Result.get()->getType().isConstQualified()) {
15267           Result = ImpCastExprToType(Result.get(),
15268                                      Result.get()->getType().withConst(),
15269                                      CK_NoOp, VK_LValue);
15270         }
15271 
15272         if (!Result.isInvalid()) {
15273           Result = PerformCopyInitialization(
15274               InitializedEntity::InitializeBlock(Var->getLocation(),
15275                                                  Cap.getCaptureType(), false),
15276               Loc, Result.get());
15277         }
15278 
15279         // Build a full-expression copy expression if initialization
15280         // succeeded and used a non-trivial constructor.  Recover from
15281         // errors by pretending that the copy isn't necessary.
15282         if (!Result.isInvalid() &&
15283             !cast<CXXConstructExpr>(Result.get())->getConstructor()
15284                 ->isTrivial()) {
15285           Result = MaybeCreateExprWithCleanups(Result);
15286           CopyExpr = Result.get();
15287         }
15288       }
15289     }
15290 
15291     BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(),
15292                               CopyExpr);
15293     Captures.push_back(NewCap);
15294   }
15295   BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
15296 
15297   BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy);
15298 
15299   // If the block isn't obviously global, i.e. it captures anything at
15300   // all, then we need to do a few things in the surrounding context:
15301   if (Result->getBlockDecl()->hasCaptures()) {
15302     // First, this expression has a new cleanup object.
15303     ExprCleanupObjects.push_back(Result->getBlockDecl());
15304     Cleanup.setExprNeedsCleanups(true);
15305 
15306     // It also gets a branch-protected scope if any of the captured
15307     // variables needs destruction.
15308     for (const auto &CI : Result->getBlockDecl()->captures()) {
15309       const VarDecl *var = CI.getVariable();
15310       if (var->getType().isDestructedType() != QualType::DK_none) {
15311         setFunctionHasBranchProtectedScope();
15312         break;
15313       }
15314     }
15315   }
15316 
15317   if (getCurFunction())
15318     getCurFunction()->addBlock(BD);
15319 
15320   return Result;
15321 }
15322 
15323 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
15324                             SourceLocation RPLoc) {
15325   TypeSourceInfo *TInfo;
15326   GetTypeFromParser(Ty, &TInfo);
15327   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
15328 }
15329 
15330 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
15331                                 Expr *E, TypeSourceInfo *TInfo,
15332                                 SourceLocation RPLoc) {
15333   Expr *OrigExpr = E;
15334   bool IsMS = false;
15335 
15336   // CUDA device code does not support varargs.
15337   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
15338     if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
15339       CUDAFunctionTarget T = IdentifyCUDATarget(F);
15340       if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
15341         return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device));
15342     }
15343   }
15344 
15345   // NVPTX does not support va_arg expression.
15346   if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
15347       Context.getTargetInfo().getTriple().isNVPTX())
15348     targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device);
15349 
15350   // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
15351   // as Microsoft ABI on an actual Microsoft platform, where
15352   // __builtin_ms_va_list and __builtin_va_list are the same.)
15353   if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
15354       Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
15355     QualType MSVaListType = Context.getBuiltinMSVaListType();
15356     if (Context.hasSameType(MSVaListType, E->getType())) {
15357       if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
15358         return ExprError();
15359       IsMS = true;
15360     }
15361   }
15362 
15363   // Get the va_list type
15364   QualType VaListType = Context.getBuiltinVaListType();
15365   if (!IsMS) {
15366     if (VaListType->isArrayType()) {
15367       // Deal with implicit array decay; for example, on x86-64,
15368       // va_list is an array, but it's supposed to decay to
15369       // a pointer for va_arg.
15370       VaListType = Context.getArrayDecayedType(VaListType);
15371       // Make sure the input expression also decays appropriately.
15372       ExprResult Result = UsualUnaryConversions(E);
15373       if (Result.isInvalid())
15374         return ExprError();
15375       E = Result.get();
15376     } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
15377       // If va_list is a record type and we are compiling in C++ mode,
15378       // check the argument using reference binding.
15379       InitializedEntity Entity = InitializedEntity::InitializeParameter(
15380           Context, Context.getLValueReferenceType(VaListType), false);
15381       ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
15382       if (Init.isInvalid())
15383         return ExprError();
15384       E = Init.getAs<Expr>();
15385     } else {
15386       // Otherwise, the va_list argument must be an l-value because
15387       // it is modified by va_arg.
15388       if (!E->isTypeDependent() &&
15389           CheckForModifiableLvalue(E, BuiltinLoc, *this))
15390         return ExprError();
15391     }
15392   }
15393 
15394   if (!IsMS && !E->isTypeDependent() &&
15395       !Context.hasSameType(VaListType, E->getType()))
15396     return ExprError(
15397         Diag(E->getBeginLoc(),
15398              diag::err_first_argument_to_va_arg_not_of_type_va_list)
15399         << OrigExpr->getType() << E->getSourceRange());
15400 
15401   if (!TInfo->getType()->isDependentType()) {
15402     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
15403                             diag::err_second_parameter_to_va_arg_incomplete,
15404                             TInfo->getTypeLoc()))
15405       return ExprError();
15406 
15407     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
15408                                TInfo->getType(),
15409                                diag::err_second_parameter_to_va_arg_abstract,
15410                                TInfo->getTypeLoc()))
15411       return ExprError();
15412 
15413     if (!TInfo->getType().isPODType(Context)) {
15414       Diag(TInfo->getTypeLoc().getBeginLoc(),
15415            TInfo->getType()->isObjCLifetimeType()
15416              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
15417              : diag::warn_second_parameter_to_va_arg_not_pod)
15418         << TInfo->getType()
15419         << TInfo->getTypeLoc().getSourceRange();
15420     }
15421 
15422     // Check for va_arg where arguments of the given type will be promoted
15423     // (i.e. this va_arg is guaranteed to have undefined behavior).
15424     QualType PromoteType;
15425     if (TInfo->getType()->isPromotableIntegerType()) {
15426       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
15427       if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
15428         PromoteType = QualType();
15429     }
15430     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
15431       PromoteType = Context.DoubleTy;
15432     if (!PromoteType.isNull())
15433       DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
15434                   PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
15435                           << TInfo->getType()
15436                           << PromoteType
15437                           << TInfo->getTypeLoc().getSourceRange());
15438   }
15439 
15440   QualType T = TInfo->getType().getNonLValueExprType(Context);
15441   return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
15442 }
15443 
15444 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
15445   // The type of __null will be int or long, depending on the size of
15446   // pointers on the target.
15447   QualType Ty;
15448   unsigned pw = Context.getTargetInfo().getPointerWidth(0);
15449   if (pw == Context.getTargetInfo().getIntWidth())
15450     Ty = Context.IntTy;
15451   else if (pw == Context.getTargetInfo().getLongWidth())
15452     Ty = Context.LongTy;
15453   else if (pw == Context.getTargetInfo().getLongLongWidth())
15454     Ty = Context.LongLongTy;
15455   else {
15456     llvm_unreachable("I don't know size of pointer!");
15457   }
15458 
15459   return new (Context) GNUNullExpr(Ty, TokenLoc);
15460 }
15461 
15462 ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind,
15463                                     SourceLocation BuiltinLoc,
15464                                     SourceLocation RPLoc) {
15465   return BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, CurContext);
15466 }
15467 
15468 ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind,
15469                                     SourceLocation BuiltinLoc,
15470                                     SourceLocation RPLoc,
15471                                     DeclContext *ParentContext) {
15472   return new (Context)
15473       SourceLocExpr(Context, Kind, BuiltinLoc, RPLoc, ParentContext);
15474 }
15475 
15476 bool Sema::CheckConversionToObjCLiteral(QualType DstType, Expr *&Exp,
15477                                         bool Diagnose) {
15478   if (!getLangOpts().ObjC)
15479     return false;
15480 
15481   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
15482   if (!PT)
15483     return false;
15484   const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
15485 
15486   // Ignore any parens, implicit casts (should only be
15487   // array-to-pointer decays), and not-so-opaque values.  The last is
15488   // important for making this trigger for property assignments.
15489   Expr *SrcExpr = Exp->IgnoreParenImpCasts();
15490   if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
15491     if (OV->getSourceExpr())
15492       SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
15493 
15494   if (auto *SL = dyn_cast<StringLiteral>(SrcExpr)) {
15495     if (!PT->isObjCIdType() &&
15496         !(ID && ID->getIdentifier()->isStr("NSString")))
15497       return false;
15498     if (!SL->isAscii())
15499       return false;
15500 
15501     if (Diagnose) {
15502       Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix)
15503           << /*string*/0 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@");
15504       Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get();
15505     }
15506     return true;
15507   }
15508 
15509   if ((isa<IntegerLiteral>(SrcExpr) || isa<CharacterLiteral>(SrcExpr) ||
15510       isa<FloatingLiteral>(SrcExpr) || isa<ObjCBoolLiteralExpr>(SrcExpr) ||
15511       isa<CXXBoolLiteralExpr>(SrcExpr)) &&
15512       !SrcExpr->isNullPointerConstant(
15513           getASTContext(), Expr::NPC_NeverValueDependent)) {
15514     if (!ID || !ID->getIdentifier()->isStr("NSNumber"))
15515       return false;
15516     if (Diagnose) {
15517       Diag(SrcExpr->getBeginLoc(), diag::err_missing_atsign_prefix)
15518           << /*number*/1
15519           << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(), "@");
15520       Expr *NumLit =
15521           BuildObjCNumericLiteral(SrcExpr->getBeginLoc(), SrcExpr).get();
15522       if (NumLit)
15523         Exp = NumLit;
15524     }
15525     return true;
15526   }
15527 
15528   return false;
15529 }
15530 
15531 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
15532                                               const Expr *SrcExpr) {
15533   if (!DstType->isFunctionPointerType() ||
15534       !SrcExpr->getType()->isFunctionType())
15535     return false;
15536 
15537   auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
15538   if (!DRE)
15539     return false;
15540 
15541   auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
15542   if (!FD)
15543     return false;
15544 
15545   return !S.checkAddressOfFunctionIsAvailable(FD,
15546                                               /*Complain=*/true,
15547                                               SrcExpr->getBeginLoc());
15548 }
15549 
15550 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
15551                                     SourceLocation Loc,
15552                                     QualType DstType, QualType SrcType,
15553                                     Expr *SrcExpr, AssignmentAction Action,
15554                                     bool *Complained) {
15555   if (Complained)
15556     *Complained = false;
15557 
15558   // Decode the result (notice that AST's are still created for extensions).
15559   bool CheckInferredResultType = false;
15560   bool isInvalid = false;
15561   unsigned DiagKind = 0;
15562   FixItHint Hint;
15563   ConversionFixItGenerator ConvHints;
15564   bool MayHaveConvFixit = false;
15565   bool MayHaveFunctionDiff = false;
15566   const ObjCInterfaceDecl *IFace = nullptr;
15567   const ObjCProtocolDecl *PDecl = nullptr;
15568 
15569   switch (ConvTy) {
15570   case Compatible:
15571       DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
15572       return false;
15573 
15574   case PointerToInt:
15575     if (getLangOpts().CPlusPlus) {
15576       DiagKind = diag::err_typecheck_convert_pointer_int;
15577       isInvalid = true;
15578     } else {
15579       DiagKind = diag::ext_typecheck_convert_pointer_int;
15580     }
15581     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15582     MayHaveConvFixit = true;
15583     break;
15584   case IntToPointer:
15585     if (getLangOpts().CPlusPlus) {
15586       DiagKind = diag::err_typecheck_convert_int_pointer;
15587       isInvalid = true;
15588     } else {
15589       DiagKind = diag::ext_typecheck_convert_int_pointer;
15590     }
15591     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15592     MayHaveConvFixit = true;
15593     break;
15594   case IncompatibleFunctionPointer:
15595     if (getLangOpts().CPlusPlus) {
15596       DiagKind = diag::err_typecheck_convert_incompatible_function_pointer;
15597       isInvalid = true;
15598     } else {
15599       DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
15600     }
15601     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15602     MayHaveConvFixit = true;
15603     break;
15604   case IncompatiblePointer:
15605     if (Action == AA_Passing_CFAudited) {
15606       DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
15607     } else if (getLangOpts().CPlusPlus) {
15608       DiagKind = diag::err_typecheck_convert_incompatible_pointer;
15609       isInvalid = true;
15610     } else {
15611       DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
15612     }
15613     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
15614       SrcType->isObjCObjectPointerType();
15615     if (Hint.isNull() && !CheckInferredResultType) {
15616       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15617     }
15618     else if (CheckInferredResultType) {
15619       SrcType = SrcType.getUnqualifiedType();
15620       DstType = DstType.getUnqualifiedType();
15621     }
15622     MayHaveConvFixit = true;
15623     break;
15624   case IncompatiblePointerSign:
15625     if (getLangOpts().CPlusPlus) {
15626       DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign;
15627       isInvalid = true;
15628     } else {
15629       DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
15630     }
15631     break;
15632   case FunctionVoidPointer:
15633     if (getLangOpts().CPlusPlus) {
15634       DiagKind = diag::err_typecheck_convert_pointer_void_func;
15635       isInvalid = true;
15636     } else {
15637       DiagKind = diag::ext_typecheck_convert_pointer_void_func;
15638     }
15639     break;
15640   case IncompatiblePointerDiscardsQualifiers: {
15641     // Perform array-to-pointer decay if necessary.
15642     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
15643 
15644     isInvalid = true;
15645 
15646     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
15647     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
15648     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
15649       DiagKind = diag::err_typecheck_incompatible_address_space;
15650       break;
15651 
15652     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
15653       DiagKind = diag::err_typecheck_incompatible_ownership;
15654       break;
15655     }
15656 
15657     llvm_unreachable("unknown error case for discarding qualifiers!");
15658     // fallthrough
15659   }
15660   case CompatiblePointerDiscardsQualifiers:
15661     // If the qualifiers lost were because we were applying the
15662     // (deprecated) C++ conversion from a string literal to a char*
15663     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
15664     // Ideally, this check would be performed in
15665     // checkPointerTypesForAssignment. However, that would require a
15666     // bit of refactoring (so that the second argument is an
15667     // expression, rather than a type), which should be done as part
15668     // of a larger effort to fix checkPointerTypesForAssignment for
15669     // C++ semantics.
15670     if (getLangOpts().CPlusPlus &&
15671         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
15672       return false;
15673     if (getLangOpts().CPlusPlus) {
15674       DiagKind =  diag::err_typecheck_convert_discards_qualifiers;
15675       isInvalid = true;
15676     } else {
15677       DiagKind =  diag::ext_typecheck_convert_discards_qualifiers;
15678     }
15679 
15680     break;
15681   case IncompatibleNestedPointerQualifiers:
15682     if (getLangOpts().CPlusPlus) {
15683       isInvalid = true;
15684       DiagKind = diag::err_nested_pointer_qualifier_mismatch;
15685     } else {
15686       DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
15687     }
15688     break;
15689   case IncompatibleNestedPointerAddressSpaceMismatch:
15690     DiagKind = diag::err_typecheck_incompatible_nested_address_space;
15691     isInvalid = true;
15692     break;
15693   case IntToBlockPointer:
15694     DiagKind = diag::err_int_to_block_pointer;
15695     isInvalid = true;
15696     break;
15697   case IncompatibleBlockPointer:
15698     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
15699     isInvalid = true;
15700     break;
15701   case IncompatibleObjCQualifiedId: {
15702     if (SrcType->isObjCQualifiedIdType()) {
15703       const ObjCObjectPointerType *srcOPT =
15704                 SrcType->castAs<ObjCObjectPointerType>();
15705       for (auto *srcProto : srcOPT->quals()) {
15706         PDecl = srcProto;
15707         break;
15708       }
15709       if (const ObjCInterfaceType *IFaceT =
15710             DstType->castAs<ObjCObjectPointerType>()->getInterfaceType())
15711         IFace = IFaceT->getDecl();
15712     }
15713     else if (DstType->isObjCQualifiedIdType()) {
15714       const ObjCObjectPointerType *dstOPT =
15715         DstType->castAs<ObjCObjectPointerType>();
15716       for (auto *dstProto : dstOPT->quals()) {
15717         PDecl = dstProto;
15718         break;
15719       }
15720       if (const ObjCInterfaceType *IFaceT =
15721             SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType())
15722         IFace = IFaceT->getDecl();
15723     }
15724     if (getLangOpts().CPlusPlus) {
15725       DiagKind = diag::err_incompatible_qualified_id;
15726       isInvalid = true;
15727     } else {
15728       DiagKind = diag::warn_incompatible_qualified_id;
15729     }
15730     break;
15731   }
15732   case IncompatibleVectors:
15733     if (getLangOpts().CPlusPlus) {
15734       DiagKind = diag::err_incompatible_vectors;
15735       isInvalid = true;
15736     } else {
15737       DiagKind = diag::warn_incompatible_vectors;
15738     }
15739     break;
15740   case IncompatibleObjCWeakRef:
15741     DiagKind = diag::err_arc_weak_unavailable_assign;
15742     isInvalid = true;
15743     break;
15744   case Incompatible:
15745     if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
15746       if (Complained)
15747         *Complained = true;
15748       return true;
15749     }
15750 
15751     DiagKind = diag::err_typecheck_convert_incompatible;
15752     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15753     MayHaveConvFixit = true;
15754     isInvalid = true;
15755     MayHaveFunctionDiff = true;
15756     break;
15757   }
15758 
15759   QualType FirstType, SecondType;
15760   switch (Action) {
15761   case AA_Assigning:
15762   case AA_Initializing:
15763     // The destination type comes first.
15764     FirstType = DstType;
15765     SecondType = SrcType;
15766     break;
15767 
15768   case AA_Returning:
15769   case AA_Passing:
15770   case AA_Passing_CFAudited:
15771   case AA_Converting:
15772   case AA_Sending:
15773   case AA_Casting:
15774     // The source type comes first.
15775     FirstType = SrcType;
15776     SecondType = DstType;
15777     break;
15778   }
15779 
15780   PartialDiagnostic FDiag = PDiag(DiagKind);
15781   if (Action == AA_Passing_CFAudited)
15782     FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
15783   else
15784     FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
15785 
15786   // If we can fix the conversion, suggest the FixIts.
15787   assert(ConvHints.isNull() || Hint.isNull());
15788   if (!ConvHints.isNull()) {
15789     for (FixItHint &H : ConvHints.Hints)
15790       FDiag << H;
15791   } else {
15792     FDiag << Hint;
15793   }
15794   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
15795 
15796   if (MayHaveFunctionDiff)
15797     HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
15798 
15799   Diag(Loc, FDiag);
15800   if ((DiagKind == diag::warn_incompatible_qualified_id ||
15801        DiagKind == diag::err_incompatible_qualified_id) &&
15802       PDecl && IFace && !IFace->hasDefinition())
15803     Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
15804         << IFace << PDecl;
15805 
15806   if (SecondType == Context.OverloadTy)
15807     NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
15808                               FirstType, /*TakingAddress=*/true);
15809 
15810   if (CheckInferredResultType)
15811     EmitRelatedResultTypeNote(SrcExpr);
15812 
15813   if (Action == AA_Returning && ConvTy == IncompatiblePointer)
15814     EmitRelatedResultTypeNoteForReturn(DstType);
15815 
15816   if (Complained)
15817     *Complained = true;
15818   return isInvalid;
15819 }
15820 
15821 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
15822                                                  llvm::APSInt *Result) {
15823   class SimpleICEDiagnoser : public VerifyICEDiagnoser {
15824   public:
15825     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
15826       S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
15827     }
15828   } Diagnoser;
15829 
15830   return VerifyIntegerConstantExpression(E, Result, Diagnoser);
15831 }
15832 
15833 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
15834                                                  llvm::APSInt *Result,
15835                                                  unsigned DiagID,
15836                                                  bool AllowFold) {
15837   class IDDiagnoser : public VerifyICEDiagnoser {
15838     unsigned DiagID;
15839 
15840   public:
15841     IDDiagnoser(unsigned DiagID)
15842       : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
15843 
15844     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
15845       S.Diag(Loc, DiagID) << SR;
15846     }
15847   } Diagnoser(DiagID);
15848 
15849   return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
15850 }
15851 
15852 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
15853                                             SourceRange SR) {
15854   S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
15855 }
15856 
15857 ExprResult
15858 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
15859                                       VerifyICEDiagnoser &Diagnoser,
15860                                       bool AllowFold) {
15861   SourceLocation DiagLoc = E->getBeginLoc();
15862 
15863   if (getLangOpts().CPlusPlus11) {
15864     // C++11 [expr.const]p5:
15865     //   If an expression of literal class type is used in a context where an
15866     //   integral constant expression is required, then that class type shall
15867     //   have a single non-explicit conversion function to an integral or
15868     //   unscoped enumeration type
15869     ExprResult Converted;
15870     class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
15871     public:
15872       CXX11ConvertDiagnoser(bool Silent)
15873           : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
15874                                 Silent, true) {}
15875 
15876       SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
15877                                            QualType T) override {
15878         return S.Diag(Loc, diag::err_ice_not_integral) << T;
15879       }
15880 
15881       SemaDiagnosticBuilder diagnoseIncomplete(
15882           Sema &S, SourceLocation Loc, QualType T) override {
15883         return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
15884       }
15885 
15886       SemaDiagnosticBuilder diagnoseExplicitConv(
15887           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
15888         return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
15889       }
15890 
15891       SemaDiagnosticBuilder noteExplicitConv(
15892           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
15893         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
15894                  << ConvTy->isEnumeralType() << ConvTy;
15895       }
15896 
15897       SemaDiagnosticBuilder diagnoseAmbiguous(
15898           Sema &S, SourceLocation Loc, QualType T) override {
15899         return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
15900       }
15901 
15902       SemaDiagnosticBuilder noteAmbiguous(
15903           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
15904         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
15905                  << ConvTy->isEnumeralType() << ConvTy;
15906       }
15907 
15908       SemaDiagnosticBuilder diagnoseConversion(
15909           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
15910         llvm_unreachable("conversion functions are permitted");
15911       }
15912     } ConvertDiagnoser(Diagnoser.Suppress);
15913 
15914     Converted = PerformContextualImplicitConversion(DiagLoc, E,
15915                                                     ConvertDiagnoser);
15916     if (Converted.isInvalid())
15917       return Converted;
15918     E = Converted.get();
15919     if (!E->getType()->isIntegralOrUnscopedEnumerationType())
15920       return ExprError();
15921   } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
15922     // An ICE must be of integral or unscoped enumeration type.
15923     if (!Diagnoser.Suppress)
15924       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
15925     return ExprError();
15926   }
15927 
15928   ExprResult RValueExpr = DefaultLvalueConversion(E);
15929   if (RValueExpr.isInvalid())
15930     return ExprError();
15931 
15932   E = RValueExpr.get();
15933 
15934   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
15935   // in the non-ICE case.
15936   if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
15937     if (Result)
15938       *Result = E->EvaluateKnownConstIntCheckOverflow(Context);
15939     if (!isa<ConstantExpr>(E))
15940       E = ConstantExpr::Create(Context, E);
15941     return E;
15942   }
15943 
15944   Expr::EvalResult EvalResult;
15945   SmallVector<PartialDiagnosticAt, 8> Notes;
15946   EvalResult.Diag = &Notes;
15947 
15948   // Try to evaluate the expression, and produce diagnostics explaining why it's
15949   // not a constant expression as a side-effect.
15950   bool Folded =
15951       E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) &&
15952       EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
15953 
15954   if (!isa<ConstantExpr>(E))
15955     E = ConstantExpr::Create(Context, E, EvalResult.Val);
15956 
15957   // In C++11, we can rely on diagnostics being produced for any expression
15958   // which is not a constant expression. If no diagnostics were produced, then
15959   // this is a constant expression.
15960   if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
15961     if (Result)
15962       *Result = EvalResult.Val.getInt();
15963     return E;
15964   }
15965 
15966   // If our only note is the usual "invalid subexpression" note, just point
15967   // the caret at its location rather than producing an essentially
15968   // redundant note.
15969   if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
15970         diag::note_invalid_subexpr_in_const_expr) {
15971     DiagLoc = Notes[0].first;
15972     Notes.clear();
15973   }
15974 
15975   if (!Folded || !AllowFold) {
15976     if (!Diagnoser.Suppress) {
15977       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
15978       for (const PartialDiagnosticAt &Note : Notes)
15979         Diag(Note.first, Note.second);
15980     }
15981 
15982     return ExprError();
15983   }
15984 
15985   Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
15986   for (const PartialDiagnosticAt &Note : Notes)
15987     Diag(Note.first, Note.second);
15988 
15989   if (Result)
15990     *Result = EvalResult.Val.getInt();
15991   return E;
15992 }
15993 
15994 namespace {
15995   // Handle the case where we conclude a expression which we speculatively
15996   // considered to be unevaluated is actually evaluated.
15997   class TransformToPE : public TreeTransform<TransformToPE> {
15998     typedef TreeTransform<TransformToPE> BaseTransform;
15999 
16000   public:
16001     TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
16002 
16003     // Make sure we redo semantic analysis
16004     bool AlwaysRebuild() { return true; }
16005     bool ReplacingOriginal() { return true; }
16006 
16007     // We need to special-case DeclRefExprs referring to FieldDecls which
16008     // are not part of a member pointer formation; normal TreeTransforming
16009     // doesn't catch this case because of the way we represent them in the AST.
16010     // FIXME: This is a bit ugly; is it really the best way to handle this
16011     // case?
16012     //
16013     // Error on DeclRefExprs referring to FieldDecls.
16014     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
16015       if (isa<FieldDecl>(E->getDecl()) &&
16016           !SemaRef.isUnevaluatedContext())
16017         return SemaRef.Diag(E->getLocation(),
16018                             diag::err_invalid_non_static_member_use)
16019             << E->getDecl() << E->getSourceRange();
16020 
16021       return BaseTransform::TransformDeclRefExpr(E);
16022     }
16023 
16024     // Exception: filter out member pointer formation
16025     ExprResult TransformUnaryOperator(UnaryOperator *E) {
16026       if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
16027         return E;
16028 
16029       return BaseTransform::TransformUnaryOperator(E);
16030     }
16031 
16032     // The body of a lambda-expression is in a separate expression evaluation
16033     // context so never needs to be transformed.
16034     // FIXME: Ideally we wouldn't transform the closure type either, and would
16035     // just recreate the capture expressions and lambda expression.
16036     StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
16037       return SkipLambdaBody(E, Body);
16038     }
16039   };
16040 }
16041 
16042 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
16043   assert(isUnevaluatedContext() &&
16044          "Should only transform unevaluated expressions");
16045   ExprEvalContexts.back().Context =
16046       ExprEvalContexts[ExprEvalContexts.size()-2].Context;
16047   if (isUnevaluatedContext())
16048     return E;
16049   return TransformToPE(*this).TransformExpr(E);
16050 }
16051 
16052 void
16053 Sema::PushExpressionEvaluationContext(
16054     ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
16055     ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
16056   ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
16057                                 LambdaContextDecl, ExprContext);
16058   Cleanup.reset();
16059   if (!MaybeODRUseExprs.empty())
16060     std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
16061 }
16062 
16063 void
16064 Sema::PushExpressionEvaluationContext(
16065     ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
16066     ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
16067   Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
16068   PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);
16069 }
16070 
16071 namespace {
16072 
16073 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
16074   PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
16075   if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) {
16076     if (E->getOpcode() == UO_Deref)
16077       return CheckPossibleDeref(S, E->getSubExpr());
16078   } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) {
16079     return CheckPossibleDeref(S, E->getBase());
16080   } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) {
16081     return CheckPossibleDeref(S, E->getBase());
16082   } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) {
16083     QualType Inner;
16084     QualType Ty = E->getType();
16085     if (const auto *Ptr = Ty->getAs<PointerType>())
16086       Inner = Ptr->getPointeeType();
16087     else if (const auto *Arr = S.Context.getAsArrayType(Ty))
16088       Inner = Arr->getElementType();
16089     else
16090       return nullptr;
16091 
16092     if (Inner->hasAttr(attr::NoDeref))
16093       return E;
16094   }
16095   return nullptr;
16096 }
16097 
16098 } // namespace
16099 
16100 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) {
16101   for (const Expr *E : Rec.PossibleDerefs) {
16102     const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E);
16103     if (DeclRef) {
16104       const ValueDecl *Decl = DeclRef->getDecl();
16105       Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type)
16106           << Decl->getName() << E->getSourceRange();
16107       Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName();
16108     } else {
16109       Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl)
16110           << E->getSourceRange();
16111     }
16112   }
16113   Rec.PossibleDerefs.clear();
16114 }
16115 
16116 /// Check whether E, which is either a discarded-value expression or an
16117 /// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue,
16118 /// and if so, remove it from the list of volatile-qualified assignments that
16119 /// we are going to warn are deprecated.
16120 void Sema::CheckUnusedVolatileAssignment(Expr *E) {
16121   if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20)
16122     return;
16123 
16124   // Note: ignoring parens here is not justified by the standard rules, but
16125   // ignoring parentheses seems like a more reasonable approach, and this only
16126   // drives a deprecation warning so doesn't affect conformance.
16127   if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) {
16128     if (BO->getOpcode() == BO_Assign) {
16129       auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs;
16130       LHSs.erase(std::remove(LHSs.begin(), LHSs.end(), BO->getLHS()),
16131                  LHSs.end());
16132     }
16133   }
16134 }
16135 
16136 ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) {
16137   if (!E.isUsable() || !Decl || !Decl->isConsteval() || isConstantEvaluated() ||
16138       RebuildingImmediateInvocation)
16139     return E;
16140 
16141   /// Opportunistically remove the callee from ReferencesToConsteval if we can.
16142   /// It's OK if this fails; we'll also remove this in
16143   /// HandleImmediateInvocations, but catching it here allows us to avoid
16144   /// walking the AST looking for it in simple cases.
16145   if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit()))
16146     if (auto *DeclRef =
16147             dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()))
16148       ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef);
16149 
16150   E = MaybeCreateExprWithCleanups(E);
16151 
16152   ConstantExpr *Res = ConstantExpr::Create(
16153       getASTContext(), E.get(),
16154       ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(),
16155                                    getASTContext()),
16156       /*IsImmediateInvocation*/ true);
16157   ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0);
16158   return Res;
16159 }
16160 
16161 static void EvaluateAndDiagnoseImmediateInvocation(
16162     Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) {
16163   llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
16164   Expr::EvalResult Eval;
16165   Eval.Diag = &Notes;
16166   ConstantExpr *CE = Candidate.getPointer();
16167   bool Result = CE->EvaluateAsConstantExpr(Eval, Expr::EvaluateForCodeGen,
16168                                            SemaRef.getASTContext(), true);
16169   if (!Result || !Notes.empty()) {
16170     Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit();
16171     if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr))
16172       InnerExpr = FunctionalCast->getSubExpr();
16173     FunctionDecl *FD = nullptr;
16174     if (auto *Call = dyn_cast<CallExpr>(InnerExpr))
16175       FD = cast<FunctionDecl>(Call->getCalleeDecl());
16176     else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr))
16177       FD = Call->getConstructor();
16178     else
16179       llvm_unreachable("unhandled decl kind");
16180     assert(FD->isConsteval());
16181     SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call) << FD;
16182     for (auto &Note : Notes)
16183       SemaRef.Diag(Note.first, Note.second);
16184     return;
16185   }
16186   CE->MoveIntoResult(Eval.Val, SemaRef.getASTContext());
16187 }
16188 
16189 static void RemoveNestedImmediateInvocation(
16190     Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec,
16191     SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) {
16192   struct ComplexRemove : TreeTransform<ComplexRemove> {
16193     using Base = TreeTransform<ComplexRemove>;
16194     llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
16195     SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet;
16196     SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator
16197         CurrentII;
16198     ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR,
16199                   SmallVector<Sema::ImmediateInvocationCandidate, 4> &II,
16200                   SmallVector<Sema::ImmediateInvocationCandidate,
16201                               4>::reverse_iterator Current)
16202         : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {}
16203     void RemoveImmediateInvocation(ConstantExpr* E) {
16204       auto It = std::find_if(CurrentII, IISet.rend(),
16205                              [E](Sema::ImmediateInvocationCandidate Elem) {
16206                                return Elem.getPointer() == E;
16207                              });
16208       assert(It != IISet.rend() &&
16209              "ConstantExpr marked IsImmediateInvocation should "
16210              "be present");
16211       It->setInt(1); // Mark as deleted
16212     }
16213     ExprResult TransformConstantExpr(ConstantExpr *E) {
16214       if (!E->isImmediateInvocation())
16215         return Base::TransformConstantExpr(E);
16216       RemoveImmediateInvocation(E);
16217       return Base::TransformExpr(E->getSubExpr());
16218     }
16219     /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so
16220     /// we need to remove its DeclRefExpr from the DRSet.
16221     ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
16222       DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit()));
16223       return Base::TransformCXXOperatorCallExpr(E);
16224     }
16225     /// Base::TransformInitializer skip ConstantExpr so we need to visit them
16226     /// here.
16227     ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) {
16228       if (!Init)
16229         return Init;
16230       /// ConstantExpr are the first layer of implicit node to be removed so if
16231       /// Init isn't a ConstantExpr, no ConstantExpr will be skipped.
16232       if (auto *CE = dyn_cast<ConstantExpr>(Init))
16233         if (CE->isImmediateInvocation())
16234           RemoveImmediateInvocation(CE);
16235       return Base::TransformInitializer(Init, NotCopyInit);
16236     }
16237     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
16238       DRSet.erase(E);
16239       return E;
16240     }
16241     bool AlwaysRebuild() { return false; }
16242     bool ReplacingOriginal() { return true; }
16243     bool AllowSkippingCXXConstructExpr() {
16244       bool Res = AllowSkippingFirstCXXConstructExpr;
16245       AllowSkippingFirstCXXConstructExpr = true;
16246       return Res;
16247     }
16248     bool AllowSkippingFirstCXXConstructExpr = true;
16249   } Transformer(SemaRef, Rec.ReferenceToConsteval,
16250                 Rec.ImmediateInvocationCandidates, It);
16251 
16252   /// CXXConstructExpr with a single argument are getting skipped by
16253   /// TreeTransform in some situtation because they could be implicit. This
16254   /// can only occur for the top-level CXXConstructExpr because it is used
16255   /// nowhere in the expression being transformed therefore will not be rebuilt.
16256   /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from
16257   /// skipping the first CXXConstructExpr.
16258   if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit()))
16259     Transformer.AllowSkippingFirstCXXConstructExpr = false;
16260 
16261   ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr());
16262   assert(Res.isUsable());
16263   Res = SemaRef.MaybeCreateExprWithCleanups(Res);
16264   It->getPointer()->setSubExpr(Res.get());
16265 }
16266 
16267 static void
16268 HandleImmediateInvocations(Sema &SemaRef,
16269                            Sema::ExpressionEvaluationContextRecord &Rec) {
16270   if ((Rec.ImmediateInvocationCandidates.size() == 0 &&
16271        Rec.ReferenceToConsteval.size() == 0) ||
16272       SemaRef.RebuildingImmediateInvocation)
16273     return;
16274 
16275   /// When we have more then 1 ImmediateInvocationCandidates we need to check
16276   /// for nested ImmediateInvocationCandidates. when we have only 1 we only
16277   /// need to remove ReferenceToConsteval in the immediate invocation.
16278   if (Rec.ImmediateInvocationCandidates.size() > 1) {
16279 
16280     /// Prevent sema calls during the tree transform from adding pointers that
16281     /// are already in the sets.
16282     llvm::SaveAndRestore<bool> DisableIITracking(
16283         SemaRef.RebuildingImmediateInvocation, true);
16284 
16285     /// Prevent diagnostic during tree transfrom as they are duplicates
16286     Sema::TentativeAnalysisScope DisableDiag(SemaRef);
16287 
16288     for (auto It = Rec.ImmediateInvocationCandidates.rbegin();
16289          It != Rec.ImmediateInvocationCandidates.rend(); It++)
16290       if (!It->getInt())
16291         RemoveNestedImmediateInvocation(SemaRef, Rec, It);
16292   } else if (Rec.ImmediateInvocationCandidates.size() == 1 &&
16293              Rec.ReferenceToConsteval.size()) {
16294     struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> {
16295       llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
16296       SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {}
16297       bool VisitDeclRefExpr(DeclRefExpr *E) {
16298         DRSet.erase(E);
16299         return DRSet.size();
16300       }
16301     } Visitor(Rec.ReferenceToConsteval);
16302     Visitor.TraverseStmt(
16303         Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr());
16304   }
16305   for (auto CE : Rec.ImmediateInvocationCandidates)
16306     if (!CE.getInt())
16307       EvaluateAndDiagnoseImmediateInvocation(SemaRef, CE);
16308   for (auto DR : Rec.ReferenceToConsteval) {
16309     auto *FD = cast<FunctionDecl>(DR->getDecl());
16310     SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address)
16311         << FD;
16312     SemaRef.Diag(FD->getLocation(), diag::note_declared_at);
16313   }
16314 }
16315 
16316 void Sema::PopExpressionEvaluationContext() {
16317   ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
16318   unsigned NumTypos = Rec.NumTypos;
16319 
16320   if (!Rec.Lambdas.empty()) {
16321     using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind;
16322     if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || Rec.isUnevaluated() ||
16323         (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17)) {
16324       unsigned D;
16325       if (Rec.isUnevaluated()) {
16326         // C++11 [expr.prim.lambda]p2:
16327         //   A lambda-expression shall not appear in an unevaluated operand
16328         //   (Clause 5).
16329         D = diag::err_lambda_unevaluated_operand;
16330       } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
16331         // C++1y [expr.const]p2:
16332         //   A conditional-expression e is a core constant expression unless the
16333         //   evaluation of e, following the rules of the abstract machine, would
16334         //   evaluate [...] a lambda-expression.
16335         D = diag::err_lambda_in_constant_expression;
16336       } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
16337         // C++17 [expr.prim.lamda]p2:
16338         // A lambda-expression shall not appear [...] in a template-argument.
16339         D = diag::err_lambda_in_invalid_context;
16340       } else
16341         llvm_unreachable("Couldn't infer lambda error message.");
16342 
16343       for (const auto *L : Rec.Lambdas)
16344         Diag(L->getBeginLoc(), D);
16345     }
16346   }
16347 
16348   WarnOnPendingNoDerefs(Rec);
16349   HandleImmediateInvocations(*this, Rec);
16350 
16351   // Warn on any volatile-qualified simple-assignments that are not discarded-
16352   // value expressions nor unevaluated operands (those cases get removed from
16353   // this list by CheckUnusedVolatileAssignment).
16354   for (auto *BO : Rec.VolatileAssignmentLHSs)
16355     Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile)
16356         << BO->getType();
16357 
16358   // When are coming out of an unevaluated context, clear out any
16359   // temporaries that we may have created as part of the evaluation of
16360   // the expression in that context: they aren't relevant because they
16361   // will never be constructed.
16362   if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
16363     ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
16364                              ExprCleanupObjects.end());
16365     Cleanup = Rec.ParentCleanup;
16366     CleanupVarDeclMarking();
16367     std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
16368   // Otherwise, merge the contexts together.
16369   } else {
16370     Cleanup.mergeFrom(Rec.ParentCleanup);
16371     MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
16372                             Rec.SavedMaybeODRUseExprs.end());
16373   }
16374 
16375   // Pop the current expression evaluation context off the stack.
16376   ExprEvalContexts.pop_back();
16377 
16378   // The global expression evaluation context record is never popped.
16379   ExprEvalContexts.back().NumTypos += NumTypos;
16380 }
16381 
16382 void Sema::DiscardCleanupsInEvaluationContext() {
16383   ExprCleanupObjects.erase(
16384          ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
16385          ExprCleanupObjects.end());
16386   Cleanup.reset();
16387   MaybeODRUseExprs.clear();
16388 }
16389 
16390 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
16391   ExprResult Result = CheckPlaceholderExpr(E);
16392   if (Result.isInvalid())
16393     return ExprError();
16394   E = Result.get();
16395   if (!E->getType()->isVariablyModifiedType())
16396     return E;
16397   return TransformToPotentiallyEvaluated(E);
16398 }
16399 
16400 /// Are we in a context that is potentially constant evaluated per C++20
16401 /// [expr.const]p12?
16402 static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) {
16403   /// C++2a [expr.const]p12:
16404   //   An expression or conversion is potentially constant evaluated if it is
16405   switch (SemaRef.ExprEvalContexts.back().Context) {
16406     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
16407       // -- a manifestly constant-evaluated expression,
16408     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
16409     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
16410     case Sema::ExpressionEvaluationContext::DiscardedStatement:
16411       // -- a potentially-evaluated expression,
16412     case Sema::ExpressionEvaluationContext::UnevaluatedList:
16413       // -- an immediate subexpression of a braced-init-list,
16414 
16415       // -- [FIXME] an expression of the form & cast-expression that occurs
16416       //    within a templated entity
16417       // -- a subexpression of one of the above that is not a subexpression of
16418       // a nested unevaluated operand.
16419       return true;
16420 
16421     case Sema::ExpressionEvaluationContext::Unevaluated:
16422     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
16423       // Expressions in this context are never evaluated.
16424       return false;
16425   }
16426   llvm_unreachable("Invalid context");
16427 }
16428 
16429 /// Return true if this function has a calling convention that requires mangling
16430 /// in the size of the parameter pack.
16431 static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) {
16432   // These manglings don't do anything on non-Windows or non-x86 platforms, so
16433   // we don't need parameter type sizes.
16434   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
16435   if (!TT.isOSWindows() || !TT.isX86())
16436     return false;
16437 
16438   // If this is C++ and this isn't an extern "C" function, parameters do not
16439   // need to be complete. In this case, C++ mangling will apply, which doesn't
16440   // use the size of the parameters.
16441   if (S.getLangOpts().CPlusPlus && !FD->isExternC())
16442     return false;
16443 
16444   // Stdcall, fastcall, and vectorcall need this special treatment.
16445   CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
16446   switch (CC) {
16447   case CC_X86StdCall:
16448   case CC_X86FastCall:
16449   case CC_X86VectorCall:
16450     return true;
16451   default:
16452     break;
16453   }
16454   return false;
16455 }
16456 
16457 /// Require that all of the parameter types of function be complete. Normally,
16458 /// parameter types are only required to be complete when a function is called
16459 /// or defined, but to mangle functions with certain calling conventions, the
16460 /// mangler needs to know the size of the parameter list. In this situation,
16461 /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles
16462 /// the function as _foo@0, i.e. zero bytes of parameters, which will usually
16463 /// result in a linker error. Clang doesn't implement this behavior, and instead
16464 /// attempts to error at compile time.
16465 static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD,
16466                                                   SourceLocation Loc) {
16467   class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser {
16468     FunctionDecl *FD;
16469     ParmVarDecl *Param;
16470 
16471   public:
16472     ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param)
16473         : FD(FD), Param(Param) {}
16474 
16475     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
16476       CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
16477       StringRef CCName;
16478       switch (CC) {
16479       case CC_X86StdCall:
16480         CCName = "stdcall";
16481         break;
16482       case CC_X86FastCall:
16483         CCName = "fastcall";
16484         break;
16485       case CC_X86VectorCall:
16486         CCName = "vectorcall";
16487         break;
16488       default:
16489         llvm_unreachable("CC does not need mangling");
16490       }
16491 
16492       S.Diag(Loc, diag::err_cconv_incomplete_param_type)
16493           << Param->getDeclName() << FD->getDeclName() << CCName;
16494     }
16495   };
16496 
16497   for (ParmVarDecl *Param : FD->parameters()) {
16498     ParamIncompleteTypeDiagnoser Diagnoser(FD, Param);
16499     S.RequireCompleteType(Loc, Param->getType(), Diagnoser);
16500   }
16501 }
16502 
16503 namespace {
16504 enum class OdrUseContext {
16505   /// Declarations in this context are not odr-used.
16506   None,
16507   /// Declarations in this context are formally odr-used, but this is a
16508   /// dependent context.
16509   Dependent,
16510   /// Declarations in this context are odr-used but not actually used (yet).
16511   FormallyOdrUsed,
16512   /// Declarations in this context are used.
16513   Used
16514 };
16515 }
16516 
16517 /// Are we within a context in which references to resolved functions or to
16518 /// variables result in odr-use?
16519 static OdrUseContext isOdrUseContext(Sema &SemaRef) {
16520   OdrUseContext Result;
16521 
16522   switch (SemaRef.ExprEvalContexts.back().Context) {
16523     case Sema::ExpressionEvaluationContext::Unevaluated:
16524     case Sema::ExpressionEvaluationContext::UnevaluatedList:
16525     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
16526       return OdrUseContext::None;
16527 
16528     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
16529     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
16530       Result = OdrUseContext::Used;
16531       break;
16532 
16533     case Sema::ExpressionEvaluationContext::DiscardedStatement:
16534       Result = OdrUseContext::FormallyOdrUsed;
16535       break;
16536 
16537     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
16538       // A default argument formally results in odr-use, but doesn't actually
16539       // result in a use in any real sense until it itself is used.
16540       Result = OdrUseContext::FormallyOdrUsed;
16541       break;
16542   }
16543 
16544   if (SemaRef.CurContext->isDependentContext())
16545     return OdrUseContext::Dependent;
16546 
16547   return Result;
16548 }
16549 
16550 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
16551   return Func->isConstexpr() &&
16552          (Func->isImplicitlyInstantiable() || !Func->isUserProvided());
16553 }
16554 
16555 /// Mark a function referenced, and check whether it is odr-used
16556 /// (C++ [basic.def.odr]p2, C99 6.9p3)
16557 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
16558                                   bool MightBeOdrUse) {
16559   assert(Func && "No function?");
16560 
16561   Func->setReferenced();
16562 
16563   // Recursive functions aren't really used until they're used from some other
16564   // context.
16565   bool IsRecursiveCall = CurContext == Func;
16566 
16567   // C++11 [basic.def.odr]p3:
16568   //   A function whose name appears as a potentially-evaluated expression is
16569   //   odr-used if it is the unique lookup result or the selected member of a
16570   //   set of overloaded functions [...].
16571   //
16572   // We (incorrectly) mark overload resolution as an unevaluated context, so we
16573   // can just check that here.
16574   OdrUseContext OdrUse =
16575       MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None;
16576   if (IsRecursiveCall && OdrUse == OdrUseContext::Used)
16577     OdrUse = OdrUseContext::FormallyOdrUsed;
16578 
16579   // Trivial default constructors and destructors are never actually used.
16580   // FIXME: What about other special members?
16581   if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() &&
16582       OdrUse == OdrUseContext::Used) {
16583     if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func))
16584       if (Constructor->isDefaultConstructor())
16585         OdrUse = OdrUseContext::FormallyOdrUsed;
16586     if (isa<CXXDestructorDecl>(Func))
16587       OdrUse = OdrUseContext::FormallyOdrUsed;
16588   }
16589 
16590   // C++20 [expr.const]p12:
16591   //   A function [...] is needed for constant evaluation if it is [...] a
16592   //   constexpr function that is named by an expression that is potentially
16593   //   constant evaluated
16594   bool NeededForConstantEvaluation =
16595       isPotentiallyConstantEvaluatedContext(*this) &&
16596       isImplicitlyDefinableConstexprFunction(Func);
16597 
16598   // Determine whether we require a function definition to exist, per
16599   // C++11 [temp.inst]p3:
16600   //   Unless a function template specialization has been explicitly
16601   //   instantiated or explicitly specialized, the function template
16602   //   specialization is implicitly instantiated when the specialization is
16603   //   referenced in a context that requires a function definition to exist.
16604   // C++20 [temp.inst]p7:
16605   //   The existence of a definition of a [...] function is considered to
16606   //   affect the semantics of the program if the [...] function is needed for
16607   //   constant evaluation by an expression
16608   // C++20 [basic.def.odr]p10:
16609   //   Every program shall contain exactly one definition of every non-inline
16610   //   function or variable that is odr-used in that program outside of a
16611   //   discarded statement
16612   // C++20 [special]p1:
16613   //   The implementation will implicitly define [defaulted special members]
16614   //   if they are odr-used or needed for constant evaluation.
16615   //
16616   // Note that we skip the implicit instantiation of templates that are only
16617   // used in unused default arguments or by recursive calls to themselves.
16618   // This is formally non-conforming, but seems reasonable in practice.
16619   bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used ||
16620                                              NeededForConstantEvaluation);
16621 
16622   // C++14 [temp.expl.spec]p6:
16623   //   If a template [...] is explicitly specialized then that specialization
16624   //   shall be declared before the first use of that specialization that would
16625   //   cause an implicit instantiation to take place, in every translation unit
16626   //   in which such a use occurs
16627   if (NeedDefinition &&
16628       (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
16629        Func->getMemberSpecializationInfo()))
16630     checkSpecializationVisibility(Loc, Func);
16631 
16632   if (getLangOpts().CUDA)
16633     CheckCUDACall(Loc, Func);
16634 
16635   if (getLangOpts().SYCLIsDevice)
16636     checkSYCLDeviceFunction(Loc, Func);
16637 
16638   // If we need a definition, try to create one.
16639   if (NeedDefinition && !Func->getBody()) {
16640     runWithSufficientStackSpace(Loc, [&] {
16641       if (CXXConstructorDecl *Constructor =
16642               dyn_cast<CXXConstructorDecl>(Func)) {
16643         Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
16644         if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
16645           if (Constructor->isDefaultConstructor()) {
16646             if (Constructor->isTrivial() &&
16647                 !Constructor->hasAttr<DLLExportAttr>())
16648               return;
16649             DefineImplicitDefaultConstructor(Loc, Constructor);
16650           } else if (Constructor->isCopyConstructor()) {
16651             DefineImplicitCopyConstructor(Loc, Constructor);
16652           } else if (Constructor->isMoveConstructor()) {
16653             DefineImplicitMoveConstructor(Loc, Constructor);
16654           }
16655         } else if (Constructor->getInheritedConstructor()) {
16656           DefineInheritingConstructor(Loc, Constructor);
16657         }
16658       } else if (CXXDestructorDecl *Destructor =
16659                      dyn_cast<CXXDestructorDecl>(Func)) {
16660         Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
16661         if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
16662           if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
16663             return;
16664           DefineImplicitDestructor(Loc, Destructor);
16665         }
16666         if (Destructor->isVirtual() && getLangOpts().AppleKext)
16667           MarkVTableUsed(Loc, Destructor->getParent());
16668       } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
16669         if (MethodDecl->isOverloadedOperator() &&
16670             MethodDecl->getOverloadedOperator() == OO_Equal) {
16671           MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
16672           if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
16673             if (MethodDecl->isCopyAssignmentOperator())
16674               DefineImplicitCopyAssignment(Loc, MethodDecl);
16675             else if (MethodDecl->isMoveAssignmentOperator())
16676               DefineImplicitMoveAssignment(Loc, MethodDecl);
16677           }
16678         } else if (isa<CXXConversionDecl>(MethodDecl) &&
16679                    MethodDecl->getParent()->isLambda()) {
16680           CXXConversionDecl *Conversion =
16681               cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
16682           if (Conversion->isLambdaToBlockPointerConversion())
16683             DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
16684           else
16685             DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
16686         } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
16687           MarkVTableUsed(Loc, MethodDecl->getParent());
16688       }
16689 
16690       if (Func->isDefaulted() && !Func->isDeleted()) {
16691         DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func);
16692         if (DCK != DefaultedComparisonKind::None)
16693           DefineDefaultedComparison(Loc, Func, DCK);
16694       }
16695 
16696       // Implicit instantiation of function templates and member functions of
16697       // class templates.
16698       if (Func->isImplicitlyInstantiable()) {
16699         TemplateSpecializationKind TSK =
16700             Func->getTemplateSpecializationKindForInstantiation();
16701         SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
16702         bool FirstInstantiation = PointOfInstantiation.isInvalid();
16703         if (FirstInstantiation) {
16704           PointOfInstantiation = Loc;
16705           Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
16706         } else if (TSK != TSK_ImplicitInstantiation) {
16707           // Use the point of use as the point of instantiation, instead of the
16708           // point of explicit instantiation (which we track as the actual point
16709           // of instantiation). This gives better backtraces in diagnostics.
16710           PointOfInstantiation = Loc;
16711         }
16712 
16713         if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
16714             Func->isConstexpr()) {
16715           if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
16716               cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
16717               CodeSynthesisContexts.size())
16718             PendingLocalImplicitInstantiations.push_back(
16719                 std::make_pair(Func, PointOfInstantiation));
16720           else if (Func->isConstexpr())
16721             // Do not defer instantiations of constexpr functions, to avoid the
16722             // expression evaluator needing to call back into Sema if it sees a
16723             // call to such a function.
16724             InstantiateFunctionDefinition(PointOfInstantiation, Func);
16725           else {
16726             Func->setInstantiationIsPending(true);
16727             PendingInstantiations.push_back(
16728                 std::make_pair(Func, PointOfInstantiation));
16729             // Notify the consumer that a function was implicitly instantiated.
16730             Consumer.HandleCXXImplicitFunctionInstantiation(Func);
16731           }
16732         }
16733       } else {
16734         // Walk redefinitions, as some of them may be instantiable.
16735         for (auto i : Func->redecls()) {
16736           if (!i->isUsed(false) && i->isImplicitlyInstantiable())
16737             MarkFunctionReferenced(Loc, i, MightBeOdrUse);
16738         }
16739       }
16740     });
16741   }
16742 
16743   // C++14 [except.spec]p17:
16744   //   An exception-specification is considered to be needed when:
16745   //   - the function is odr-used or, if it appears in an unevaluated operand,
16746   //     would be odr-used if the expression were potentially-evaluated;
16747   //
16748   // Note, we do this even if MightBeOdrUse is false. That indicates that the
16749   // function is a pure virtual function we're calling, and in that case the
16750   // function was selected by overload resolution and we need to resolve its
16751   // exception specification for a different reason.
16752   const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
16753   if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
16754     ResolveExceptionSpec(Loc, FPT);
16755 
16756   // If this is the first "real" use, act on that.
16757   if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) {
16758     // Keep track of used but undefined functions.
16759     if (!Func->isDefined()) {
16760       if (mightHaveNonExternalLinkage(Func))
16761         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
16762       else if (Func->getMostRecentDecl()->isInlined() &&
16763                !LangOpts.GNUInline &&
16764                !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
16765         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
16766       else if (isExternalWithNoLinkageType(Func))
16767         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
16768     }
16769 
16770     // Some x86 Windows calling conventions mangle the size of the parameter
16771     // pack into the name. Computing the size of the parameters requires the
16772     // parameter types to be complete. Check that now.
16773     if (funcHasParameterSizeMangling(*this, Func))
16774       CheckCompleteParameterTypesForMangler(*this, Func, Loc);
16775 
16776     // In the MS C++ ABI, the compiler emits destructor variants where they are
16777     // used. If the destructor is used here but defined elsewhere, mark the
16778     // virtual base destructors referenced. If those virtual base destructors
16779     // are inline, this will ensure they are defined when emitting the complete
16780     // destructor variant. This checking may be redundant if the destructor is
16781     // provided later in this TU.
16782     if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
16783       if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) {
16784         CXXRecordDecl *Parent = Dtor->getParent();
16785         if (Parent->getNumVBases() > 0 && !Dtor->getBody())
16786           CheckCompleteDestructorVariant(Loc, Dtor);
16787       }
16788     }
16789 
16790     Func->markUsed(Context);
16791   }
16792 }
16793 
16794 /// Directly mark a variable odr-used. Given a choice, prefer to use
16795 /// MarkVariableReferenced since it does additional checks and then
16796 /// calls MarkVarDeclODRUsed.
16797 /// If the variable must be captured:
16798 ///  - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
16799 ///  - else capture it in the DeclContext that maps to the
16800 ///    *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
16801 static void
16802 MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef,
16803                    const unsigned *const FunctionScopeIndexToStopAt = nullptr) {
16804   // Keep track of used but undefined variables.
16805   // FIXME: We shouldn't suppress this warning for static data members.
16806   if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
16807       (!Var->isExternallyVisible() || Var->isInline() ||
16808        SemaRef.isExternalWithNoLinkageType(Var)) &&
16809       !(Var->isStaticDataMember() && Var->hasInit())) {
16810     SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()];
16811     if (old.isInvalid())
16812       old = Loc;
16813   }
16814   QualType CaptureType, DeclRefType;
16815   if (SemaRef.LangOpts.OpenMP)
16816     SemaRef.tryCaptureOpenMPLambdas(Var);
16817   SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit,
16818     /*EllipsisLoc*/ SourceLocation(),
16819     /*BuildAndDiagnose*/ true,
16820     CaptureType, DeclRefType,
16821     FunctionScopeIndexToStopAt);
16822 
16823   Var->markUsed(SemaRef.Context);
16824 }
16825 
16826 void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture,
16827                                              SourceLocation Loc,
16828                                              unsigned CapturingScopeIndex) {
16829   MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex);
16830 }
16831 
16832 static void
16833 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
16834                                    ValueDecl *var, DeclContext *DC) {
16835   DeclContext *VarDC = var->getDeclContext();
16836 
16837   //  If the parameter still belongs to the translation unit, then
16838   //  we're actually just using one parameter in the declaration of
16839   //  the next.
16840   if (isa<ParmVarDecl>(var) &&
16841       isa<TranslationUnitDecl>(VarDC))
16842     return;
16843 
16844   // For C code, don't diagnose about capture if we're not actually in code
16845   // right now; it's impossible to write a non-constant expression outside of
16846   // function context, so we'll get other (more useful) diagnostics later.
16847   //
16848   // For C++, things get a bit more nasty... it would be nice to suppress this
16849   // diagnostic for certain cases like using a local variable in an array bound
16850   // for a member of a local class, but the correct predicate is not obvious.
16851   if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
16852     return;
16853 
16854   unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
16855   unsigned ContextKind = 3; // unknown
16856   if (isa<CXXMethodDecl>(VarDC) &&
16857       cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
16858     ContextKind = 2;
16859   } else if (isa<FunctionDecl>(VarDC)) {
16860     ContextKind = 0;
16861   } else if (isa<BlockDecl>(VarDC)) {
16862     ContextKind = 1;
16863   }
16864 
16865   S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
16866     << var << ValueKind << ContextKind << VarDC;
16867   S.Diag(var->getLocation(), diag::note_entity_declared_at)
16868       << var;
16869 
16870   // FIXME: Add additional diagnostic info about class etc. which prevents
16871   // capture.
16872 }
16873 
16874 
16875 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
16876                                       bool &SubCapturesAreNested,
16877                                       QualType &CaptureType,
16878                                       QualType &DeclRefType) {
16879    // Check whether we've already captured it.
16880   if (CSI->CaptureMap.count(Var)) {
16881     // If we found a capture, any subcaptures are nested.
16882     SubCapturesAreNested = true;
16883 
16884     // Retrieve the capture type for this variable.
16885     CaptureType = CSI->getCapture(Var).getCaptureType();
16886 
16887     // Compute the type of an expression that refers to this variable.
16888     DeclRefType = CaptureType.getNonReferenceType();
16889 
16890     // Similarly to mutable captures in lambda, all the OpenMP captures by copy
16891     // are mutable in the sense that user can change their value - they are
16892     // private instances of the captured declarations.
16893     const Capture &Cap = CSI->getCapture(Var);
16894     if (Cap.isCopyCapture() &&
16895         !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
16896         !(isa<CapturedRegionScopeInfo>(CSI) &&
16897           cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
16898       DeclRefType.addConst();
16899     return true;
16900   }
16901   return false;
16902 }
16903 
16904 // Only block literals, captured statements, and lambda expressions can
16905 // capture; other scopes don't work.
16906 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
16907                                  SourceLocation Loc,
16908                                  const bool Diagnose, Sema &S) {
16909   if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
16910     return getLambdaAwareParentOfDeclContext(DC);
16911   else if (Var->hasLocalStorage()) {
16912     if (Diagnose)
16913        diagnoseUncapturableValueReference(S, Loc, Var, DC);
16914   }
16915   return nullptr;
16916 }
16917 
16918 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
16919 // certain types of variables (unnamed, variably modified types etc.)
16920 // so check for eligibility.
16921 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
16922                                  SourceLocation Loc,
16923                                  const bool Diagnose, Sema &S) {
16924 
16925   bool IsBlock = isa<BlockScopeInfo>(CSI);
16926   bool IsLambda = isa<LambdaScopeInfo>(CSI);
16927 
16928   // Lambdas are not allowed to capture unnamed variables
16929   // (e.g. anonymous unions).
16930   // FIXME: The C++11 rule don't actually state this explicitly, but I'm
16931   // assuming that's the intent.
16932   if (IsLambda && !Var->getDeclName()) {
16933     if (Diagnose) {
16934       S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
16935       S.Diag(Var->getLocation(), diag::note_declared_at);
16936     }
16937     return false;
16938   }
16939 
16940   // Prohibit variably-modified types in blocks; they're difficult to deal with.
16941   if (Var->getType()->isVariablyModifiedType() && IsBlock) {
16942     if (Diagnose) {
16943       S.Diag(Loc, diag::err_ref_vm_type);
16944       S.Diag(Var->getLocation(), diag::note_previous_decl)
16945         << Var->getDeclName();
16946     }
16947     return false;
16948   }
16949   // Prohibit structs with flexible array members too.
16950   // We cannot capture what is in the tail end of the struct.
16951   if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
16952     if (VTTy->getDecl()->hasFlexibleArrayMember()) {
16953       if (Diagnose) {
16954         if (IsBlock)
16955           S.Diag(Loc, diag::err_ref_flexarray_type);
16956         else
16957           S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
16958             << Var->getDeclName();
16959         S.Diag(Var->getLocation(), diag::note_previous_decl)
16960           << Var->getDeclName();
16961       }
16962       return false;
16963     }
16964   }
16965   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
16966   // Lambdas and captured statements are not allowed to capture __block
16967   // variables; they don't support the expected semantics.
16968   if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
16969     if (Diagnose) {
16970       S.Diag(Loc, diag::err_capture_block_variable)
16971         << Var->getDeclName() << !IsLambda;
16972       S.Diag(Var->getLocation(), diag::note_previous_decl)
16973         << Var->getDeclName();
16974     }
16975     return false;
16976   }
16977   // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
16978   if (S.getLangOpts().OpenCL && IsBlock &&
16979       Var->getType()->isBlockPointerType()) {
16980     if (Diagnose)
16981       S.Diag(Loc, diag::err_opencl_block_ref_block);
16982     return false;
16983   }
16984 
16985   return true;
16986 }
16987 
16988 // Returns true if the capture by block was successful.
16989 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
16990                                  SourceLocation Loc,
16991                                  const bool BuildAndDiagnose,
16992                                  QualType &CaptureType,
16993                                  QualType &DeclRefType,
16994                                  const bool Nested,
16995                                  Sema &S, bool Invalid) {
16996   bool ByRef = false;
16997 
16998   // Blocks are not allowed to capture arrays, excepting OpenCL.
16999   // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
17000   // (decayed to pointers).
17001   if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
17002     if (BuildAndDiagnose) {
17003       S.Diag(Loc, diag::err_ref_array_type);
17004       S.Diag(Var->getLocation(), diag::note_previous_decl)
17005       << Var->getDeclName();
17006       Invalid = true;
17007     } else {
17008       return false;
17009     }
17010   }
17011 
17012   // Forbid the block-capture of autoreleasing variables.
17013   if (!Invalid &&
17014       CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
17015     if (BuildAndDiagnose) {
17016       S.Diag(Loc, diag::err_arc_autoreleasing_capture)
17017         << /*block*/ 0;
17018       S.Diag(Var->getLocation(), diag::note_previous_decl)
17019         << Var->getDeclName();
17020       Invalid = true;
17021     } else {
17022       return false;
17023     }
17024   }
17025 
17026   // Warn about implicitly autoreleasing indirect parameters captured by blocks.
17027   if (const auto *PT = CaptureType->getAs<PointerType>()) {
17028     QualType PointeeTy = PT->getPointeeType();
17029 
17030     if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() &&
17031         PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
17032         !S.Context.hasDirectOwnershipQualifier(PointeeTy)) {
17033       if (BuildAndDiagnose) {
17034         SourceLocation VarLoc = Var->getLocation();
17035         S.Diag(Loc, diag::warn_block_capture_autoreleasing);
17036         S.Diag(VarLoc, diag::note_declare_parameter_strong);
17037       }
17038     }
17039   }
17040 
17041   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
17042   if (HasBlocksAttr || CaptureType->isReferenceType() ||
17043       (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) {
17044     // Block capture by reference does not change the capture or
17045     // declaration reference types.
17046     ByRef = true;
17047   } else {
17048     // Block capture by copy introduces 'const'.
17049     CaptureType = CaptureType.getNonReferenceType().withConst();
17050     DeclRefType = CaptureType;
17051   }
17052 
17053   // Actually capture the variable.
17054   if (BuildAndDiagnose)
17055     BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(),
17056                     CaptureType, Invalid);
17057 
17058   return !Invalid;
17059 }
17060 
17061 
17062 /// Capture the given variable in the captured region.
17063 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
17064                                     VarDecl *Var,
17065                                     SourceLocation Loc,
17066                                     const bool BuildAndDiagnose,
17067                                     QualType &CaptureType,
17068                                     QualType &DeclRefType,
17069                                     const bool RefersToCapturedVariable,
17070                                     Sema &S, bool Invalid) {
17071   // By default, capture variables by reference.
17072   bool ByRef = true;
17073   // Using an LValue reference type is consistent with Lambdas (see below).
17074   if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
17075     if (S.isOpenMPCapturedDecl(Var)) {
17076       bool HasConst = DeclRefType.isConstQualified();
17077       DeclRefType = DeclRefType.getUnqualifiedType();
17078       // Don't lose diagnostics about assignments to const.
17079       if (HasConst)
17080         DeclRefType.addConst();
17081     }
17082     // Do not capture firstprivates in tasks.
17083     if (S.isOpenMPPrivateDecl(Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel) !=
17084         OMPC_unknown)
17085       return true;
17086     ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel,
17087                                     RSI->OpenMPCaptureLevel);
17088   }
17089 
17090   if (ByRef)
17091     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
17092   else
17093     CaptureType = DeclRefType;
17094 
17095   // Actually capture the variable.
17096   if (BuildAndDiagnose)
17097     RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable,
17098                     Loc, SourceLocation(), CaptureType, Invalid);
17099 
17100   return !Invalid;
17101 }
17102 
17103 /// Capture the given variable in the lambda.
17104 static bool captureInLambda(LambdaScopeInfo *LSI,
17105                             VarDecl *Var,
17106                             SourceLocation Loc,
17107                             const bool BuildAndDiagnose,
17108                             QualType &CaptureType,
17109                             QualType &DeclRefType,
17110                             const bool RefersToCapturedVariable,
17111                             const Sema::TryCaptureKind Kind,
17112                             SourceLocation EllipsisLoc,
17113                             const bool IsTopScope,
17114                             Sema &S, bool Invalid) {
17115   // Determine whether we are capturing by reference or by value.
17116   bool ByRef = false;
17117   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
17118     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
17119   } else {
17120     ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
17121   }
17122 
17123   // Compute the type of the field that will capture this variable.
17124   if (ByRef) {
17125     // C++11 [expr.prim.lambda]p15:
17126     //   An entity is captured by reference if it is implicitly or
17127     //   explicitly captured but not captured by copy. It is
17128     //   unspecified whether additional unnamed non-static data
17129     //   members are declared in the closure type for entities
17130     //   captured by reference.
17131     //
17132     // FIXME: It is not clear whether we want to build an lvalue reference
17133     // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
17134     // to do the former, while EDG does the latter. Core issue 1249 will
17135     // clarify, but for now we follow GCC because it's a more permissive and
17136     // easily defensible position.
17137     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
17138   } else {
17139     // C++11 [expr.prim.lambda]p14:
17140     //   For each entity captured by copy, an unnamed non-static
17141     //   data member is declared in the closure type. The
17142     //   declaration order of these members is unspecified. The type
17143     //   of such a data member is the type of the corresponding
17144     //   captured entity if the entity is not a reference to an
17145     //   object, or the referenced type otherwise. [Note: If the
17146     //   captured entity is a reference to a function, the
17147     //   corresponding data member is also a reference to a
17148     //   function. - end note ]
17149     if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
17150       if (!RefType->getPointeeType()->isFunctionType())
17151         CaptureType = RefType->getPointeeType();
17152     }
17153 
17154     // Forbid the lambda copy-capture of autoreleasing variables.
17155     if (!Invalid &&
17156         CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
17157       if (BuildAndDiagnose) {
17158         S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
17159         S.Diag(Var->getLocation(), diag::note_previous_decl)
17160           << Var->getDeclName();
17161         Invalid = true;
17162       } else {
17163         return false;
17164       }
17165     }
17166 
17167     // Make sure that by-copy captures are of a complete and non-abstract type.
17168     if (!Invalid && BuildAndDiagnose) {
17169       if (!CaptureType->isDependentType() &&
17170           S.RequireCompleteSizedType(
17171               Loc, CaptureType,
17172               diag::err_capture_of_incomplete_or_sizeless_type,
17173               Var->getDeclName()))
17174         Invalid = true;
17175       else if (S.RequireNonAbstractType(Loc, CaptureType,
17176                                         diag::err_capture_of_abstract_type))
17177         Invalid = true;
17178     }
17179   }
17180 
17181   // Compute the type of a reference to this captured variable.
17182   if (ByRef)
17183     DeclRefType = CaptureType.getNonReferenceType();
17184   else {
17185     // C++ [expr.prim.lambda]p5:
17186     //   The closure type for a lambda-expression has a public inline
17187     //   function call operator [...]. This function call operator is
17188     //   declared const (9.3.1) if and only if the lambda-expression's
17189     //   parameter-declaration-clause is not followed by mutable.
17190     DeclRefType = CaptureType.getNonReferenceType();
17191     if (!LSI->Mutable && !CaptureType->isReferenceType())
17192       DeclRefType.addConst();
17193   }
17194 
17195   // Add the capture.
17196   if (BuildAndDiagnose)
17197     LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable,
17198                     Loc, EllipsisLoc, CaptureType, Invalid);
17199 
17200   return !Invalid;
17201 }
17202 
17203 bool Sema::tryCaptureVariable(
17204     VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
17205     SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
17206     QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
17207   // An init-capture is notionally from the context surrounding its
17208   // declaration, but its parent DC is the lambda class.
17209   DeclContext *VarDC = Var->getDeclContext();
17210   if (Var->isInitCapture())
17211     VarDC = VarDC->getParent();
17212 
17213   DeclContext *DC = CurContext;
17214   const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
17215       ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
17216   // We need to sync up the Declaration Context with the
17217   // FunctionScopeIndexToStopAt
17218   if (FunctionScopeIndexToStopAt) {
17219     unsigned FSIndex = FunctionScopes.size() - 1;
17220     while (FSIndex != MaxFunctionScopesIndex) {
17221       DC = getLambdaAwareParentOfDeclContext(DC);
17222       --FSIndex;
17223     }
17224   }
17225 
17226 
17227   // If the variable is declared in the current context, there is no need to
17228   // capture it.
17229   if (VarDC == DC) return true;
17230 
17231   // Capture global variables if it is required to use private copy of this
17232   // variable.
17233   bool IsGlobal = !Var->hasLocalStorage();
17234   if (IsGlobal &&
17235       !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true,
17236                                                 MaxFunctionScopesIndex)))
17237     return true;
17238   Var = Var->getCanonicalDecl();
17239 
17240   // Walk up the stack to determine whether we can capture the variable,
17241   // performing the "simple" checks that don't depend on type. We stop when
17242   // we've either hit the declared scope of the variable or find an existing
17243   // capture of that variable.  We start from the innermost capturing-entity
17244   // (the DC) and ensure that all intervening capturing-entities
17245   // (blocks/lambdas etc.) between the innermost capturer and the variable`s
17246   // declcontext can either capture the variable or have already captured
17247   // the variable.
17248   CaptureType = Var->getType();
17249   DeclRefType = CaptureType.getNonReferenceType();
17250   bool Nested = false;
17251   bool Explicit = (Kind != TryCapture_Implicit);
17252   unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
17253   do {
17254     // Only block literals, captured statements, and lambda expressions can
17255     // capture; other scopes don't work.
17256     DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
17257                                                               ExprLoc,
17258                                                               BuildAndDiagnose,
17259                                                               *this);
17260     // We need to check for the parent *first* because, if we *have*
17261     // private-captured a global variable, we need to recursively capture it in
17262     // intermediate blocks, lambdas, etc.
17263     if (!ParentDC) {
17264       if (IsGlobal) {
17265         FunctionScopesIndex = MaxFunctionScopesIndex - 1;
17266         break;
17267       }
17268       return true;
17269     }
17270 
17271     FunctionScopeInfo  *FSI = FunctionScopes[FunctionScopesIndex];
17272     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
17273 
17274 
17275     // Check whether we've already captured it.
17276     if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
17277                                              DeclRefType)) {
17278       CSI->getCapture(Var).markUsed(BuildAndDiagnose);
17279       break;
17280     }
17281     // If we are instantiating a generic lambda call operator body,
17282     // we do not want to capture new variables.  What was captured
17283     // during either a lambdas transformation or initial parsing
17284     // should be used.
17285     if (isGenericLambdaCallOperatorSpecialization(DC)) {
17286       if (BuildAndDiagnose) {
17287         LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
17288         if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
17289           Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
17290           Diag(Var->getLocation(), diag::note_previous_decl)
17291              << Var->getDeclName();
17292           Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
17293         } else
17294           diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
17295       }
17296       return true;
17297     }
17298 
17299     // Try to capture variable-length arrays types.
17300     if (Var->getType()->isVariablyModifiedType()) {
17301       // We're going to walk down into the type and look for VLA
17302       // expressions.
17303       QualType QTy = Var->getType();
17304       if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
17305         QTy = PVD->getOriginalType();
17306       captureVariablyModifiedType(Context, QTy, CSI);
17307     }
17308 
17309     if (getLangOpts().OpenMP) {
17310       if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
17311         // OpenMP private variables should not be captured in outer scope, so
17312         // just break here. Similarly, global variables that are captured in a
17313         // target region should not be captured outside the scope of the region.
17314         if (RSI->CapRegionKind == CR_OpenMP) {
17315           OpenMPClauseKind IsOpenMPPrivateDecl = isOpenMPPrivateDecl(
17316               Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel);
17317           // If the variable is private (i.e. not captured) and has variably
17318           // modified type, we still need to capture the type for correct
17319           // codegen in all regions, associated with the construct. Currently,
17320           // it is captured in the innermost captured region only.
17321           if (IsOpenMPPrivateDecl != OMPC_unknown &&
17322               Var->getType()->isVariablyModifiedType()) {
17323             QualType QTy = Var->getType();
17324             if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
17325               QTy = PVD->getOriginalType();
17326             for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel);
17327                  I < E; ++I) {
17328               auto *OuterRSI = cast<CapturedRegionScopeInfo>(
17329                   FunctionScopes[FunctionScopesIndex - I]);
17330               assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel &&
17331                      "Wrong number of captured regions associated with the "
17332                      "OpenMP construct.");
17333               captureVariablyModifiedType(Context, QTy, OuterRSI);
17334             }
17335           }
17336           bool IsTargetCap =
17337               IsOpenMPPrivateDecl != OMPC_private &&
17338               isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel,
17339                                          RSI->OpenMPCaptureLevel);
17340           // Do not capture global if it is not privatized in outer regions.
17341           bool IsGlobalCap =
17342               IsGlobal && isOpenMPGlobalCapturedDecl(Var, RSI->OpenMPLevel,
17343                                                      RSI->OpenMPCaptureLevel);
17344 
17345           // When we detect target captures we are looking from inside the
17346           // target region, therefore we need to propagate the capture from the
17347           // enclosing region. Therefore, the capture is not initially nested.
17348           if (IsTargetCap)
17349             adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel);
17350 
17351           if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private ||
17352               (IsGlobal && !IsGlobalCap)) {
17353             Nested = !IsTargetCap;
17354             DeclRefType = DeclRefType.getUnqualifiedType();
17355             CaptureType = Context.getLValueReferenceType(DeclRefType);
17356             break;
17357           }
17358         }
17359       }
17360     }
17361     if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
17362       // No capture-default, and this is not an explicit capture
17363       // so cannot capture this variable.
17364       if (BuildAndDiagnose) {
17365         Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
17366         Diag(Var->getLocation(), diag::note_previous_decl)
17367           << Var->getDeclName();
17368         if (cast<LambdaScopeInfo>(CSI)->Lambda)
17369           Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getBeginLoc(),
17370                diag::note_lambda_decl);
17371         // FIXME: If we error out because an outer lambda can not implicitly
17372         // capture a variable that an inner lambda explicitly captures, we
17373         // should have the inner lambda do the explicit capture - because
17374         // it makes for cleaner diagnostics later.  This would purely be done
17375         // so that the diagnostic does not misleadingly claim that a variable
17376         // can not be captured by a lambda implicitly even though it is captured
17377         // explicitly.  Suggestion:
17378         //  - create const bool VariableCaptureWasInitiallyExplicit = Explicit
17379         //    at the function head
17380         //  - cache the StartingDeclContext - this must be a lambda
17381         //  - captureInLambda in the innermost lambda the variable.
17382       }
17383       return true;
17384     }
17385 
17386     FunctionScopesIndex--;
17387     DC = ParentDC;
17388     Explicit = false;
17389   } while (!VarDC->Equals(DC));
17390 
17391   // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
17392   // computing the type of the capture at each step, checking type-specific
17393   // requirements, and adding captures if requested.
17394   // If the variable had already been captured previously, we start capturing
17395   // at the lambda nested within that one.
17396   bool Invalid = false;
17397   for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
17398        ++I) {
17399     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
17400 
17401     // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
17402     // certain types of variables (unnamed, variably modified types etc.)
17403     // so check for eligibility.
17404     if (!Invalid)
17405       Invalid =
17406           !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this);
17407 
17408     // After encountering an error, if we're actually supposed to capture, keep
17409     // capturing in nested contexts to suppress any follow-on diagnostics.
17410     if (Invalid && !BuildAndDiagnose)
17411       return true;
17412 
17413     if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
17414       Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
17415                                DeclRefType, Nested, *this, Invalid);
17416       Nested = true;
17417     } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
17418       Invalid = !captureInCapturedRegion(RSI, Var, ExprLoc, BuildAndDiagnose,
17419                                          CaptureType, DeclRefType, Nested,
17420                                          *this, Invalid);
17421       Nested = true;
17422     } else {
17423       LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
17424       Invalid =
17425           !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
17426                            DeclRefType, Nested, Kind, EllipsisLoc,
17427                            /*IsTopScope*/ I == N - 1, *this, Invalid);
17428       Nested = true;
17429     }
17430 
17431     if (Invalid && !BuildAndDiagnose)
17432       return true;
17433   }
17434   return Invalid;
17435 }
17436 
17437 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
17438                               TryCaptureKind Kind, SourceLocation EllipsisLoc) {
17439   QualType CaptureType;
17440   QualType DeclRefType;
17441   return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
17442                             /*BuildAndDiagnose=*/true, CaptureType,
17443                             DeclRefType, nullptr);
17444 }
17445 
17446 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
17447   QualType CaptureType;
17448   QualType DeclRefType;
17449   return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
17450                              /*BuildAndDiagnose=*/false, CaptureType,
17451                              DeclRefType, nullptr);
17452 }
17453 
17454 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
17455   QualType CaptureType;
17456   QualType DeclRefType;
17457 
17458   // Determine whether we can capture this variable.
17459   if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
17460                          /*BuildAndDiagnose=*/false, CaptureType,
17461                          DeclRefType, nullptr))
17462     return QualType();
17463 
17464   return DeclRefType;
17465 }
17466 
17467 namespace {
17468 // Helper to copy the template arguments from a DeclRefExpr or MemberExpr.
17469 // The produced TemplateArgumentListInfo* points to data stored within this
17470 // object, so should only be used in contexts where the pointer will not be
17471 // used after the CopiedTemplateArgs object is destroyed.
17472 class CopiedTemplateArgs {
17473   bool HasArgs;
17474   TemplateArgumentListInfo TemplateArgStorage;
17475 public:
17476   template<typename RefExpr>
17477   CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) {
17478     if (HasArgs)
17479       E->copyTemplateArgumentsInto(TemplateArgStorage);
17480   }
17481   operator TemplateArgumentListInfo*()
17482 #ifdef __has_cpp_attribute
17483 #if __has_cpp_attribute(clang::lifetimebound)
17484   [[clang::lifetimebound]]
17485 #endif
17486 #endif
17487   {
17488     return HasArgs ? &TemplateArgStorage : nullptr;
17489   }
17490 };
17491 }
17492 
17493 /// Walk the set of potential results of an expression and mark them all as
17494 /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason.
17495 ///
17496 /// \return A new expression if we found any potential results, ExprEmpty() if
17497 ///         not, and ExprError() if we diagnosed an error.
17498 static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E,
17499                                                       NonOdrUseReason NOUR) {
17500   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
17501   // an object that satisfies the requirements for appearing in a
17502   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
17503   // is immediately applied."  This function handles the lvalue-to-rvalue
17504   // conversion part.
17505   //
17506   // If we encounter a node that claims to be an odr-use but shouldn't be, we
17507   // transform it into the relevant kind of non-odr-use node and rebuild the
17508   // tree of nodes leading to it.
17509   //
17510   // This is a mini-TreeTransform that only transforms a restricted subset of
17511   // nodes (and only certain operands of them).
17512 
17513   // Rebuild a subexpression.
17514   auto Rebuild = [&](Expr *Sub) {
17515     return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR);
17516   };
17517 
17518   // Check whether a potential result satisfies the requirements of NOUR.
17519   auto IsPotentialResultOdrUsed = [&](NamedDecl *D) {
17520     // Any entity other than a VarDecl is always odr-used whenever it's named
17521     // in a potentially-evaluated expression.
17522     auto *VD = dyn_cast<VarDecl>(D);
17523     if (!VD)
17524       return true;
17525 
17526     // C++2a [basic.def.odr]p4:
17527     //   A variable x whose name appears as a potentially-evalauted expression
17528     //   e is odr-used by e unless
17529     //   -- x is a reference that is usable in constant expressions, or
17530     //   -- x is a variable of non-reference type that is usable in constant
17531     //      expressions and has no mutable subobjects, and e is an element of
17532     //      the set of potential results of an expression of
17533     //      non-volatile-qualified non-class type to which the lvalue-to-rvalue
17534     //      conversion is applied, or
17535     //   -- x is a variable of non-reference type, and e is an element of the
17536     //      set of potential results of a discarded-value expression to which
17537     //      the lvalue-to-rvalue conversion is not applied
17538     //
17539     // We check the first bullet and the "potentially-evaluated" condition in
17540     // BuildDeclRefExpr. We check the type requirements in the second bullet
17541     // in CheckLValueToRValueConversionOperand below.
17542     switch (NOUR) {
17543     case NOUR_None:
17544     case NOUR_Unevaluated:
17545       llvm_unreachable("unexpected non-odr-use-reason");
17546 
17547     case NOUR_Constant:
17548       // Constant references were handled when they were built.
17549       if (VD->getType()->isReferenceType())
17550         return true;
17551       if (auto *RD = VD->getType()->getAsCXXRecordDecl())
17552         if (RD->hasMutableFields())
17553           return true;
17554       if (!VD->isUsableInConstantExpressions(S.Context))
17555         return true;
17556       break;
17557 
17558     case NOUR_Discarded:
17559       if (VD->getType()->isReferenceType())
17560         return true;
17561       break;
17562     }
17563     return false;
17564   };
17565 
17566   // Mark that this expression does not constitute an odr-use.
17567   auto MarkNotOdrUsed = [&] {
17568     S.MaybeODRUseExprs.remove(E);
17569     if (LambdaScopeInfo *LSI = S.getCurLambda())
17570       LSI->markVariableExprAsNonODRUsed(E);
17571   };
17572 
17573   // C++2a [basic.def.odr]p2:
17574   //   The set of potential results of an expression e is defined as follows:
17575   switch (E->getStmtClass()) {
17576   //   -- If e is an id-expression, ...
17577   case Expr::DeclRefExprClass: {
17578     auto *DRE = cast<DeclRefExpr>(E);
17579     if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl()))
17580       break;
17581 
17582     // Rebuild as a non-odr-use DeclRefExpr.
17583     MarkNotOdrUsed();
17584     return DeclRefExpr::Create(
17585         S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(),
17586         DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(),
17587         DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(),
17588         DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR);
17589   }
17590 
17591   case Expr::FunctionParmPackExprClass: {
17592     auto *FPPE = cast<FunctionParmPackExpr>(E);
17593     // If any of the declarations in the pack is odr-used, then the expression
17594     // as a whole constitutes an odr-use.
17595     for (VarDecl *D : *FPPE)
17596       if (IsPotentialResultOdrUsed(D))
17597         return ExprEmpty();
17598 
17599     // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice,
17600     // nothing cares about whether we marked this as an odr-use, but it might
17601     // be useful for non-compiler tools.
17602     MarkNotOdrUsed();
17603     break;
17604   }
17605 
17606   //   -- If e is a subscripting operation with an array operand...
17607   case Expr::ArraySubscriptExprClass: {
17608     auto *ASE = cast<ArraySubscriptExpr>(E);
17609     Expr *OldBase = ASE->getBase()->IgnoreImplicit();
17610     if (!OldBase->getType()->isArrayType())
17611       break;
17612     ExprResult Base = Rebuild(OldBase);
17613     if (!Base.isUsable())
17614       return Base;
17615     Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS();
17616     Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS();
17617     SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored.
17618     return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS,
17619                                      ASE->getRBracketLoc());
17620   }
17621 
17622   case Expr::MemberExprClass: {
17623     auto *ME = cast<MemberExpr>(E);
17624     // -- If e is a class member access expression [...] naming a non-static
17625     //    data member...
17626     if (isa<FieldDecl>(ME->getMemberDecl())) {
17627       ExprResult Base = Rebuild(ME->getBase());
17628       if (!Base.isUsable())
17629         return Base;
17630       return MemberExpr::Create(
17631           S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(),
17632           ME->getQualifierLoc(), ME->getTemplateKeywordLoc(),
17633           ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(),
17634           CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(),
17635           ME->getObjectKind(), ME->isNonOdrUse());
17636     }
17637 
17638     if (ME->getMemberDecl()->isCXXInstanceMember())
17639       break;
17640 
17641     // -- If e is a class member access expression naming a static data member,
17642     //    ...
17643     if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl()))
17644       break;
17645 
17646     // Rebuild as a non-odr-use MemberExpr.
17647     MarkNotOdrUsed();
17648     return MemberExpr::Create(
17649         S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(),
17650         ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(),
17651         ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME),
17652         ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR);
17653     return ExprEmpty();
17654   }
17655 
17656   case Expr::BinaryOperatorClass: {
17657     auto *BO = cast<BinaryOperator>(E);
17658     Expr *LHS = BO->getLHS();
17659     Expr *RHS = BO->getRHS();
17660     // -- If e is a pointer-to-member expression of the form e1 .* e2 ...
17661     if (BO->getOpcode() == BO_PtrMemD) {
17662       ExprResult Sub = Rebuild(LHS);
17663       if (!Sub.isUsable())
17664         return Sub;
17665       LHS = Sub.get();
17666     //   -- If e is a comma expression, ...
17667     } else if (BO->getOpcode() == BO_Comma) {
17668       ExprResult Sub = Rebuild(RHS);
17669       if (!Sub.isUsable())
17670         return Sub;
17671       RHS = Sub.get();
17672     } else {
17673       break;
17674     }
17675     return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(),
17676                         LHS, RHS);
17677   }
17678 
17679   //   -- If e has the form (e1)...
17680   case Expr::ParenExprClass: {
17681     auto *PE = cast<ParenExpr>(E);
17682     ExprResult Sub = Rebuild(PE->getSubExpr());
17683     if (!Sub.isUsable())
17684       return Sub;
17685     return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get());
17686   }
17687 
17688   //   -- If e is a glvalue conditional expression, ...
17689   // We don't apply this to a binary conditional operator. FIXME: Should we?
17690   case Expr::ConditionalOperatorClass: {
17691     auto *CO = cast<ConditionalOperator>(E);
17692     ExprResult LHS = Rebuild(CO->getLHS());
17693     if (LHS.isInvalid())
17694       return ExprError();
17695     ExprResult RHS = Rebuild(CO->getRHS());
17696     if (RHS.isInvalid())
17697       return ExprError();
17698     if (!LHS.isUsable() && !RHS.isUsable())
17699       return ExprEmpty();
17700     if (!LHS.isUsable())
17701       LHS = CO->getLHS();
17702     if (!RHS.isUsable())
17703       RHS = CO->getRHS();
17704     return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(),
17705                                 CO->getCond(), LHS.get(), RHS.get());
17706   }
17707 
17708   // [Clang extension]
17709   //   -- If e has the form __extension__ e1...
17710   case Expr::UnaryOperatorClass: {
17711     auto *UO = cast<UnaryOperator>(E);
17712     if (UO->getOpcode() != UO_Extension)
17713       break;
17714     ExprResult Sub = Rebuild(UO->getSubExpr());
17715     if (!Sub.isUsable())
17716       return Sub;
17717     return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension,
17718                           Sub.get());
17719   }
17720 
17721   // [Clang extension]
17722   //   -- If e has the form _Generic(...), the set of potential results is the
17723   //      union of the sets of potential results of the associated expressions.
17724   case Expr::GenericSelectionExprClass: {
17725     auto *GSE = cast<GenericSelectionExpr>(E);
17726 
17727     SmallVector<Expr *, 4> AssocExprs;
17728     bool AnyChanged = false;
17729     for (Expr *OrigAssocExpr : GSE->getAssocExprs()) {
17730       ExprResult AssocExpr = Rebuild(OrigAssocExpr);
17731       if (AssocExpr.isInvalid())
17732         return ExprError();
17733       if (AssocExpr.isUsable()) {
17734         AssocExprs.push_back(AssocExpr.get());
17735         AnyChanged = true;
17736       } else {
17737         AssocExprs.push_back(OrigAssocExpr);
17738       }
17739     }
17740 
17741     return AnyChanged ? S.CreateGenericSelectionExpr(
17742                             GSE->getGenericLoc(), GSE->getDefaultLoc(),
17743                             GSE->getRParenLoc(), GSE->getControllingExpr(),
17744                             GSE->getAssocTypeSourceInfos(), AssocExprs)
17745                       : ExprEmpty();
17746   }
17747 
17748   // [Clang extension]
17749   //   -- If e has the form __builtin_choose_expr(...), the set of potential
17750   //      results is the union of the sets of potential results of the
17751   //      second and third subexpressions.
17752   case Expr::ChooseExprClass: {
17753     auto *CE = cast<ChooseExpr>(E);
17754 
17755     ExprResult LHS = Rebuild(CE->getLHS());
17756     if (LHS.isInvalid())
17757       return ExprError();
17758 
17759     ExprResult RHS = Rebuild(CE->getLHS());
17760     if (RHS.isInvalid())
17761       return ExprError();
17762 
17763     if (!LHS.get() && !RHS.get())
17764       return ExprEmpty();
17765     if (!LHS.isUsable())
17766       LHS = CE->getLHS();
17767     if (!RHS.isUsable())
17768       RHS = CE->getRHS();
17769 
17770     return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(),
17771                              RHS.get(), CE->getRParenLoc());
17772   }
17773 
17774   // Step through non-syntactic nodes.
17775   case Expr::ConstantExprClass: {
17776     auto *CE = cast<ConstantExpr>(E);
17777     ExprResult Sub = Rebuild(CE->getSubExpr());
17778     if (!Sub.isUsable())
17779       return Sub;
17780     return ConstantExpr::Create(S.Context, Sub.get());
17781   }
17782 
17783   // We could mostly rely on the recursive rebuilding to rebuild implicit
17784   // casts, but not at the top level, so rebuild them here.
17785   case Expr::ImplicitCastExprClass: {
17786     auto *ICE = cast<ImplicitCastExpr>(E);
17787     // Only step through the narrow set of cast kinds we expect to encounter.
17788     // Anything else suggests we've left the region in which potential results
17789     // can be found.
17790     switch (ICE->getCastKind()) {
17791     case CK_NoOp:
17792     case CK_DerivedToBase:
17793     case CK_UncheckedDerivedToBase: {
17794       ExprResult Sub = Rebuild(ICE->getSubExpr());
17795       if (!Sub.isUsable())
17796         return Sub;
17797       CXXCastPath Path(ICE->path());
17798       return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(),
17799                                  ICE->getValueKind(), &Path);
17800     }
17801 
17802     default:
17803       break;
17804     }
17805     break;
17806   }
17807 
17808   default:
17809     break;
17810   }
17811 
17812   // Can't traverse through this node. Nothing to do.
17813   return ExprEmpty();
17814 }
17815 
17816 ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) {
17817   // Check whether the operand is or contains an object of non-trivial C union
17818   // type.
17819   if (E->getType().isVolatileQualified() &&
17820       (E->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
17821        E->getType().hasNonTrivialToPrimitiveCopyCUnion()))
17822     checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
17823                           Sema::NTCUC_LValueToRValueVolatile,
17824                           NTCUK_Destruct|NTCUK_Copy);
17825 
17826   // C++2a [basic.def.odr]p4:
17827   //   [...] an expression of non-volatile-qualified non-class type to which
17828   //   the lvalue-to-rvalue conversion is applied [...]
17829   if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>())
17830     return E;
17831 
17832   ExprResult Result =
17833       rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant);
17834   if (Result.isInvalid())
17835     return ExprError();
17836   return Result.get() ? Result : E;
17837 }
17838 
17839 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
17840   Res = CorrectDelayedTyposInExpr(Res);
17841 
17842   if (!Res.isUsable())
17843     return Res;
17844 
17845   // If a constant-expression is a reference to a variable where we delay
17846   // deciding whether it is an odr-use, just assume we will apply the
17847   // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
17848   // (a non-type template argument), we have special handling anyway.
17849   return CheckLValueToRValueConversionOperand(Res.get());
17850 }
17851 
17852 void Sema::CleanupVarDeclMarking() {
17853   // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
17854   // call.
17855   MaybeODRUseExprSet LocalMaybeODRUseExprs;
17856   std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs);
17857 
17858   for (Expr *E : LocalMaybeODRUseExprs) {
17859     if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
17860       MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()),
17861                          DRE->getLocation(), *this);
17862     } else if (auto *ME = dyn_cast<MemberExpr>(E)) {
17863       MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(),
17864                          *this);
17865     } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) {
17866       for (VarDecl *VD : *FP)
17867         MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this);
17868     } else {
17869       llvm_unreachable("Unexpected expression");
17870     }
17871   }
17872 
17873   assert(MaybeODRUseExprs.empty() &&
17874          "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?");
17875 }
17876 
17877 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
17878                                     VarDecl *Var, Expr *E) {
17879   assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||
17880           isa<FunctionParmPackExpr>(E)) &&
17881          "Invalid Expr argument to DoMarkVarDeclReferenced");
17882   Var->setReferenced();
17883 
17884   if (Var->isInvalidDecl())
17885     return;
17886 
17887   auto *MSI = Var->getMemberSpecializationInfo();
17888   TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind()
17889                                        : Var->getTemplateSpecializationKind();
17890 
17891   OdrUseContext OdrUse = isOdrUseContext(SemaRef);
17892   bool UsableInConstantExpr =
17893       Var->mightBeUsableInConstantExpressions(SemaRef.Context);
17894 
17895   // C++20 [expr.const]p12:
17896   //   A variable [...] is needed for constant evaluation if it is [...] a
17897   //   variable whose name appears as a potentially constant evaluated
17898   //   expression that is either a contexpr variable or is of non-volatile
17899   //   const-qualified integral type or of reference type
17900   bool NeededForConstantEvaluation =
17901       isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr;
17902 
17903   bool NeedDefinition =
17904       OdrUse == OdrUseContext::Used || NeededForConstantEvaluation;
17905 
17906   VarTemplateSpecializationDecl *VarSpec =
17907       dyn_cast<VarTemplateSpecializationDecl>(Var);
17908   assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
17909          "Can't instantiate a partial template specialization.");
17910 
17911   // If this might be a member specialization of a static data member, check
17912   // the specialization is visible. We already did the checks for variable
17913   // template specializations when we created them.
17914   if (NeedDefinition && TSK != TSK_Undeclared &&
17915       !isa<VarTemplateSpecializationDecl>(Var))
17916     SemaRef.checkSpecializationVisibility(Loc, Var);
17917 
17918   // Perform implicit instantiation of static data members, static data member
17919   // templates of class templates, and variable template specializations. Delay
17920   // instantiations of variable templates, except for those that could be used
17921   // in a constant expression.
17922   if (NeedDefinition && isTemplateInstantiation(TSK)) {
17923     // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
17924     // instantiation declaration if a variable is usable in a constant
17925     // expression (among other cases).
17926     bool TryInstantiating =
17927         TSK == TSK_ImplicitInstantiation ||
17928         (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
17929 
17930     if (TryInstantiating) {
17931       SourceLocation PointOfInstantiation =
17932           MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation();
17933       bool FirstInstantiation = PointOfInstantiation.isInvalid();
17934       if (FirstInstantiation) {
17935         PointOfInstantiation = Loc;
17936         if (MSI)
17937           MSI->setPointOfInstantiation(PointOfInstantiation);
17938         else
17939           Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
17940       }
17941 
17942       bool InstantiationDependent = false;
17943       bool IsNonDependent =
17944           VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
17945                         VarSpec->getTemplateArgsInfo(), InstantiationDependent)
17946                   : true;
17947 
17948       // Do not instantiate specializations that are still type-dependent.
17949       if (IsNonDependent) {
17950         if (UsableInConstantExpr) {
17951           // Do not defer instantiations of variables that could be used in a
17952           // constant expression.
17953           SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] {
17954             SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
17955           });
17956         } else if (FirstInstantiation ||
17957                    isa<VarTemplateSpecializationDecl>(Var)) {
17958           // FIXME: For a specialization of a variable template, we don't
17959           // distinguish between "declaration and type implicitly instantiated"
17960           // and "implicit instantiation of definition requested", so we have
17961           // no direct way to avoid enqueueing the pending instantiation
17962           // multiple times.
17963           SemaRef.PendingInstantiations
17964               .push_back(std::make_pair(Var, PointOfInstantiation));
17965         }
17966       }
17967     }
17968   }
17969 
17970   // C++2a [basic.def.odr]p4:
17971   //   A variable x whose name appears as a potentially-evaluated expression e
17972   //   is odr-used by e unless
17973   //   -- x is a reference that is usable in constant expressions
17974   //   -- x is a variable of non-reference type that is usable in constant
17975   //      expressions and has no mutable subobjects [FIXME], and e is an
17976   //      element of the set of potential results of an expression of
17977   //      non-volatile-qualified non-class type to which the lvalue-to-rvalue
17978   //      conversion is applied
17979   //   -- x is a variable of non-reference type, and e is an element of the set
17980   //      of potential results of a discarded-value expression to which the
17981   //      lvalue-to-rvalue conversion is not applied [FIXME]
17982   //
17983   // We check the first part of the second bullet here, and
17984   // Sema::CheckLValueToRValueConversionOperand deals with the second part.
17985   // FIXME: To get the third bullet right, we need to delay this even for
17986   // variables that are not usable in constant expressions.
17987 
17988   // If we already know this isn't an odr-use, there's nothing more to do.
17989   if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E))
17990     if (DRE->isNonOdrUse())
17991       return;
17992   if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E))
17993     if (ME->isNonOdrUse())
17994       return;
17995 
17996   switch (OdrUse) {
17997   case OdrUseContext::None:
17998     assert((!E || isa<FunctionParmPackExpr>(E)) &&
17999            "missing non-odr-use marking for unevaluated decl ref");
18000     break;
18001 
18002   case OdrUseContext::FormallyOdrUsed:
18003     // FIXME: Ignoring formal odr-uses results in incorrect lambda capture
18004     // behavior.
18005     break;
18006 
18007   case OdrUseContext::Used:
18008     // If we might later find that this expression isn't actually an odr-use,
18009     // delay the marking.
18010     if (E && Var->isUsableInConstantExpressions(SemaRef.Context))
18011       SemaRef.MaybeODRUseExprs.insert(E);
18012     else
18013       MarkVarDeclODRUsed(Var, Loc, SemaRef);
18014     break;
18015 
18016   case OdrUseContext::Dependent:
18017     // If this is a dependent context, we don't need to mark variables as
18018     // odr-used, but we may still need to track them for lambda capture.
18019     // FIXME: Do we also need to do this inside dependent typeid expressions
18020     // (which are modeled as unevaluated at this point)?
18021     const bool RefersToEnclosingScope =
18022         (SemaRef.CurContext != Var->getDeclContext() &&
18023          Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
18024     if (RefersToEnclosingScope) {
18025       LambdaScopeInfo *const LSI =
18026           SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
18027       if (LSI && (!LSI->CallOperator ||
18028                   !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
18029         // If a variable could potentially be odr-used, defer marking it so
18030         // until we finish analyzing the full expression for any
18031         // lvalue-to-rvalue
18032         // or discarded value conversions that would obviate odr-use.
18033         // Add it to the list of potential captures that will be analyzed
18034         // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
18035         // unless the variable is a reference that was initialized by a constant
18036         // expression (this will never need to be captured or odr-used).
18037         //
18038         // FIXME: We can simplify this a lot after implementing P0588R1.
18039         assert(E && "Capture variable should be used in an expression.");
18040         if (!Var->getType()->isReferenceType() ||
18041             !Var->isUsableInConstantExpressions(SemaRef.Context))
18042           LSI->addPotentialCapture(E->IgnoreParens());
18043       }
18044     }
18045     break;
18046   }
18047 }
18048 
18049 /// Mark a variable referenced, and check whether it is odr-used
18050 /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
18051 /// used directly for normal expressions referring to VarDecl.
18052 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
18053   DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
18054 }
18055 
18056 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
18057                                Decl *D, Expr *E, bool MightBeOdrUse) {
18058   if (SemaRef.isInOpenMPDeclareTargetContext())
18059     SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
18060 
18061   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
18062     DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
18063     return;
18064   }
18065 
18066   SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
18067 
18068   // If this is a call to a method via a cast, also mark the method in the
18069   // derived class used in case codegen can devirtualize the call.
18070   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
18071   if (!ME)
18072     return;
18073   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
18074   if (!MD)
18075     return;
18076   // Only attempt to devirtualize if this is truly a virtual call.
18077   bool IsVirtualCall = MD->isVirtual() &&
18078                           ME->performsVirtualDispatch(SemaRef.getLangOpts());
18079   if (!IsVirtualCall)
18080     return;
18081 
18082   // If it's possible to devirtualize the call, mark the called function
18083   // referenced.
18084   CXXMethodDecl *DM = MD->getDevirtualizedMethod(
18085       ME->getBase(), SemaRef.getLangOpts().AppleKext);
18086   if (DM)
18087     SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
18088 }
18089 
18090 /// Perform reference-marking and odr-use handling for a DeclRefExpr.
18091 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) {
18092   // TODO: update this with DR# once a defect report is filed.
18093   // C++11 defect. The address of a pure member should not be an ODR use, even
18094   // if it's a qualified reference.
18095   bool OdrUse = true;
18096   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
18097     if (Method->isVirtual() &&
18098         !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
18099       OdrUse = false;
18100 
18101   if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl()))
18102     if (!isConstantEvaluated() && FD->isConsteval() &&
18103         !RebuildingImmediateInvocation)
18104       ExprEvalContexts.back().ReferenceToConsteval.insert(E);
18105   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
18106 }
18107 
18108 /// Perform reference-marking and odr-use handling for a MemberExpr.
18109 void Sema::MarkMemberReferenced(MemberExpr *E) {
18110   // C++11 [basic.def.odr]p2:
18111   //   A non-overloaded function whose name appears as a potentially-evaluated
18112   //   expression or a member of a set of candidate functions, if selected by
18113   //   overload resolution when referred to from a potentially-evaluated
18114   //   expression, is odr-used, unless it is a pure virtual function and its
18115   //   name is not explicitly qualified.
18116   bool MightBeOdrUse = true;
18117   if (E->performsVirtualDispatch(getLangOpts())) {
18118     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
18119       if (Method->isPure())
18120         MightBeOdrUse = false;
18121   }
18122   SourceLocation Loc =
18123       E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
18124   MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse);
18125 }
18126 
18127 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr.
18128 void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) {
18129   for (VarDecl *VD : *E)
18130     MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true);
18131 }
18132 
18133 /// Perform marking for a reference to an arbitrary declaration.  It
18134 /// marks the declaration referenced, and performs odr-use checking for
18135 /// functions and variables. This method should not be used when building a
18136 /// normal expression which refers to a variable.
18137 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
18138                                  bool MightBeOdrUse) {
18139   if (MightBeOdrUse) {
18140     if (auto *VD = dyn_cast<VarDecl>(D)) {
18141       MarkVariableReferenced(Loc, VD);
18142       return;
18143     }
18144   }
18145   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
18146     MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
18147     return;
18148   }
18149   D->setReferenced();
18150 }
18151 
18152 namespace {
18153   // Mark all of the declarations used by a type as referenced.
18154   // FIXME: Not fully implemented yet! We need to have a better understanding
18155   // of when we're entering a context we should not recurse into.
18156   // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
18157   // TreeTransforms rebuilding the type in a new context. Rather than
18158   // duplicating the TreeTransform logic, we should consider reusing it here.
18159   // Currently that causes problems when rebuilding LambdaExprs.
18160   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
18161     Sema &S;
18162     SourceLocation Loc;
18163 
18164   public:
18165     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
18166 
18167     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
18168 
18169     bool TraverseTemplateArgument(const TemplateArgument &Arg);
18170   };
18171 }
18172 
18173 bool MarkReferencedDecls::TraverseTemplateArgument(
18174     const TemplateArgument &Arg) {
18175   {
18176     // A non-type template argument is a constant-evaluated context.
18177     EnterExpressionEvaluationContext Evaluated(
18178         S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
18179     if (Arg.getKind() == TemplateArgument::Declaration) {
18180       if (Decl *D = Arg.getAsDecl())
18181         S.MarkAnyDeclReferenced(Loc, D, true);
18182     } else if (Arg.getKind() == TemplateArgument::Expression) {
18183       S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false);
18184     }
18185   }
18186 
18187   return Inherited::TraverseTemplateArgument(Arg);
18188 }
18189 
18190 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
18191   MarkReferencedDecls Marker(*this, Loc);
18192   Marker.TraverseType(T);
18193 }
18194 
18195 namespace {
18196 /// Helper class that marks all of the declarations referenced by
18197 /// potentially-evaluated subexpressions as "referenced".
18198 class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> {
18199 public:
18200   typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited;
18201   bool SkipLocalVariables;
18202 
18203   EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
18204       : Inherited(S), SkipLocalVariables(SkipLocalVariables) {}
18205 
18206   void visitUsedDecl(SourceLocation Loc, Decl *D) {
18207     S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D));
18208   }
18209 
18210   void VisitDeclRefExpr(DeclRefExpr *E) {
18211     // If we were asked not to visit local variables, don't.
18212     if (SkipLocalVariables) {
18213       if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
18214         if (VD->hasLocalStorage())
18215           return;
18216     }
18217     S.MarkDeclRefReferenced(E);
18218   }
18219 
18220   void VisitMemberExpr(MemberExpr *E) {
18221     S.MarkMemberReferenced(E);
18222     Visit(E->getBase());
18223   }
18224 };
18225 } // namespace
18226 
18227 /// Mark any declarations that appear within this expression or any
18228 /// potentially-evaluated subexpressions as "referenced".
18229 ///
18230 /// \param SkipLocalVariables If true, don't mark local variables as
18231 /// 'referenced'.
18232 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
18233                                             bool SkipLocalVariables) {
18234   EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
18235 }
18236 
18237 /// Emit a diagnostic that describes an effect on the run-time behavior
18238 /// of the program being compiled.
18239 ///
18240 /// This routine emits the given diagnostic when the code currently being
18241 /// type-checked is "potentially evaluated", meaning that there is a
18242 /// possibility that the code will actually be executable. Code in sizeof()
18243 /// expressions, code used only during overload resolution, etc., are not
18244 /// potentially evaluated. This routine will suppress such diagnostics or,
18245 /// in the absolutely nutty case of potentially potentially evaluated
18246 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
18247 /// later.
18248 ///
18249 /// This routine should be used for all diagnostics that describe the run-time
18250 /// behavior of a program, such as passing a non-POD value through an ellipsis.
18251 /// Failure to do so will likely result in spurious diagnostics or failures
18252 /// during overload resolution or within sizeof/alignof/typeof/typeid.
18253 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts,
18254                                const PartialDiagnostic &PD) {
18255   switch (ExprEvalContexts.back().Context) {
18256   case ExpressionEvaluationContext::Unevaluated:
18257   case ExpressionEvaluationContext::UnevaluatedList:
18258   case ExpressionEvaluationContext::UnevaluatedAbstract:
18259   case ExpressionEvaluationContext::DiscardedStatement:
18260     // The argument will never be evaluated, so don't complain.
18261     break;
18262 
18263   case ExpressionEvaluationContext::ConstantEvaluated:
18264     // Relevant diagnostics should be produced by constant evaluation.
18265     break;
18266 
18267   case ExpressionEvaluationContext::PotentiallyEvaluated:
18268   case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
18269     if (!Stmts.empty() && getCurFunctionOrMethodDecl()) {
18270       FunctionScopes.back()->PossiblyUnreachableDiags.
18271         push_back(sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
18272       return true;
18273     }
18274 
18275     // The initializer of a constexpr variable or of the first declaration of a
18276     // static data member is not syntactically a constant evaluated constant,
18277     // but nonetheless is always required to be a constant expression, so we
18278     // can skip diagnosing.
18279     // FIXME: Using the mangling context here is a hack.
18280     if (auto *VD = dyn_cast_or_null<VarDecl>(
18281             ExprEvalContexts.back().ManglingContextDecl)) {
18282       if (VD->isConstexpr() ||
18283           (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline()))
18284         break;
18285       // FIXME: For any other kind of variable, we should build a CFG for its
18286       // initializer and check whether the context in question is reachable.
18287     }
18288 
18289     Diag(Loc, PD);
18290     return true;
18291   }
18292 
18293   return false;
18294 }
18295 
18296 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
18297                                const PartialDiagnostic &PD) {
18298   return DiagRuntimeBehavior(
18299       Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD);
18300 }
18301 
18302 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
18303                                CallExpr *CE, FunctionDecl *FD) {
18304   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
18305     return false;
18306 
18307   // If we're inside a decltype's expression, don't check for a valid return
18308   // type or construct temporaries until we know whether this is the last call.
18309   if (ExprEvalContexts.back().ExprContext ==
18310       ExpressionEvaluationContextRecord::EK_Decltype) {
18311     ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
18312     return false;
18313   }
18314 
18315   class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
18316     FunctionDecl *FD;
18317     CallExpr *CE;
18318 
18319   public:
18320     CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
18321       : FD(FD), CE(CE) { }
18322 
18323     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
18324       if (!FD) {
18325         S.Diag(Loc, diag::err_call_incomplete_return)
18326           << T << CE->getSourceRange();
18327         return;
18328       }
18329 
18330       S.Diag(Loc, diag::err_call_function_incomplete_return)
18331         << CE->getSourceRange() << FD->getDeclName() << T;
18332       S.Diag(FD->getLocation(), diag::note_entity_declared_at)
18333           << FD->getDeclName();
18334     }
18335   } Diagnoser(FD, CE);
18336 
18337   if (RequireCompleteType(Loc, ReturnType, Diagnoser))
18338     return true;
18339 
18340   return false;
18341 }
18342 
18343 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
18344 // will prevent this condition from triggering, which is what we want.
18345 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
18346   SourceLocation Loc;
18347 
18348   unsigned diagnostic = diag::warn_condition_is_assignment;
18349   bool IsOrAssign = false;
18350 
18351   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
18352     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
18353       return;
18354 
18355     IsOrAssign = Op->getOpcode() == BO_OrAssign;
18356 
18357     // Greylist some idioms by putting them into a warning subcategory.
18358     if (ObjCMessageExpr *ME
18359           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
18360       Selector Sel = ME->getSelector();
18361 
18362       // self = [<foo> init...]
18363       if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
18364         diagnostic = diag::warn_condition_is_idiomatic_assignment;
18365 
18366       // <foo> = [<bar> nextObject]
18367       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
18368         diagnostic = diag::warn_condition_is_idiomatic_assignment;
18369     }
18370 
18371     Loc = Op->getOperatorLoc();
18372   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
18373     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
18374       return;
18375 
18376     IsOrAssign = Op->getOperator() == OO_PipeEqual;
18377     Loc = Op->getOperatorLoc();
18378   } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
18379     return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
18380   else {
18381     // Not an assignment.
18382     return;
18383   }
18384 
18385   Diag(Loc, diagnostic) << E->getSourceRange();
18386 
18387   SourceLocation Open = E->getBeginLoc();
18388   SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
18389   Diag(Loc, diag::note_condition_assign_silence)
18390         << FixItHint::CreateInsertion(Open, "(")
18391         << FixItHint::CreateInsertion(Close, ")");
18392 
18393   if (IsOrAssign)
18394     Diag(Loc, diag::note_condition_or_assign_to_comparison)
18395       << FixItHint::CreateReplacement(Loc, "!=");
18396   else
18397     Diag(Loc, diag::note_condition_assign_to_comparison)
18398       << FixItHint::CreateReplacement(Loc, "==");
18399 }
18400 
18401 /// Redundant parentheses over an equality comparison can indicate
18402 /// that the user intended an assignment used as condition.
18403 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
18404   // Don't warn if the parens came from a macro.
18405   SourceLocation parenLoc = ParenE->getBeginLoc();
18406   if (parenLoc.isInvalid() || parenLoc.isMacroID())
18407     return;
18408   // Don't warn for dependent expressions.
18409   if (ParenE->isTypeDependent())
18410     return;
18411 
18412   Expr *E = ParenE->IgnoreParens();
18413 
18414   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
18415     if (opE->getOpcode() == BO_EQ &&
18416         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
18417                                                            == Expr::MLV_Valid) {
18418       SourceLocation Loc = opE->getOperatorLoc();
18419 
18420       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
18421       SourceRange ParenERange = ParenE->getSourceRange();
18422       Diag(Loc, diag::note_equality_comparison_silence)
18423         << FixItHint::CreateRemoval(ParenERange.getBegin())
18424         << FixItHint::CreateRemoval(ParenERange.getEnd());
18425       Diag(Loc, diag::note_equality_comparison_to_assign)
18426         << FixItHint::CreateReplacement(Loc, "=");
18427     }
18428 }
18429 
18430 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
18431                                        bool IsConstexpr) {
18432   DiagnoseAssignmentAsCondition(E);
18433   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
18434     DiagnoseEqualityWithExtraParens(parenE);
18435 
18436   ExprResult result = CheckPlaceholderExpr(E);
18437   if (result.isInvalid()) return ExprError();
18438   E = result.get();
18439 
18440   if (!E->isTypeDependent()) {
18441     if (getLangOpts().CPlusPlus)
18442       return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
18443 
18444     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
18445     if (ERes.isInvalid())
18446       return ExprError();
18447     E = ERes.get();
18448 
18449     QualType T = E->getType();
18450     if (!T->isScalarType()) { // C99 6.8.4.1p1
18451       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
18452         << T << E->getSourceRange();
18453       return ExprError();
18454     }
18455     CheckBoolLikeConversion(E, Loc);
18456   }
18457 
18458   return E;
18459 }
18460 
18461 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
18462                                            Expr *SubExpr, ConditionKind CK) {
18463   // Empty conditions are valid in for-statements.
18464   if (!SubExpr)
18465     return ConditionResult();
18466 
18467   ExprResult Cond;
18468   switch (CK) {
18469   case ConditionKind::Boolean:
18470     Cond = CheckBooleanCondition(Loc, SubExpr);
18471     break;
18472 
18473   case ConditionKind::ConstexprIf:
18474     Cond = CheckBooleanCondition(Loc, SubExpr, true);
18475     break;
18476 
18477   case ConditionKind::Switch:
18478     Cond = CheckSwitchCondition(Loc, SubExpr);
18479     break;
18480   }
18481   if (Cond.isInvalid())
18482     return ConditionError();
18483 
18484   // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
18485   FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
18486   if (!FullExpr.get())
18487     return ConditionError();
18488 
18489   return ConditionResult(*this, nullptr, FullExpr,
18490                          CK == ConditionKind::ConstexprIf);
18491 }
18492 
18493 namespace {
18494   /// A visitor for rebuilding a call to an __unknown_any expression
18495   /// to have an appropriate type.
18496   struct RebuildUnknownAnyFunction
18497     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
18498 
18499     Sema &S;
18500 
18501     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
18502 
18503     ExprResult VisitStmt(Stmt *S) {
18504       llvm_unreachable("unexpected statement!");
18505     }
18506 
18507     ExprResult VisitExpr(Expr *E) {
18508       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
18509         << E->getSourceRange();
18510       return ExprError();
18511     }
18512 
18513     /// Rebuild an expression which simply semantically wraps another
18514     /// expression which it shares the type and value kind of.
18515     template <class T> ExprResult rebuildSugarExpr(T *E) {
18516       ExprResult SubResult = Visit(E->getSubExpr());
18517       if (SubResult.isInvalid()) return ExprError();
18518 
18519       Expr *SubExpr = SubResult.get();
18520       E->setSubExpr(SubExpr);
18521       E->setType(SubExpr->getType());
18522       E->setValueKind(SubExpr->getValueKind());
18523       assert(E->getObjectKind() == OK_Ordinary);
18524       return E;
18525     }
18526 
18527     ExprResult VisitParenExpr(ParenExpr *E) {
18528       return rebuildSugarExpr(E);
18529     }
18530 
18531     ExprResult VisitUnaryExtension(UnaryOperator *E) {
18532       return rebuildSugarExpr(E);
18533     }
18534 
18535     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
18536       ExprResult SubResult = Visit(E->getSubExpr());
18537       if (SubResult.isInvalid()) return ExprError();
18538 
18539       Expr *SubExpr = SubResult.get();
18540       E->setSubExpr(SubExpr);
18541       E->setType(S.Context.getPointerType(SubExpr->getType()));
18542       assert(E->getValueKind() == VK_RValue);
18543       assert(E->getObjectKind() == OK_Ordinary);
18544       return E;
18545     }
18546 
18547     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
18548       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
18549 
18550       E->setType(VD->getType());
18551 
18552       assert(E->getValueKind() == VK_RValue);
18553       if (S.getLangOpts().CPlusPlus &&
18554           !(isa<CXXMethodDecl>(VD) &&
18555             cast<CXXMethodDecl>(VD)->isInstance()))
18556         E->setValueKind(VK_LValue);
18557 
18558       return E;
18559     }
18560 
18561     ExprResult VisitMemberExpr(MemberExpr *E) {
18562       return resolveDecl(E, E->getMemberDecl());
18563     }
18564 
18565     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
18566       return resolveDecl(E, E->getDecl());
18567     }
18568   };
18569 }
18570 
18571 /// Given a function expression of unknown-any type, try to rebuild it
18572 /// to have a function type.
18573 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
18574   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
18575   if (Result.isInvalid()) return ExprError();
18576   return S.DefaultFunctionArrayConversion(Result.get());
18577 }
18578 
18579 namespace {
18580   /// A visitor for rebuilding an expression of type __unknown_anytype
18581   /// into one which resolves the type directly on the referring
18582   /// expression.  Strict preservation of the original source
18583   /// structure is not a goal.
18584   struct RebuildUnknownAnyExpr
18585     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
18586 
18587     Sema &S;
18588 
18589     /// The current destination type.
18590     QualType DestType;
18591 
18592     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
18593       : S(S), DestType(CastType) {}
18594 
18595     ExprResult VisitStmt(Stmt *S) {
18596       llvm_unreachable("unexpected statement!");
18597     }
18598 
18599     ExprResult VisitExpr(Expr *E) {
18600       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
18601         << E->getSourceRange();
18602       return ExprError();
18603     }
18604 
18605     ExprResult VisitCallExpr(CallExpr *E);
18606     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
18607 
18608     /// Rebuild an expression which simply semantically wraps another
18609     /// expression which it shares the type and value kind of.
18610     template <class T> ExprResult rebuildSugarExpr(T *E) {
18611       ExprResult SubResult = Visit(E->getSubExpr());
18612       if (SubResult.isInvalid()) return ExprError();
18613       Expr *SubExpr = SubResult.get();
18614       E->setSubExpr(SubExpr);
18615       E->setType(SubExpr->getType());
18616       E->setValueKind(SubExpr->getValueKind());
18617       assert(E->getObjectKind() == OK_Ordinary);
18618       return E;
18619     }
18620 
18621     ExprResult VisitParenExpr(ParenExpr *E) {
18622       return rebuildSugarExpr(E);
18623     }
18624 
18625     ExprResult VisitUnaryExtension(UnaryOperator *E) {
18626       return rebuildSugarExpr(E);
18627     }
18628 
18629     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
18630       const PointerType *Ptr = DestType->getAs<PointerType>();
18631       if (!Ptr) {
18632         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
18633           << E->getSourceRange();
18634         return ExprError();
18635       }
18636 
18637       if (isa<CallExpr>(E->getSubExpr())) {
18638         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
18639           << E->getSourceRange();
18640         return ExprError();
18641       }
18642 
18643       assert(E->getValueKind() == VK_RValue);
18644       assert(E->getObjectKind() == OK_Ordinary);
18645       E->setType(DestType);
18646 
18647       // Build the sub-expression as if it were an object of the pointee type.
18648       DestType = Ptr->getPointeeType();
18649       ExprResult SubResult = Visit(E->getSubExpr());
18650       if (SubResult.isInvalid()) return ExprError();
18651       E->setSubExpr(SubResult.get());
18652       return E;
18653     }
18654 
18655     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
18656 
18657     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
18658 
18659     ExprResult VisitMemberExpr(MemberExpr *E) {
18660       return resolveDecl(E, E->getMemberDecl());
18661     }
18662 
18663     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
18664       return resolveDecl(E, E->getDecl());
18665     }
18666   };
18667 }
18668 
18669 /// Rebuilds a call expression which yielded __unknown_anytype.
18670 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
18671   Expr *CalleeExpr = E->getCallee();
18672 
18673   enum FnKind {
18674     FK_MemberFunction,
18675     FK_FunctionPointer,
18676     FK_BlockPointer
18677   };
18678 
18679   FnKind Kind;
18680   QualType CalleeType = CalleeExpr->getType();
18681   if (CalleeType == S.Context.BoundMemberTy) {
18682     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
18683     Kind = FK_MemberFunction;
18684     CalleeType = Expr::findBoundMemberType(CalleeExpr);
18685   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
18686     CalleeType = Ptr->getPointeeType();
18687     Kind = FK_FunctionPointer;
18688   } else {
18689     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
18690     Kind = FK_BlockPointer;
18691   }
18692   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
18693 
18694   // Verify that this is a legal result type of a function.
18695   if (DestType->isArrayType() || DestType->isFunctionType()) {
18696     unsigned diagID = diag::err_func_returning_array_function;
18697     if (Kind == FK_BlockPointer)
18698       diagID = diag::err_block_returning_array_function;
18699 
18700     S.Diag(E->getExprLoc(), diagID)
18701       << DestType->isFunctionType() << DestType;
18702     return ExprError();
18703   }
18704 
18705   // Otherwise, go ahead and set DestType as the call's result.
18706   E->setType(DestType.getNonLValueExprType(S.Context));
18707   E->setValueKind(Expr::getValueKindForType(DestType));
18708   assert(E->getObjectKind() == OK_Ordinary);
18709 
18710   // Rebuild the function type, replacing the result type with DestType.
18711   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
18712   if (Proto) {
18713     // __unknown_anytype(...) is a special case used by the debugger when
18714     // it has no idea what a function's signature is.
18715     //
18716     // We want to build this call essentially under the K&R
18717     // unprototyped rules, but making a FunctionNoProtoType in C++
18718     // would foul up all sorts of assumptions.  However, we cannot
18719     // simply pass all arguments as variadic arguments, nor can we
18720     // portably just call the function under a non-variadic type; see
18721     // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
18722     // However, it turns out that in practice it is generally safe to
18723     // call a function declared as "A foo(B,C,D);" under the prototype
18724     // "A foo(B,C,D,...);".  The only known exception is with the
18725     // Windows ABI, where any variadic function is implicitly cdecl
18726     // regardless of its normal CC.  Therefore we change the parameter
18727     // types to match the types of the arguments.
18728     //
18729     // This is a hack, but it is far superior to moving the
18730     // corresponding target-specific code from IR-gen to Sema/AST.
18731 
18732     ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
18733     SmallVector<QualType, 8> ArgTypes;
18734     if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
18735       ArgTypes.reserve(E->getNumArgs());
18736       for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
18737         Expr *Arg = E->getArg(i);
18738         QualType ArgType = Arg->getType();
18739         if (E->isLValue()) {
18740           ArgType = S.Context.getLValueReferenceType(ArgType);
18741         } else if (E->isXValue()) {
18742           ArgType = S.Context.getRValueReferenceType(ArgType);
18743         }
18744         ArgTypes.push_back(ArgType);
18745       }
18746       ParamTypes = ArgTypes;
18747     }
18748     DestType = S.Context.getFunctionType(DestType, ParamTypes,
18749                                          Proto->getExtProtoInfo());
18750   } else {
18751     DestType = S.Context.getFunctionNoProtoType(DestType,
18752                                                 FnType->getExtInfo());
18753   }
18754 
18755   // Rebuild the appropriate pointer-to-function type.
18756   switch (Kind) {
18757   case FK_MemberFunction:
18758     // Nothing to do.
18759     break;
18760 
18761   case FK_FunctionPointer:
18762     DestType = S.Context.getPointerType(DestType);
18763     break;
18764 
18765   case FK_BlockPointer:
18766     DestType = S.Context.getBlockPointerType(DestType);
18767     break;
18768   }
18769 
18770   // Finally, we can recurse.
18771   ExprResult CalleeResult = Visit(CalleeExpr);
18772   if (!CalleeResult.isUsable()) return ExprError();
18773   E->setCallee(CalleeResult.get());
18774 
18775   // Bind a temporary if necessary.
18776   return S.MaybeBindToTemporary(E);
18777 }
18778 
18779 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
18780   // Verify that this is a legal result type of a call.
18781   if (DestType->isArrayType() || DestType->isFunctionType()) {
18782     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
18783       << DestType->isFunctionType() << DestType;
18784     return ExprError();
18785   }
18786 
18787   // Rewrite the method result type if available.
18788   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
18789     assert(Method->getReturnType() == S.Context.UnknownAnyTy);
18790     Method->setReturnType(DestType);
18791   }
18792 
18793   // Change the type of the message.
18794   E->setType(DestType.getNonReferenceType());
18795   E->setValueKind(Expr::getValueKindForType(DestType));
18796 
18797   return S.MaybeBindToTemporary(E);
18798 }
18799 
18800 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
18801   // The only case we should ever see here is a function-to-pointer decay.
18802   if (E->getCastKind() == CK_FunctionToPointerDecay) {
18803     assert(E->getValueKind() == VK_RValue);
18804     assert(E->getObjectKind() == OK_Ordinary);
18805 
18806     E->setType(DestType);
18807 
18808     // Rebuild the sub-expression as the pointee (function) type.
18809     DestType = DestType->castAs<PointerType>()->getPointeeType();
18810 
18811     ExprResult Result = Visit(E->getSubExpr());
18812     if (!Result.isUsable()) return ExprError();
18813 
18814     E->setSubExpr(Result.get());
18815     return E;
18816   } else if (E->getCastKind() == CK_LValueToRValue) {
18817     assert(E->getValueKind() == VK_RValue);
18818     assert(E->getObjectKind() == OK_Ordinary);
18819 
18820     assert(isa<BlockPointerType>(E->getType()));
18821 
18822     E->setType(DestType);
18823 
18824     // The sub-expression has to be a lvalue reference, so rebuild it as such.
18825     DestType = S.Context.getLValueReferenceType(DestType);
18826 
18827     ExprResult Result = Visit(E->getSubExpr());
18828     if (!Result.isUsable()) return ExprError();
18829 
18830     E->setSubExpr(Result.get());
18831     return E;
18832   } else {
18833     llvm_unreachable("Unhandled cast type!");
18834   }
18835 }
18836 
18837 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
18838   ExprValueKind ValueKind = VK_LValue;
18839   QualType Type = DestType;
18840 
18841   // We know how to make this work for certain kinds of decls:
18842 
18843   //  - functions
18844   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
18845     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
18846       DestType = Ptr->getPointeeType();
18847       ExprResult Result = resolveDecl(E, VD);
18848       if (Result.isInvalid()) return ExprError();
18849       return S.ImpCastExprToType(Result.get(), Type,
18850                                  CK_FunctionToPointerDecay, VK_RValue);
18851     }
18852 
18853     if (!Type->isFunctionType()) {
18854       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
18855         << VD << E->getSourceRange();
18856       return ExprError();
18857     }
18858     if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
18859       // We must match the FunctionDecl's type to the hack introduced in
18860       // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
18861       // type. See the lengthy commentary in that routine.
18862       QualType FDT = FD->getType();
18863       const FunctionType *FnType = FDT->castAs<FunctionType>();
18864       const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
18865       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
18866       if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
18867         SourceLocation Loc = FD->getLocation();
18868         FunctionDecl *NewFD = FunctionDecl::Create(
18869             S.Context, FD->getDeclContext(), Loc, Loc,
18870             FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(),
18871             SC_None, false /*isInlineSpecified*/, FD->hasPrototype(),
18872             /*ConstexprKind*/ CSK_unspecified);
18873 
18874         if (FD->getQualifier())
18875           NewFD->setQualifierInfo(FD->getQualifierLoc());
18876 
18877         SmallVector<ParmVarDecl*, 16> Params;
18878         for (const auto &AI : FT->param_types()) {
18879           ParmVarDecl *Param =
18880             S.BuildParmVarDeclForTypedef(FD, Loc, AI);
18881           Param->setScopeInfo(0, Params.size());
18882           Params.push_back(Param);
18883         }
18884         NewFD->setParams(Params);
18885         DRE->setDecl(NewFD);
18886         VD = DRE->getDecl();
18887       }
18888     }
18889 
18890     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
18891       if (MD->isInstance()) {
18892         ValueKind = VK_RValue;
18893         Type = S.Context.BoundMemberTy;
18894       }
18895 
18896     // Function references aren't l-values in C.
18897     if (!S.getLangOpts().CPlusPlus)
18898       ValueKind = VK_RValue;
18899 
18900   //  - variables
18901   } else if (isa<VarDecl>(VD)) {
18902     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
18903       Type = RefTy->getPointeeType();
18904     } else if (Type->isFunctionType()) {
18905       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
18906         << VD << E->getSourceRange();
18907       return ExprError();
18908     }
18909 
18910   //  - nothing else
18911   } else {
18912     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
18913       << VD << E->getSourceRange();
18914     return ExprError();
18915   }
18916 
18917   // Modifying the declaration like this is friendly to IR-gen but
18918   // also really dangerous.
18919   VD->setType(DestType);
18920   E->setType(Type);
18921   E->setValueKind(ValueKind);
18922   return E;
18923 }
18924 
18925 /// Check a cast of an unknown-any type.  We intentionally only
18926 /// trigger this for C-style casts.
18927 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
18928                                      Expr *CastExpr, CastKind &CastKind,
18929                                      ExprValueKind &VK, CXXCastPath &Path) {
18930   // The type we're casting to must be either void or complete.
18931   if (!CastType->isVoidType() &&
18932       RequireCompleteType(TypeRange.getBegin(), CastType,
18933                           diag::err_typecheck_cast_to_incomplete))
18934     return ExprError();
18935 
18936   // Rewrite the casted expression from scratch.
18937   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
18938   if (!result.isUsable()) return ExprError();
18939 
18940   CastExpr = result.get();
18941   VK = CastExpr->getValueKind();
18942   CastKind = CK_NoOp;
18943 
18944   return CastExpr;
18945 }
18946 
18947 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
18948   return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
18949 }
18950 
18951 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
18952                                     Expr *arg, QualType &paramType) {
18953   // If the syntactic form of the argument is not an explicit cast of
18954   // any sort, just do default argument promotion.
18955   ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
18956   if (!castArg) {
18957     ExprResult result = DefaultArgumentPromotion(arg);
18958     if (result.isInvalid()) return ExprError();
18959     paramType = result.get()->getType();
18960     return result;
18961   }
18962 
18963   // Otherwise, use the type that was written in the explicit cast.
18964   assert(!arg->hasPlaceholderType());
18965   paramType = castArg->getTypeAsWritten();
18966 
18967   // Copy-initialize a parameter of that type.
18968   InitializedEntity entity =
18969     InitializedEntity::InitializeParameter(Context, paramType,
18970                                            /*consumed*/ false);
18971   return PerformCopyInitialization(entity, callLoc, arg);
18972 }
18973 
18974 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
18975   Expr *orig = E;
18976   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
18977   while (true) {
18978     E = E->IgnoreParenImpCasts();
18979     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
18980       E = call->getCallee();
18981       diagID = diag::err_uncasted_call_of_unknown_any;
18982     } else {
18983       break;
18984     }
18985   }
18986 
18987   SourceLocation loc;
18988   NamedDecl *d;
18989   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
18990     loc = ref->getLocation();
18991     d = ref->getDecl();
18992   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
18993     loc = mem->getMemberLoc();
18994     d = mem->getMemberDecl();
18995   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
18996     diagID = diag::err_uncasted_call_of_unknown_any;
18997     loc = msg->getSelectorStartLoc();
18998     d = msg->getMethodDecl();
18999     if (!d) {
19000       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
19001         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
19002         << orig->getSourceRange();
19003       return ExprError();
19004     }
19005   } else {
19006     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
19007       << E->getSourceRange();
19008     return ExprError();
19009   }
19010 
19011   S.Diag(loc, diagID) << d << orig->getSourceRange();
19012 
19013   // Never recoverable.
19014   return ExprError();
19015 }
19016 
19017 /// Check for operands with placeholder types and complain if found.
19018 /// Returns ExprError() if there was an error and no recovery was possible.
19019 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
19020   if (!getLangOpts().CPlusPlus) {
19021     // C cannot handle TypoExpr nodes on either side of a binop because it
19022     // doesn't handle dependent types properly, so make sure any TypoExprs have
19023     // been dealt with before checking the operands.
19024     ExprResult Result = CorrectDelayedTyposInExpr(E);
19025     if (!Result.isUsable()) return ExprError();
19026     E = Result.get();
19027   }
19028 
19029   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
19030   if (!placeholderType) return E;
19031 
19032   switch (placeholderType->getKind()) {
19033 
19034   // Overloaded expressions.
19035   case BuiltinType::Overload: {
19036     // Try to resolve a single function template specialization.
19037     // This is obligatory.
19038     ExprResult Result = E;
19039     if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
19040       return Result;
19041 
19042     // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
19043     // leaves Result unchanged on failure.
19044     Result = E;
19045     if (resolveAndFixAddressOfSingleOverloadCandidate(Result))
19046       return Result;
19047 
19048     // If that failed, try to recover with a call.
19049     tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
19050                          /*complain*/ true);
19051     return Result;
19052   }
19053 
19054   // Bound member functions.
19055   case BuiltinType::BoundMember: {
19056     ExprResult result = E;
19057     const Expr *BME = E->IgnoreParens();
19058     PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
19059     // Try to give a nicer diagnostic if it is a bound member that we recognize.
19060     if (isa<CXXPseudoDestructorExpr>(BME)) {
19061       PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
19062     } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
19063       if (ME->getMemberNameInfo().getName().getNameKind() ==
19064           DeclarationName::CXXDestructorName)
19065         PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
19066     }
19067     tryToRecoverWithCall(result, PD,
19068                          /*complain*/ true);
19069     return result;
19070   }
19071 
19072   // ARC unbridged casts.
19073   case BuiltinType::ARCUnbridgedCast: {
19074     Expr *realCast = stripARCUnbridgedCast(E);
19075     diagnoseARCUnbridgedCast(realCast);
19076     return realCast;
19077   }
19078 
19079   // Expressions of unknown type.
19080   case BuiltinType::UnknownAny:
19081     return diagnoseUnknownAnyExpr(*this, E);
19082 
19083   // Pseudo-objects.
19084   case BuiltinType::PseudoObject:
19085     return checkPseudoObjectRValue(E);
19086 
19087   case BuiltinType::BuiltinFn: {
19088     // Accept __noop without parens by implicitly converting it to a call expr.
19089     auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
19090     if (DRE) {
19091       auto *FD = cast<FunctionDecl>(DRE->getDecl());
19092       if (FD->getBuiltinID() == Builtin::BI__noop) {
19093         E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
19094                               CK_BuiltinFnToFnPtr)
19095                 .get();
19096         return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy,
19097                                 VK_RValue, SourceLocation());
19098       }
19099     }
19100 
19101     Diag(E->getBeginLoc(), diag::err_builtin_fn_use);
19102     return ExprError();
19103   }
19104 
19105   case BuiltinType::IncompleteMatrixIdx:
19106     Diag(cast<MatrixSubscriptExpr>(E->IgnoreParens())
19107              ->getRowIdx()
19108              ->getBeginLoc(),
19109          diag::err_matrix_incomplete_index);
19110     return ExprError();
19111 
19112   // Expressions of unknown type.
19113   case BuiltinType::OMPArraySection:
19114     Diag(E->getBeginLoc(), diag::err_omp_array_section_use);
19115     return ExprError();
19116 
19117   // Expressions of unknown type.
19118   case BuiltinType::OMPArrayShaping:
19119     return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use));
19120 
19121   case BuiltinType::OMPIterator:
19122     return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use));
19123 
19124   // Everything else should be impossible.
19125 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
19126   case BuiltinType::Id:
19127 #include "clang/Basic/OpenCLImageTypes.def"
19128 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
19129   case BuiltinType::Id:
19130 #include "clang/Basic/OpenCLExtensionTypes.def"
19131 #define SVE_TYPE(Name, Id, SingletonId) \
19132   case BuiltinType::Id:
19133 #include "clang/Basic/AArch64SVEACLETypes.def"
19134 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
19135 #define PLACEHOLDER_TYPE(Id, SingletonId)
19136 #include "clang/AST/BuiltinTypes.def"
19137     break;
19138   }
19139 
19140   llvm_unreachable("invalid placeholder type!");
19141 }
19142 
19143 bool Sema::CheckCaseExpression(Expr *E) {
19144   if (E->isTypeDependent())
19145     return true;
19146   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
19147     return E->getType()->isIntegralOrEnumerationType();
19148   return false;
19149 }
19150 
19151 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
19152 ExprResult
19153 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
19154   assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
19155          "Unknown Objective-C Boolean value!");
19156   QualType BoolT = Context.ObjCBuiltinBoolTy;
19157   if (!Context.getBOOLDecl()) {
19158     LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
19159                         Sema::LookupOrdinaryName);
19160     if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
19161       NamedDecl *ND = Result.getFoundDecl();
19162       if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
19163         Context.setBOOLDecl(TD);
19164     }
19165   }
19166   if (Context.getBOOLDecl())
19167     BoolT = Context.getBOOLType();
19168   return new (Context)
19169       ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
19170 }
19171 
19172 ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
19173     llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
19174     SourceLocation RParen) {
19175 
19176   StringRef Platform = getASTContext().getTargetInfo().getPlatformName();
19177 
19178   auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) {
19179     return Spec.getPlatform() == Platform;
19180   });
19181 
19182   VersionTuple Version;
19183   if (Spec != AvailSpecs.end())
19184     Version = Spec->getVersion();
19185 
19186   // The use of `@available` in the enclosing function should be analyzed to
19187   // warn when it's used inappropriately (i.e. not if(@available)).
19188   if (getCurFunctionOrMethodDecl())
19189     getEnclosingFunction()->HasPotentialAvailabilityViolations = true;
19190   else if (getCurBlock() || getCurLambda())
19191     getCurFunction()->HasPotentialAvailabilityViolations = true;
19192 
19193   return new (Context)
19194       ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
19195 }
19196 
19197 ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End,
19198                                     ArrayRef<Expr *> SubExprs, QualType T) {
19199   // FIXME: enable it for C++, RecoveryExpr is type-dependent to suppress
19200   // bogus diagnostics and this trick does not work in C.
19201   // FIXME: use containsErrors() to suppress unwanted diags in C.
19202   if (!Context.getLangOpts().RecoveryAST)
19203     return ExprError();
19204 
19205   if (isSFINAEContext())
19206     return ExprError();
19207 
19208   if (T.isNull() || !Context.getLangOpts().RecoveryASTType)
19209     // We don't know the concrete type, fallback to dependent type.
19210     T = Context.DependentTy;
19211   return RecoveryExpr::Create(Context, T, Begin, End, SubExprs);
19212 }
19213