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/PartialDiagnostic.h"
31 #include "clang/Basic/SourceManager.h"
32 #include "clang/Basic/TargetInfo.h"
33 #include "clang/Lex/LiteralSupport.h"
34 #include "clang/Lex/Preprocessor.h"
35 #include "clang/Sema/AnalysisBasedWarnings.h"
36 #include "clang/Sema/DeclSpec.h"
37 #include "clang/Sema/DelayedDiagnostic.h"
38 #include "clang/Sema/Designator.h"
39 #include "clang/Sema/Initialization.h"
40 #include "clang/Sema/Lookup.h"
41 #include "clang/Sema/Overload.h"
42 #include "clang/Sema/ParsedTemplate.h"
43 #include "clang/Sema/Scope.h"
44 #include "clang/Sema/ScopeInfo.h"
45 #include "clang/Sema/SemaFixItUtils.h"
46 #include "clang/Sema/SemaInternal.h"
47 #include "clang/Sema/Template.h"
48 #include "llvm/Support/ConvertUTF.h"
49 #include "llvm/Support/SaveAndRestore.h"
50 using namespace clang;
51 using namespace sema;
52 using llvm::RoundingMode;
53 
54 /// Determine whether the use of this declaration is valid, without
55 /// emitting diagnostics.
56 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
57   // See if this is an auto-typed variable whose initializer we are parsing.
58   if (ParsingInitForAutoVars.count(D))
59     return false;
60 
61   // See if this is a deleted function.
62   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
63     if (FD->isDeleted())
64       return false;
65 
66     // If the function has a deduced return type, and we can't deduce it,
67     // then we can't use it either.
68     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
69         DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
70       return false;
71 
72     // See if this is an aligned allocation/deallocation function that is
73     // unavailable.
74     if (TreatUnavailableAsInvalid &&
75         isUnavailableAlignedAllocationFunction(*FD))
76       return false;
77   }
78 
79   // See if this function is unavailable.
80   if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
81       cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
82     return false;
83 
84   return true;
85 }
86 
87 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
88   // Warn if this is used but marked unused.
89   if (const auto *A = D->getAttr<UnusedAttr>()) {
90     // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
91     // should diagnose them.
92     if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused &&
93         A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) {
94       const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext());
95       if (DC && !DC->hasAttr<UnusedAttr>())
96         S.Diag(Loc, diag::warn_used_but_marked_unused) << D;
97     }
98   }
99 }
100 
101 /// Emit a note explaining that this function is deleted.
102 void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
103   assert(Decl && Decl->isDeleted());
104 
105   if (Decl->isDefaulted()) {
106     // If the method was explicitly defaulted, point at that declaration.
107     if (!Decl->isImplicit())
108       Diag(Decl->getLocation(), diag::note_implicitly_deleted);
109 
110     // Try to diagnose why this special member function was implicitly
111     // deleted. This might fail, if that reason no longer applies.
112     DiagnoseDeletedDefaultedFunction(Decl);
113     return;
114   }
115 
116   auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
117   if (Ctor && Ctor->isInheritingConstructor())
118     return NoteDeletedInheritingConstructor(Ctor);
119 
120   Diag(Decl->getLocation(), diag::note_availability_specified_here)
121     << Decl << 1;
122 }
123 
124 /// Determine whether a FunctionDecl was ever declared with an
125 /// explicit storage class.
126 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
127   for (auto I : D->redecls()) {
128     if (I->getStorageClass() != SC_None)
129       return true;
130   }
131   return false;
132 }
133 
134 /// Check whether we're in an extern inline function and referring to a
135 /// variable or function with internal linkage (C11 6.7.4p3).
136 ///
137 /// This is only a warning because we used to silently accept this code, but
138 /// in many cases it will not behave correctly. This is not enabled in C++ mode
139 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
140 /// and so while there may still be user mistakes, most of the time we can't
141 /// prove that there are errors.
142 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
143                                                       const NamedDecl *D,
144                                                       SourceLocation Loc) {
145   // This is disabled under C++; there are too many ways for this to fire in
146   // contexts where the warning is a false positive, or where it is technically
147   // correct but benign.
148   if (S.getLangOpts().CPlusPlus)
149     return;
150 
151   // Check if this is an inlined function or method.
152   FunctionDecl *Current = S.getCurFunctionDecl();
153   if (!Current)
154     return;
155   if (!Current->isInlined())
156     return;
157   if (!Current->isExternallyVisible())
158     return;
159 
160   // Check if the decl has internal linkage.
161   if (D->getFormalLinkage() != InternalLinkage)
162     return;
163 
164   // Downgrade from ExtWarn to Extension if
165   //  (1) the supposedly external inline function is in the main file,
166   //      and probably won't be included anywhere else.
167   //  (2) the thing we're referencing is a pure function.
168   //  (3) the thing we're referencing is another inline function.
169   // This last can give us false negatives, but it's better than warning on
170   // wrappers for simple C library functions.
171   const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
172   bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
173   if (!DowngradeWarning && UsedFn)
174     DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
175 
176   S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
177                                : diag::ext_internal_in_extern_inline)
178     << /*IsVar=*/!UsedFn << D;
179 
180   S.MaybeSuggestAddingStaticToDecl(Current);
181 
182   S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
183       << D;
184 }
185 
186 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
187   const FunctionDecl *First = Cur->getFirstDecl();
188 
189   // Suggest "static" on the function, if possible.
190   if (!hasAnyExplicitStorageClass(First)) {
191     SourceLocation DeclBegin = First->getSourceRange().getBegin();
192     Diag(DeclBegin, diag::note_convert_inline_to_static)
193       << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
194   }
195 }
196 
197 /// Determine whether the use of this declaration is valid, and
198 /// emit any corresponding diagnostics.
199 ///
200 /// This routine diagnoses various problems with referencing
201 /// declarations that can occur when using a declaration. For example,
202 /// it might warn if a deprecated or unavailable declaration is being
203 /// used, or produce an error (and return true) if a C++0x deleted
204 /// function is being used.
205 ///
206 /// \returns true if there was an error (this declaration cannot be
207 /// referenced), false otherwise.
208 ///
209 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
210                              const ObjCInterfaceDecl *UnknownObjCClass,
211                              bool ObjCPropertyAccess,
212                              bool AvoidPartialAvailabilityChecks,
213                              ObjCInterfaceDecl *ClassReceiver) {
214   SourceLocation Loc = Locs.front();
215   if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
216     // If there were any diagnostics suppressed by template argument deduction,
217     // emit them now.
218     auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
219     if (Pos != SuppressedDiagnostics.end()) {
220       for (const PartialDiagnosticAt &Suppressed : Pos->second)
221         Diag(Suppressed.first, Suppressed.second);
222 
223       // Clear out the list of suppressed diagnostics, so that we don't emit
224       // them again for this specialization. However, we don't obsolete this
225       // entry from the table, because we want to avoid ever emitting these
226       // diagnostics again.
227       Pos->second.clear();
228     }
229 
230     // C++ [basic.start.main]p3:
231     //   The function 'main' shall not be used within a program.
232     if (cast<FunctionDecl>(D)->isMain())
233       Diag(Loc, diag::ext_main_used);
234 
235     diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc);
236   }
237 
238   // See if this is an auto-typed variable whose initializer we are parsing.
239   if (ParsingInitForAutoVars.count(D)) {
240     if (isa<BindingDecl>(D)) {
241       Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
242         << D->getDeclName();
243     } else {
244       Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
245         << D->getDeclName() << cast<VarDecl>(D)->getType();
246     }
247     return true;
248   }
249 
250   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
251     // See if this is a deleted function.
252     if (FD->isDeleted()) {
253       auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
254       if (Ctor && Ctor->isInheritingConstructor())
255         Diag(Loc, diag::err_deleted_inherited_ctor_use)
256             << Ctor->getParent()
257             << Ctor->getInheritedConstructor().getConstructor()->getParent();
258       else
259         Diag(Loc, diag::err_deleted_function_use);
260       NoteDeletedFunction(FD);
261       return true;
262     }
263 
264     // [expr.prim.id]p4
265     //   A program that refers explicitly or implicitly to a function with a
266     //   trailing requires-clause whose constraint-expression is not satisfied,
267     //   other than to declare it, is ill-formed. [...]
268     //
269     // See if this is a function with constraints that need to be satisfied.
270     // Check this before deducing the return type, as it might instantiate the
271     // definition.
272     if (FD->getTrailingRequiresClause()) {
273       ConstraintSatisfaction Satisfaction;
274       if (CheckFunctionConstraints(FD, Satisfaction, Loc))
275         // A diagnostic will have already been generated (non-constant
276         // constraint expression, for example)
277         return true;
278       if (!Satisfaction.IsSatisfied) {
279         Diag(Loc,
280              diag::err_reference_to_function_with_unsatisfied_constraints)
281             << D;
282         DiagnoseUnsatisfiedConstraint(Satisfaction);
283         return true;
284       }
285     }
286 
287     // If the function has a deduced return type, and we can't deduce it,
288     // then we can't use it either.
289     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
290         DeduceReturnType(FD, Loc))
291       return true;
292 
293     if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD))
294       return true;
295 
296     if (getLangOpts().SYCLIsDevice && !checkSYCLDeviceFunction(Loc, FD))
297       return true;
298   }
299 
300   if (auto *MD = dyn_cast<CXXMethodDecl>(D)) {
301     // Lambdas are only default-constructible or assignable in C++2a onwards.
302     if (MD->getParent()->isLambda() &&
303         ((isa<CXXConstructorDecl>(MD) &&
304           cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) ||
305          MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) {
306       Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign)
307         << !isa<CXXConstructorDecl>(MD);
308     }
309   }
310 
311   auto getReferencedObjCProp = [](const NamedDecl *D) ->
312                                       const ObjCPropertyDecl * {
313     if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
314       return MD->findPropertyDecl();
315     return nullptr;
316   };
317   if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
318     if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc))
319       return true;
320   } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) {
321       return true;
322   }
323 
324   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
325   // Only the variables omp_in and omp_out are allowed in the combiner.
326   // Only the variables omp_priv and omp_orig are allowed in the
327   // initializer-clause.
328   auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
329   if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
330       isa<VarDecl>(D)) {
331     Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
332         << getCurFunction()->HasOMPDeclareReductionCombiner;
333     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
334     return true;
335   }
336 
337   // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions
338   //  List-items in map clauses on this construct may only refer to the declared
339   //  variable var and entities that could be referenced by a procedure defined
340   //  at the same location
341   if (LangOpts.OpenMP && isa<VarDecl>(D) &&
342       !isOpenMPDeclareMapperVarDeclAllowed(cast<VarDecl>(D))) {
343     Diag(Loc, diag::err_omp_declare_mapper_wrong_var)
344         << getOpenMPDeclareMapperVarName();
345     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
346     return true;
347   }
348 
349   DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,
350                              AvoidPartialAvailabilityChecks, ClassReceiver);
351 
352   DiagnoseUnusedOfDecl(*this, D, Loc);
353 
354   diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
355 
356   if (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)) {
357     if (const auto *VD = dyn_cast<ValueDecl>(D))
358       checkDeviceDecl(VD, Loc);
359 
360     if (!Context.getTargetInfo().isTLSSupported())
361       if (const auto *VD = dyn_cast<VarDecl>(D))
362         if (VD->getTLSKind() != VarDecl::TLS_None)
363           targetDiag(*Locs.begin(), diag::err_thread_unsupported);
364   }
365 
366   if (isa<ParmVarDecl>(D) && isa<RequiresExprBodyDecl>(D->getDeclContext()) &&
367       !isUnevaluatedContext()) {
368     // C++ [expr.prim.req.nested] p3
369     //   A local parameter shall only appear as an unevaluated operand
370     //   (Clause 8) within the constraint-expression.
371     Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context)
372         << D;
373     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
374     return true;
375   }
376 
377   return false;
378 }
379 
380 /// DiagnoseSentinelCalls - This routine checks whether a call or
381 /// message-send is to a declaration with the sentinel attribute, and
382 /// if so, it checks that the requirements of the sentinel are
383 /// satisfied.
384 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
385                                  ArrayRef<Expr *> Args) {
386   const SentinelAttr *attr = D->getAttr<SentinelAttr>();
387   if (!attr)
388     return;
389 
390   // The number of formal parameters of the declaration.
391   unsigned numFormalParams;
392 
393   // The kind of declaration.  This is also an index into a %select in
394   // the diagnostic.
395   enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
396 
397   if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
398     numFormalParams = MD->param_size();
399     calleeType = CT_Method;
400   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
401     numFormalParams = FD->param_size();
402     calleeType = CT_Function;
403   } else if (isa<VarDecl>(D)) {
404     QualType type = cast<ValueDecl>(D)->getType();
405     const FunctionType *fn = nullptr;
406     if (const PointerType *ptr = type->getAs<PointerType>()) {
407       fn = ptr->getPointeeType()->getAs<FunctionType>();
408       if (!fn) return;
409       calleeType = CT_Function;
410     } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
411       fn = ptr->getPointeeType()->castAs<FunctionType>();
412       calleeType = CT_Block;
413     } else {
414       return;
415     }
416 
417     if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
418       numFormalParams = proto->getNumParams();
419     } else {
420       numFormalParams = 0;
421     }
422   } else {
423     return;
424   }
425 
426   // "nullPos" is the number of formal parameters at the end which
427   // effectively count as part of the variadic arguments.  This is
428   // useful if you would prefer to not have *any* formal parameters,
429   // but the language forces you to have at least one.
430   unsigned nullPos = attr->getNullPos();
431   assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
432   numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
433 
434   // The number of arguments which should follow the sentinel.
435   unsigned numArgsAfterSentinel = attr->getSentinel();
436 
437   // If there aren't enough arguments for all the formal parameters,
438   // the sentinel, and the args after the sentinel, complain.
439   if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
440     Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
441     Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
442     return;
443   }
444 
445   // Otherwise, find the sentinel expression.
446   Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
447   if (!sentinelExpr) return;
448   if (sentinelExpr->isValueDependent()) return;
449   if (Context.isSentinelNullExpr(sentinelExpr)) return;
450 
451   // Pick a reasonable string to insert.  Optimistically use 'nil', 'nullptr',
452   // or 'NULL' if those are actually defined in the context.  Only use
453   // 'nil' for ObjC methods, where it's much more likely that the
454   // variadic arguments form a list of object pointers.
455   SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc());
456   std::string NullValue;
457   if (calleeType == CT_Method && PP.isMacroDefined("nil"))
458     NullValue = "nil";
459   else if (getLangOpts().CPlusPlus11)
460     NullValue = "nullptr";
461   else if (PP.isMacroDefined("NULL"))
462     NullValue = "NULL";
463   else
464     NullValue = "(void*) 0";
465 
466   if (MissingNilLoc.isInvalid())
467     Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
468   else
469     Diag(MissingNilLoc, diag::warn_missing_sentinel)
470       << int(calleeType)
471       << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
472   Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
473 }
474 
475 SourceRange Sema::getExprRange(Expr *E) const {
476   return E ? E->getSourceRange() : SourceRange();
477 }
478 
479 //===----------------------------------------------------------------------===//
480 //  Standard Promotions and Conversions
481 //===----------------------------------------------------------------------===//
482 
483 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
484 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
485   // Handle any placeholder expressions which made it here.
486   if (E->getType()->isPlaceholderType()) {
487     ExprResult result = CheckPlaceholderExpr(E);
488     if (result.isInvalid()) return ExprError();
489     E = result.get();
490   }
491 
492   QualType Ty = E->getType();
493   assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
494 
495   if (Ty->isFunctionType()) {
496     if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
497       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
498         if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
499           return ExprError();
500 
501     E = ImpCastExprToType(E, Context.getPointerType(Ty),
502                           CK_FunctionToPointerDecay).get();
503   } else if (Ty->isArrayType()) {
504     // In C90 mode, arrays only promote to pointers if the array expression is
505     // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
506     // type 'array of type' is converted to an expression that has type 'pointer
507     // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
508     // that has type 'array of type' ...".  The relevant change is "an lvalue"
509     // (C90) to "an expression" (C99).
510     //
511     // C++ 4.2p1:
512     // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
513     // T" can be converted to an rvalue of type "pointer to T".
514     //
515     if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
516       E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
517                             CK_ArrayToPointerDecay).get();
518   }
519   return E;
520 }
521 
522 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
523   // Check to see if we are dereferencing a null pointer.  If so,
524   // and if not volatile-qualified, this is undefined behavior that the
525   // optimizer will delete, so warn about it.  People sometimes try to use this
526   // to get a deterministic trap and are surprised by clang's behavior.  This
527   // only handles the pattern "*null", which is a very syntactic check.
528   const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts());
529   if (UO && UO->getOpcode() == UO_Deref &&
530       UO->getSubExpr()->getType()->isPointerType()) {
531     const LangAS AS =
532         UO->getSubExpr()->getType()->getPointeeType().getAddressSpace();
533     if ((!isTargetAddressSpace(AS) ||
534          (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) &&
535         UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant(
536             S.Context, Expr::NPC_ValueDependentIsNotNull) &&
537         !UO->getType().isVolatileQualified()) {
538       S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
539                             S.PDiag(diag::warn_indirection_through_null)
540                                 << UO->getSubExpr()->getSourceRange());
541       S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
542                             S.PDiag(diag::note_indirection_through_null));
543     }
544   }
545 }
546 
547 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
548                                     SourceLocation AssignLoc,
549                                     const Expr* RHS) {
550   const ObjCIvarDecl *IV = OIRE->getDecl();
551   if (!IV)
552     return;
553 
554   DeclarationName MemberName = IV->getDeclName();
555   IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
556   if (!Member || !Member->isStr("isa"))
557     return;
558 
559   const Expr *Base = OIRE->getBase();
560   QualType BaseType = Base->getType();
561   if (OIRE->isArrow())
562     BaseType = BaseType->getPointeeType();
563   if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
564     if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
565       ObjCInterfaceDecl *ClassDeclared = nullptr;
566       ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
567       if (!ClassDeclared->getSuperClass()
568           && (*ClassDeclared->ivar_begin()) == IV) {
569         if (RHS) {
570           NamedDecl *ObjectSetClass =
571             S.LookupSingleName(S.TUScope,
572                                &S.Context.Idents.get("object_setClass"),
573                                SourceLocation(), S.LookupOrdinaryName);
574           if (ObjectSetClass) {
575             SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc());
576             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign)
577                 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
578                                               "object_setClass(")
579                 << FixItHint::CreateReplacement(
580                        SourceRange(OIRE->getOpLoc(), AssignLoc), ",")
581                 << FixItHint::CreateInsertion(RHSLocEnd, ")");
582           }
583           else
584             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
585         } else {
586           NamedDecl *ObjectGetClass =
587             S.LookupSingleName(S.TUScope,
588                                &S.Context.Idents.get("object_getClass"),
589                                SourceLocation(), S.LookupOrdinaryName);
590           if (ObjectGetClass)
591             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use)
592                 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
593                                               "object_getClass(")
594                 << FixItHint::CreateReplacement(
595                        SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")");
596           else
597             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
598         }
599         S.Diag(IV->getLocation(), diag::note_ivar_decl);
600       }
601     }
602 }
603 
604 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
605   // Handle any placeholder expressions which made it here.
606   if (E->getType()->isPlaceholderType()) {
607     ExprResult result = CheckPlaceholderExpr(E);
608     if (result.isInvalid()) return ExprError();
609     E = result.get();
610   }
611 
612   // C++ [conv.lval]p1:
613   //   A glvalue of a non-function, non-array type T can be
614   //   converted to a prvalue.
615   if (!E->isGLValue()) return E;
616 
617   QualType T = E->getType();
618   assert(!T.isNull() && "r-value conversion on typeless expression?");
619 
620   // lvalue-to-rvalue conversion cannot be applied to function or array types.
621   if (T->isFunctionType() || T->isArrayType())
622     return E;
623 
624   // We don't want to throw lvalue-to-rvalue casts on top of
625   // expressions of certain types in C++.
626   if (getLangOpts().CPlusPlus &&
627       (E->getType() == Context.OverloadTy ||
628        T->isDependentType() ||
629        T->isRecordType()))
630     return E;
631 
632   // The C standard is actually really unclear on this point, and
633   // DR106 tells us what the result should be but not why.  It's
634   // generally best to say that void types just doesn't undergo
635   // lvalue-to-rvalue at all.  Note that expressions of unqualified
636   // 'void' type are never l-values, but qualified void can be.
637   if (T->isVoidType())
638     return E;
639 
640   // OpenCL usually rejects direct accesses to values of 'half' type.
641   if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
642       T->isHalfType()) {
643     Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
644       << 0 << T;
645     return ExprError();
646   }
647 
648   CheckForNullPointerDereference(*this, E);
649   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
650     NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
651                                      &Context.Idents.get("object_getClass"),
652                                      SourceLocation(), LookupOrdinaryName);
653     if (ObjectGetClass)
654       Diag(E->getExprLoc(), diag::warn_objc_isa_use)
655           << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(")
656           << FixItHint::CreateReplacement(
657                  SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
658     else
659       Diag(E->getExprLoc(), diag::warn_objc_isa_use);
660   }
661   else if (const ObjCIvarRefExpr *OIRE =
662             dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
663     DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
664 
665   // C++ [conv.lval]p1:
666   //   [...] If T is a non-class type, the type of the prvalue is the
667   //   cv-unqualified version of T. Otherwise, the type of the
668   //   rvalue is T.
669   //
670   // C99 6.3.2.1p2:
671   //   If the lvalue has qualified type, the value has the unqualified
672   //   version of the type of the lvalue; otherwise, the value has the
673   //   type of the lvalue.
674   if (T.hasQualifiers())
675     T = T.getUnqualifiedType();
676 
677   // Under the MS ABI, lock down the inheritance model now.
678   if (T->isMemberPointerType() &&
679       Context.getTargetInfo().getCXXABI().isMicrosoft())
680     (void)isCompleteType(E->getExprLoc(), T);
681 
682   ExprResult Res = CheckLValueToRValueConversionOperand(E);
683   if (Res.isInvalid())
684     return Res;
685   E = Res.get();
686 
687   // Loading a __weak object implicitly retains the value, so we need a cleanup to
688   // balance that.
689   if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
690     Cleanup.setExprNeedsCleanups(true);
691 
692   if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
693     Cleanup.setExprNeedsCleanups(true);
694 
695   // C++ [conv.lval]p3:
696   //   If T is cv std::nullptr_t, the result is a null pointer constant.
697   CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue;
698   Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_RValue,
699                                  FPOptionsOverride());
700 
701   // C11 6.3.2.1p2:
702   //   ... if the lvalue has atomic type, the value has the non-atomic version
703   //   of the type of the lvalue ...
704   if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
705     T = Atomic->getValueType().getUnqualifiedType();
706     Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
707                                    nullptr, VK_RValue, FPOptionsOverride());
708   }
709 
710   return Res;
711 }
712 
713 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
714   ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
715   if (Res.isInvalid())
716     return ExprError();
717   Res = DefaultLvalueConversion(Res.get());
718   if (Res.isInvalid())
719     return ExprError();
720   return Res;
721 }
722 
723 /// CallExprUnaryConversions - a special case of an unary conversion
724 /// performed on a function designator of a call expression.
725 ExprResult Sema::CallExprUnaryConversions(Expr *E) {
726   QualType Ty = E->getType();
727   ExprResult Res = E;
728   // Only do implicit cast for a function type, but not for a pointer
729   // to function type.
730   if (Ty->isFunctionType()) {
731     Res = ImpCastExprToType(E, Context.getPointerType(Ty),
732                             CK_FunctionToPointerDecay);
733     if (Res.isInvalid())
734       return ExprError();
735   }
736   Res = DefaultLvalueConversion(Res.get());
737   if (Res.isInvalid())
738     return ExprError();
739   return Res.get();
740 }
741 
742 /// UsualUnaryConversions - Performs various conversions that are common to most
743 /// operators (C99 6.3). The conversions of array and function types are
744 /// sometimes suppressed. For example, the array->pointer conversion doesn't
745 /// apply if the array is an argument to the sizeof or address (&) operators.
746 /// In these instances, this routine should *not* be called.
747 ExprResult Sema::UsualUnaryConversions(Expr *E) {
748   // First, convert to an r-value.
749   ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
750   if (Res.isInvalid())
751     return ExprError();
752   E = Res.get();
753 
754   QualType Ty = E->getType();
755   assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
756 
757   // Half FP have to be promoted to float unless it is natively supported
758   if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
759     return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
760 
761   // Try to perform integral promotions if the object has a theoretically
762   // promotable type.
763   if (Ty->isIntegralOrUnscopedEnumerationType()) {
764     // C99 6.3.1.1p2:
765     //
766     //   The following may be used in an expression wherever an int or
767     //   unsigned int may be used:
768     //     - an object or expression with an integer type whose integer
769     //       conversion rank is less than or equal to the rank of int
770     //       and unsigned int.
771     //     - A bit-field of type _Bool, int, signed int, or unsigned int.
772     //
773     //   If an int can represent all values of the original type, the
774     //   value is converted to an int; otherwise, it is converted to an
775     //   unsigned int. These are called the integer promotions. All
776     //   other types are unchanged by the integer promotions.
777 
778     QualType PTy = Context.isPromotableBitField(E);
779     if (!PTy.isNull()) {
780       E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
781       return E;
782     }
783     if (Ty->isPromotableIntegerType()) {
784       QualType PT = Context.getPromotedIntegerType(Ty);
785       E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
786       return E;
787     }
788   }
789   return E;
790 }
791 
792 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
793 /// do not have a prototype. Arguments that have type float or __fp16
794 /// are promoted to double. All other argument types are converted by
795 /// UsualUnaryConversions().
796 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
797   QualType Ty = E->getType();
798   assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
799 
800   ExprResult Res = UsualUnaryConversions(E);
801   if (Res.isInvalid())
802     return ExprError();
803   E = Res.get();
804 
805   // If this is a 'float'  or '__fp16' (CVR qualified or typedef)
806   // promote to double.
807   // Note that default argument promotion applies only to float (and
808   // half/fp16); it does not apply to _Float16.
809   const BuiltinType *BTy = Ty->getAs<BuiltinType>();
810   if (BTy && (BTy->getKind() == BuiltinType::Half ||
811               BTy->getKind() == BuiltinType::Float)) {
812     if (getLangOpts().OpenCL &&
813         !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
814         if (BTy->getKind() == BuiltinType::Half) {
815             E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
816         }
817     } else {
818       E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
819     }
820   }
821 
822   // C++ performs lvalue-to-rvalue conversion as a default argument
823   // promotion, even on class types, but note:
824   //   C++11 [conv.lval]p2:
825   //     When an lvalue-to-rvalue conversion occurs in an unevaluated
826   //     operand or a subexpression thereof the value contained in the
827   //     referenced object is not accessed. Otherwise, if the glvalue
828   //     has a class type, the conversion copy-initializes a temporary
829   //     of type T from the glvalue and the result of the conversion
830   //     is a prvalue for the temporary.
831   // FIXME: add some way to gate this entire thing for correctness in
832   // potentially potentially evaluated contexts.
833   if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
834     ExprResult Temp = PerformCopyInitialization(
835                        InitializedEntity::InitializeTemporary(E->getType()),
836                                                 E->getExprLoc(), E);
837     if (Temp.isInvalid())
838       return ExprError();
839     E = Temp.get();
840   }
841 
842   return E;
843 }
844 
845 /// Determine the degree of POD-ness for an expression.
846 /// Incomplete types are considered POD, since this check can be performed
847 /// when we're in an unevaluated context.
848 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
849   if (Ty->isIncompleteType()) {
850     // C++11 [expr.call]p7:
851     //   After these conversions, if the argument does not have arithmetic,
852     //   enumeration, pointer, pointer to member, or class type, the program
853     //   is ill-formed.
854     //
855     // Since we've already performed array-to-pointer and function-to-pointer
856     // decay, the only such type in C++ is cv void. This also handles
857     // initializer lists as variadic arguments.
858     if (Ty->isVoidType())
859       return VAK_Invalid;
860 
861     if (Ty->isObjCObjectType())
862       return VAK_Invalid;
863     return VAK_Valid;
864   }
865 
866   if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
867     return VAK_Invalid;
868 
869   if (Ty.isCXX98PODType(Context))
870     return VAK_Valid;
871 
872   // C++11 [expr.call]p7:
873   //   Passing a potentially-evaluated argument of class type (Clause 9)
874   //   having a non-trivial copy constructor, a non-trivial move constructor,
875   //   or a non-trivial destructor, with no corresponding parameter,
876   //   is conditionally-supported with implementation-defined semantics.
877   if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
878     if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
879       if (!Record->hasNonTrivialCopyConstructor() &&
880           !Record->hasNonTrivialMoveConstructor() &&
881           !Record->hasNonTrivialDestructor())
882         return VAK_ValidInCXX11;
883 
884   if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
885     return VAK_Valid;
886 
887   if (Ty->isObjCObjectType())
888     return VAK_Invalid;
889 
890   if (getLangOpts().MSVCCompat)
891     return VAK_MSVCUndefined;
892 
893   // FIXME: In C++11, these cases are conditionally-supported, meaning we're
894   // permitted to reject them. We should consider doing so.
895   return VAK_Undefined;
896 }
897 
898 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
899   // Don't allow one to pass an Objective-C interface to a vararg.
900   const QualType &Ty = E->getType();
901   VarArgKind VAK = isValidVarArgType(Ty);
902 
903   // Complain about passing non-POD types through varargs.
904   switch (VAK) {
905   case VAK_ValidInCXX11:
906     DiagRuntimeBehavior(
907         E->getBeginLoc(), nullptr,
908         PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT);
909     LLVM_FALLTHROUGH;
910   case VAK_Valid:
911     if (Ty->isRecordType()) {
912       // This is unlikely to be what the user intended. If the class has a
913       // 'c_str' member function, the user probably meant to call that.
914       DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
915                           PDiag(diag::warn_pass_class_arg_to_vararg)
916                               << Ty << CT << hasCStrMethod(E) << ".c_str()");
917     }
918     break;
919 
920   case VAK_Undefined:
921   case VAK_MSVCUndefined:
922     DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
923                         PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
924                             << getLangOpts().CPlusPlus11 << Ty << CT);
925     break;
926 
927   case VAK_Invalid:
928     if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
929       Diag(E->getBeginLoc(),
930            diag::err_cannot_pass_non_trivial_c_struct_to_vararg)
931           << Ty << CT;
932     else if (Ty->isObjCObjectType())
933       DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
934                           PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
935                               << Ty << CT);
936     else
937       Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg)
938           << isa<InitListExpr>(E) << Ty << CT;
939     break;
940   }
941 }
942 
943 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
944 /// will create a trap if the resulting type is not a POD type.
945 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
946                                                   FunctionDecl *FDecl) {
947   if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
948     // Strip the unbridged-cast placeholder expression off, if applicable.
949     if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
950         (CT == VariadicMethod ||
951          (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
952       E = stripARCUnbridgedCast(E);
953 
954     // Otherwise, do normal placeholder checking.
955     } else {
956       ExprResult ExprRes = CheckPlaceholderExpr(E);
957       if (ExprRes.isInvalid())
958         return ExprError();
959       E = ExprRes.get();
960     }
961   }
962 
963   ExprResult ExprRes = DefaultArgumentPromotion(E);
964   if (ExprRes.isInvalid())
965     return ExprError();
966 
967   // Copy blocks to the heap.
968   if (ExprRes.get()->getType()->isBlockPointerType())
969     maybeExtendBlockObject(ExprRes);
970 
971   E = ExprRes.get();
972 
973   // Diagnostics regarding non-POD argument types are
974   // emitted along with format string checking in Sema::CheckFunctionCall().
975   if (isValidVarArgType(E->getType()) == VAK_Undefined) {
976     // Turn this into a trap.
977     CXXScopeSpec SS;
978     SourceLocation TemplateKWLoc;
979     UnqualifiedId Name;
980     Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
981                        E->getBeginLoc());
982     ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name,
983                                           /*HasTrailingLParen=*/true,
984                                           /*IsAddressOfOperand=*/false);
985     if (TrapFn.isInvalid())
986       return ExprError();
987 
988     ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(),
989                                     None, E->getEndLoc());
990     if (Call.isInvalid())
991       return ExprError();
992 
993     ExprResult Comma =
994         ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E);
995     if (Comma.isInvalid())
996       return ExprError();
997     return Comma.get();
998   }
999 
1000   if (!getLangOpts().CPlusPlus &&
1001       RequireCompleteType(E->getExprLoc(), E->getType(),
1002                           diag::err_call_incomplete_argument))
1003     return ExprError();
1004 
1005   return E;
1006 }
1007 
1008 /// Converts an integer to complex float type.  Helper function of
1009 /// UsualArithmeticConversions()
1010 ///
1011 /// \return false if the integer expression is an integer type and is
1012 /// successfully converted to the complex type.
1013 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
1014                                                   ExprResult &ComplexExpr,
1015                                                   QualType IntTy,
1016                                                   QualType ComplexTy,
1017                                                   bool SkipCast) {
1018   if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
1019   if (SkipCast) return false;
1020   if (IntTy->isIntegerType()) {
1021     QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
1022     IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
1023     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1024                                   CK_FloatingRealToComplex);
1025   } else {
1026     assert(IntTy->isComplexIntegerType());
1027     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1028                                   CK_IntegralComplexToFloatingComplex);
1029   }
1030   return false;
1031 }
1032 
1033 /// Handle arithmetic conversion with complex types.  Helper function of
1034 /// UsualArithmeticConversions()
1035 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
1036                                              ExprResult &RHS, QualType LHSType,
1037                                              QualType RHSType,
1038                                              bool IsCompAssign) {
1039   // if we have an integer operand, the result is the complex type.
1040   if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
1041                                              /*skipCast*/false))
1042     return LHSType;
1043   if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
1044                                              /*skipCast*/IsCompAssign))
1045     return RHSType;
1046 
1047   // This handles complex/complex, complex/float, or float/complex.
1048   // When both operands are complex, the shorter operand is converted to the
1049   // type of the longer, and that is the type of the result. This corresponds
1050   // to what is done when combining two real floating-point operands.
1051   // The fun begins when size promotion occur across type domains.
1052   // From H&S 6.3.4: When one operand is complex and the other is a real
1053   // floating-point type, the less precise type is converted, within it's
1054   // real or complex domain, to the precision of the other type. For example,
1055   // when combining a "long double" with a "double _Complex", the
1056   // "double _Complex" is promoted to "long double _Complex".
1057 
1058   // Compute the rank of the two types, regardless of whether they are complex.
1059   int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1060 
1061   auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
1062   auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
1063   QualType LHSElementType =
1064       LHSComplexType ? LHSComplexType->getElementType() : LHSType;
1065   QualType RHSElementType =
1066       RHSComplexType ? RHSComplexType->getElementType() : RHSType;
1067 
1068   QualType ResultType = S.Context.getComplexType(LHSElementType);
1069   if (Order < 0) {
1070     // Promote the precision of the LHS if not an assignment.
1071     ResultType = S.Context.getComplexType(RHSElementType);
1072     if (!IsCompAssign) {
1073       if (LHSComplexType)
1074         LHS =
1075             S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
1076       else
1077         LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
1078     }
1079   } else if (Order > 0) {
1080     // Promote the precision of the RHS.
1081     if (RHSComplexType)
1082       RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
1083     else
1084       RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
1085   }
1086   return ResultType;
1087 }
1088 
1089 /// Handle arithmetic conversion from integer to float.  Helper function
1090 /// of UsualArithmeticConversions()
1091 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1092                                            ExprResult &IntExpr,
1093                                            QualType FloatTy, QualType IntTy,
1094                                            bool ConvertFloat, bool ConvertInt) {
1095   if (IntTy->isIntegerType()) {
1096     if (ConvertInt)
1097       // Convert intExpr to the lhs floating point type.
1098       IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1099                                     CK_IntegralToFloating);
1100     return FloatTy;
1101   }
1102 
1103   // Convert both sides to the appropriate complex float.
1104   assert(IntTy->isComplexIntegerType());
1105   QualType result = S.Context.getComplexType(FloatTy);
1106 
1107   // _Complex int -> _Complex float
1108   if (ConvertInt)
1109     IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1110                                   CK_IntegralComplexToFloatingComplex);
1111 
1112   // float -> _Complex float
1113   if (ConvertFloat)
1114     FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1115                                     CK_FloatingRealToComplex);
1116 
1117   return result;
1118 }
1119 
1120 /// Handle arithmethic conversion with floating point types.  Helper
1121 /// function of UsualArithmeticConversions()
1122 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1123                                       ExprResult &RHS, QualType LHSType,
1124                                       QualType RHSType, bool IsCompAssign) {
1125   bool LHSFloat = LHSType->isRealFloatingType();
1126   bool RHSFloat = RHSType->isRealFloatingType();
1127 
1128   // FIXME: Implement floating to fixed point conversion.(Bug 46268)
1129   // Reference N1169 4.1.4 (Type conversion, usual arithmetic conversions).
1130   if ((LHSType->isFixedPointType() && RHSFloat) ||
1131       (LHSFloat && RHSType->isFixedPointType()))
1132     return QualType();
1133   // If we have two real floating types, convert the smaller operand
1134   // to the bigger result.
1135   if (LHSFloat && RHSFloat) {
1136     int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1137     if (order > 0) {
1138       RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1139       return LHSType;
1140     }
1141 
1142     assert(order < 0 && "illegal float comparison");
1143     if (!IsCompAssign)
1144       LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1145     return RHSType;
1146   }
1147 
1148   if (LHSFloat) {
1149     // Half FP has to be promoted to float unless it is natively supported
1150     if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1151       LHSType = S.Context.FloatTy;
1152 
1153     return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1154                                       /*ConvertFloat=*/!IsCompAssign,
1155                                       /*ConvertInt=*/ true);
1156   }
1157   assert(RHSFloat);
1158   return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1159                                     /*ConvertFloat=*/ true,
1160                                     /*ConvertInt=*/!IsCompAssign);
1161 }
1162 
1163 /// Diagnose attempts to convert between __float128 and long double if
1164 /// there is no support for such conversion. Helper function of
1165 /// UsualArithmeticConversions().
1166 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1167                                       QualType RHSType) {
1168   /*  No issue converting if at least one of the types is not a floating point
1169       type or the two types have the same rank.
1170   */
1171   if (!LHSType->isFloatingType() || !RHSType->isFloatingType() ||
1172       S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0)
1173     return false;
1174 
1175   assert(LHSType->isFloatingType() && RHSType->isFloatingType() &&
1176          "The remaining types must be floating point types.");
1177 
1178   auto *LHSComplex = LHSType->getAs<ComplexType>();
1179   auto *RHSComplex = RHSType->getAs<ComplexType>();
1180 
1181   QualType LHSElemType = LHSComplex ?
1182     LHSComplex->getElementType() : LHSType;
1183   QualType RHSElemType = RHSComplex ?
1184     RHSComplex->getElementType() : RHSType;
1185 
1186   // No issue if the two types have the same representation
1187   if (&S.Context.getFloatTypeSemantics(LHSElemType) ==
1188       &S.Context.getFloatTypeSemantics(RHSElemType))
1189     return false;
1190 
1191   bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty &&
1192                                 RHSElemType == S.Context.LongDoubleTy);
1193   Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy &&
1194                             RHSElemType == S.Context.Float128Ty);
1195 
1196   // We've handled the situation where __float128 and long double have the same
1197   // representation. We allow all conversions for all possible long double types
1198   // except PPC's double double.
1199   return Float128AndLongDouble &&
1200     (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) ==
1201      &llvm::APFloat::PPCDoubleDouble());
1202 }
1203 
1204 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1205 
1206 namespace {
1207 /// These helper callbacks are placed in an anonymous namespace to
1208 /// permit their use as function template parameters.
1209 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1210   return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1211 }
1212 
1213 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1214   return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1215                              CK_IntegralComplexCast);
1216 }
1217 }
1218 
1219 /// Handle integer arithmetic conversions.  Helper function of
1220 /// UsualArithmeticConversions()
1221 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1222 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1223                                         ExprResult &RHS, QualType LHSType,
1224                                         QualType RHSType, bool IsCompAssign) {
1225   // The rules for this case are in C99 6.3.1.8
1226   int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1227   bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1228   bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1229   if (LHSSigned == RHSSigned) {
1230     // Same signedness; use the higher-ranked type
1231     if (order >= 0) {
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 (order != (LHSSigned ? 1 : -1)) {
1238     // The unsigned type has greater than or equal rank to the
1239     // signed type, so use the unsigned type
1240     if (RHSSigned) {
1241       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1242       return LHSType;
1243     } else if (!IsCompAssign)
1244       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1245     return RHSType;
1246   } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1247     // The two types are different widths; if we are here, that
1248     // means the signed type is larger than the unsigned type, so
1249     // use the signed type.
1250     if (LHSSigned) {
1251       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1252       return LHSType;
1253     } else if (!IsCompAssign)
1254       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1255     return RHSType;
1256   } else {
1257     // The signed type is higher-ranked than the unsigned type,
1258     // but isn't actually any bigger (like unsigned int and long
1259     // on most 32-bit systems).  Use the unsigned type corresponding
1260     // to the signed type.
1261     QualType result =
1262       S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1263     RHS = (*doRHSCast)(S, RHS.get(), result);
1264     if (!IsCompAssign)
1265       LHS = (*doLHSCast)(S, LHS.get(), result);
1266     return result;
1267   }
1268 }
1269 
1270 /// Handle conversions with GCC complex int extension.  Helper function
1271 /// of UsualArithmeticConversions()
1272 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1273                                            ExprResult &RHS, QualType LHSType,
1274                                            QualType RHSType,
1275                                            bool IsCompAssign) {
1276   const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1277   const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1278 
1279   if (LHSComplexInt && RHSComplexInt) {
1280     QualType LHSEltType = LHSComplexInt->getElementType();
1281     QualType RHSEltType = RHSComplexInt->getElementType();
1282     QualType ScalarType =
1283       handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1284         (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1285 
1286     return S.Context.getComplexType(ScalarType);
1287   }
1288 
1289   if (LHSComplexInt) {
1290     QualType LHSEltType = LHSComplexInt->getElementType();
1291     QualType ScalarType =
1292       handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1293         (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1294     QualType ComplexType = S.Context.getComplexType(ScalarType);
1295     RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1296                               CK_IntegralRealToComplex);
1297 
1298     return ComplexType;
1299   }
1300 
1301   assert(RHSComplexInt);
1302 
1303   QualType RHSEltType = RHSComplexInt->getElementType();
1304   QualType ScalarType =
1305     handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1306       (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1307   QualType ComplexType = S.Context.getComplexType(ScalarType);
1308 
1309   if (!IsCompAssign)
1310     LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1311                               CK_IntegralRealToComplex);
1312   return ComplexType;
1313 }
1314 
1315 /// Return the rank of a given fixed point or integer type. The value itself
1316 /// doesn't matter, but the values must be increasing with proper increasing
1317 /// rank as described in N1169 4.1.1.
1318 static unsigned GetFixedPointRank(QualType Ty) {
1319   const auto *BTy = Ty->getAs<BuiltinType>();
1320   assert(BTy && "Expected a builtin type.");
1321 
1322   switch (BTy->getKind()) {
1323   case BuiltinType::ShortFract:
1324   case BuiltinType::UShortFract:
1325   case BuiltinType::SatShortFract:
1326   case BuiltinType::SatUShortFract:
1327     return 1;
1328   case BuiltinType::Fract:
1329   case BuiltinType::UFract:
1330   case BuiltinType::SatFract:
1331   case BuiltinType::SatUFract:
1332     return 2;
1333   case BuiltinType::LongFract:
1334   case BuiltinType::ULongFract:
1335   case BuiltinType::SatLongFract:
1336   case BuiltinType::SatULongFract:
1337     return 3;
1338   case BuiltinType::ShortAccum:
1339   case BuiltinType::UShortAccum:
1340   case BuiltinType::SatShortAccum:
1341   case BuiltinType::SatUShortAccum:
1342     return 4;
1343   case BuiltinType::Accum:
1344   case BuiltinType::UAccum:
1345   case BuiltinType::SatAccum:
1346   case BuiltinType::SatUAccum:
1347     return 5;
1348   case BuiltinType::LongAccum:
1349   case BuiltinType::ULongAccum:
1350   case BuiltinType::SatLongAccum:
1351   case BuiltinType::SatULongAccum:
1352     return 6;
1353   default:
1354     if (BTy->isInteger())
1355       return 0;
1356     llvm_unreachable("Unexpected fixed point or integer type");
1357   }
1358 }
1359 
1360 /// handleFixedPointConversion - Fixed point operations between fixed
1361 /// point types and integers or other fixed point types do not fall under
1362 /// usual arithmetic conversion since these conversions could result in loss
1363 /// of precsision (N1169 4.1.4). These operations should be calculated with
1364 /// the full precision of their result type (N1169 4.1.6.2.1).
1365 static QualType handleFixedPointConversion(Sema &S, QualType LHSTy,
1366                                            QualType RHSTy) {
1367   assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) &&
1368          "Expected at least one of the operands to be a fixed point type");
1369   assert((LHSTy->isFixedPointOrIntegerType() ||
1370           RHSTy->isFixedPointOrIntegerType()) &&
1371          "Special fixed point arithmetic operation conversions are only "
1372          "applied to ints or other fixed point types");
1373 
1374   // If one operand has signed fixed-point type and the other operand has
1375   // unsigned fixed-point type, then the unsigned fixed-point operand is
1376   // converted to its corresponding signed fixed-point type and the resulting
1377   // type is the type of the converted operand.
1378   if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType())
1379     LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy);
1380   else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType())
1381     RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy);
1382 
1383   // The result type is the type with the highest rank, whereby a fixed-point
1384   // conversion rank is always greater than an integer conversion rank; if the
1385   // type of either of the operands is a saturating fixedpoint type, the result
1386   // type shall be the saturating fixed-point type corresponding to the type
1387   // with the highest rank; the resulting value is converted (taking into
1388   // account rounding and overflow) to the precision of the resulting type.
1389   // Same ranks between signed and unsigned types are resolved earlier, so both
1390   // types are either signed or both unsigned at this point.
1391   unsigned LHSTyRank = GetFixedPointRank(LHSTy);
1392   unsigned RHSTyRank = GetFixedPointRank(RHSTy);
1393 
1394   QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy;
1395 
1396   if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType())
1397     ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy);
1398 
1399   return ResultTy;
1400 }
1401 
1402 /// Check that the usual arithmetic conversions can be performed on this pair of
1403 /// expressions that might be of enumeration type.
1404 static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS,
1405                                            SourceLocation Loc,
1406                                            Sema::ArithConvKind ACK) {
1407   // C++2a [expr.arith.conv]p1:
1408   //   If one operand is of enumeration type and the other operand is of a
1409   //   different enumeration type or a floating-point type, this behavior is
1410   //   deprecated ([depr.arith.conv.enum]).
1411   //
1412   // Warn on this in all language modes. Produce a deprecation warning in C++20.
1413   // Eventually we will presumably reject these cases (in C++23 onwards?).
1414   QualType L = LHS->getType(), R = RHS->getType();
1415   bool LEnum = L->isUnscopedEnumerationType(),
1416        REnum = R->isUnscopedEnumerationType();
1417   bool IsCompAssign = ACK == Sema::ACK_CompAssign;
1418   if ((!IsCompAssign && LEnum && R->isFloatingType()) ||
1419       (REnum && L->isFloatingType())) {
1420     S.Diag(Loc, S.getLangOpts().CPlusPlus20
1421                     ? diag::warn_arith_conv_enum_float_cxx20
1422                     : diag::warn_arith_conv_enum_float)
1423         << LHS->getSourceRange() << RHS->getSourceRange()
1424         << (int)ACK << LEnum << L << R;
1425   } else if (!IsCompAssign && LEnum && REnum &&
1426              !S.Context.hasSameUnqualifiedType(L, R)) {
1427     unsigned DiagID;
1428     if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() ||
1429         !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) {
1430       // If either enumeration type is unnamed, it's less likely that the
1431       // user cares about this, but this situation is still deprecated in
1432       // C++2a. Use a different warning group.
1433       DiagID = S.getLangOpts().CPlusPlus20
1434                     ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20
1435                     : diag::warn_arith_conv_mixed_anon_enum_types;
1436     } else if (ACK == Sema::ACK_Conditional) {
1437       // Conditional expressions are separated out because they have
1438       // historically had a different warning flag.
1439       DiagID = S.getLangOpts().CPlusPlus20
1440                    ? diag::warn_conditional_mixed_enum_types_cxx20
1441                    : diag::warn_conditional_mixed_enum_types;
1442     } else if (ACK == Sema::ACK_Comparison) {
1443       // Comparison expressions are separated out because they have
1444       // historically had a different warning flag.
1445       DiagID = S.getLangOpts().CPlusPlus20
1446                    ? diag::warn_comparison_mixed_enum_types_cxx20
1447                    : diag::warn_comparison_mixed_enum_types;
1448     } else {
1449       DiagID = S.getLangOpts().CPlusPlus20
1450                    ? diag::warn_arith_conv_mixed_enum_types_cxx20
1451                    : diag::warn_arith_conv_mixed_enum_types;
1452     }
1453     S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
1454                         << (int)ACK << L << R;
1455   }
1456 }
1457 
1458 /// UsualArithmeticConversions - Performs various conversions that are common to
1459 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1460 /// routine returns the first non-arithmetic type found. The client is
1461 /// responsible for emitting appropriate error diagnostics.
1462 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1463                                           SourceLocation Loc,
1464                                           ArithConvKind ACK) {
1465   checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK);
1466 
1467   if (ACK != ACK_CompAssign) {
1468     LHS = UsualUnaryConversions(LHS.get());
1469     if (LHS.isInvalid())
1470       return QualType();
1471   }
1472 
1473   RHS = UsualUnaryConversions(RHS.get());
1474   if (RHS.isInvalid())
1475     return QualType();
1476 
1477   // For conversion purposes, we ignore any qualifiers.
1478   // For example, "const float" and "float" are equivalent.
1479   QualType LHSType =
1480     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1481   QualType RHSType =
1482     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1483 
1484   // For conversion purposes, we ignore any atomic qualifier on the LHS.
1485   if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1486     LHSType = AtomicLHS->getValueType();
1487 
1488   // If both types are identical, no conversion is needed.
1489   if (LHSType == RHSType)
1490     return LHSType;
1491 
1492   // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1493   // The caller can deal with this (e.g. pointer + int).
1494   if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1495     return QualType();
1496 
1497   // Apply unary and bitfield promotions to the LHS's type.
1498   QualType LHSUnpromotedType = LHSType;
1499   if (LHSType->isPromotableIntegerType())
1500     LHSType = Context.getPromotedIntegerType(LHSType);
1501   QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1502   if (!LHSBitfieldPromoteTy.isNull())
1503     LHSType = LHSBitfieldPromoteTy;
1504   if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign)
1505     LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1506 
1507   // If both types are identical, no conversion is needed.
1508   if (LHSType == RHSType)
1509     return LHSType;
1510 
1511   // ExtInt types aren't subject to conversions between them or normal integers,
1512   // so this fails.
1513   if(LHSType->isExtIntType() || RHSType->isExtIntType())
1514     return QualType();
1515 
1516   // At this point, we have two different arithmetic types.
1517 
1518   // Diagnose attempts to convert between __float128 and long double where
1519   // such conversions currently can't be handled.
1520   if (unsupportedTypeConversion(*this, LHSType, RHSType))
1521     return QualType();
1522 
1523   // Handle complex types first (C99 6.3.1.8p1).
1524   if (LHSType->isComplexType() || RHSType->isComplexType())
1525     return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1526                                         ACK == ACK_CompAssign);
1527 
1528   // Now handle "real" floating types (i.e. float, double, long double).
1529   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1530     return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1531                                  ACK == ACK_CompAssign);
1532 
1533   // Handle GCC complex int extension.
1534   if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1535     return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1536                                       ACK == ACK_CompAssign);
1537 
1538   if (LHSType->isFixedPointType() || RHSType->isFixedPointType())
1539     return handleFixedPointConversion(*this, LHSType, RHSType);
1540 
1541   // Finally, we have two differing integer types.
1542   return handleIntegerConversion<doIntegralCast, doIntegralCast>
1543            (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign);
1544 }
1545 
1546 //===----------------------------------------------------------------------===//
1547 //  Semantic Analysis for various Expression Types
1548 //===----------------------------------------------------------------------===//
1549 
1550 
1551 ExprResult
1552 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1553                                 SourceLocation DefaultLoc,
1554                                 SourceLocation RParenLoc,
1555                                 Expr *ControllingExpr,
1556                                 ArrayRef<ParsedType> ArgTypes,
1557                                 ArrayRef<Expr *> ArgExprs) {
1558   unsigned NumAssocs = ArgTypes.size();
1559   assert(NumAssocs == ArgExprs.size());
1560 
1561   TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1562   for (unsigned i = 0; i < NumAssocs; ++i) {
1563     if (ArgTypes[i])
1564       (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1565     else
1566       Types[i] = nullptr;
1567   }
1568 
1569   ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1570                                              ControllingExpr,
1571                                              llvm::makeArrayRef(Types, NumAssocs),
1572                                              ArgExprs);
1573   delete [] Types;
1574   return ER;
1575 }
1576 
1577 ExprResult
1578 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1579                                  SourceLocation DefaultLoc,
1580                                  SourceLocation RParenLoc,
1581                                  Expr *ControllingExpr,
1582                                  ArrayRef<TypeSourceInfo *> Types,
1583                                  ArrayRef<Expr *> Exprs) {
1584   unsigned NumAssocs = Types.size();
1585   assert(NumAssocs == Exprs.size());
1586 
1587   // Decay and strip qualifiers for the controlling expression type, and handle
1588   // placeholder type replacement. See committee discussion from WG14 DR423.
1589   {
1590     EnterExpressionEvaluationContext Unevaluated(
1591         *this, Sema::ExpressionEvaluationContext::Unevaluated);
1592     ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
1593     if (R.isInvalid())
1594       return ExprError();
1595     ControllingExpr = R.get();
1596   }
1597 
1598   // The controlling expression is an unevaluated operand, so side effects are
1599   // likely unintended.
1600   if (!inTemplateInstantiation() &&
1601       ControllingExpr->HasSideEffects(Context, false))
1602     Diag(ControllingExpr->getExprLoc(),
1603          diag::warn_side_effects_unevaluated_context);
1604 
1605   bool TypeErrorFound = false,
1606        IsResultDependent = ControllingExpr->isTypeDependent(),
1607        ContainsUnexpandedParameterPack
1608          = ControllingExpr->containsUnexpandedParameterPack();
1609 
1610   for (unsigned i = 0; i < NumAssocs; ++i) {
1611     if (Exprs[i]->containsUnexpandedParameterPack())
1612       ContainsUnexpandedParameterPack = true;
1613 
1614     if (Types[i]) {
1615       if (Types[i]->getType()->containsUnexpandedParameterPack())
1616         ContainsUnexpandedParameterPack = true;
1617 
1618       if (Types[i]->getType()->isDependentType()) {
1619         IsResultDependent = true;
1620       } else {
1621         // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1622         // complete object type other than a variably modified type."
1623         unsigned D = 0;
1624         if (Types[i]->getType()->isIncompleteType())
1625           D = diag::err_assoc_type_incomplete;
1626         else if (!Types[i]->getType()->isObjectType())
1627           D = diag::err_assoc_type_nonobject;
1628         else if (Types[i]->getType()->isVariablyModifiedType())
1629           D = diag::err_assoc_type_variably_modified;
1630 
1631         if (D != 0) {
1632           Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1633             << Types[i]->getTypeLoc().getSourceRange()
1634             << Types[i]->getType();
1635           TypeErrorFound = true;
1636         }
1637 
1638         // C11 6.5.1.1p2 "No two generic associations in the same generic
1639         // selection shall specify compatible types."
1640         for (unsigned j = i+1; j < NumAssocs; ++j)
1641           if (Types[j] && !Types[j]->getType()->isDependentType() &&
1642               Context.typesAreCompatible(Types[i]->getType(),
1643                                          Types[j]->getType())) {
1644             Diag(Types[j]->getTypeLoc().getBeginLoc(),
1645                  diag::err_assoc_compatible_types)
1646               << Types[j]->getTypeLoc().getSourceRange()
1647               << Types[j]->getType()
1648               << Types[i]->getType();
1649             Diag(Types[i]->getTypeLoc().getBeginLoc(),
1650                  diag::note_compat_assoc)
1651               << Types[i]->getTypeLoc().getSourceRange()
1652               << Types[i]->getType();
1653             TypeErrorFound = true;
1654           }
1655       }
1656     }
1657   }
1658   if (TypeErrorFound)
1659     return ExprError();
1660 
1661   // If we determined that the generic selection is result-dependent, don't
1662   // try to compute the result expression.
1663   if (IsResultDependent)
1664     return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types,
1665                                         Exprs, DefaultLoc, RParenLoc,
1666                                         ContainsUnexpandedParameterPack);
1667 
1668   SmallVector<unsigned, 1> CompatIndices;
1669   unsigned DefaultIndex = -1U;
1670   for (unsigned i = 0; i < NumAssocs; ++i) {
1671     if (!Types[i])
1672       DefaultIndex = i;
1673     else if (Context.typesAreCompatible(ControllingExpr->getType(),
1674                                         Types[i]->getType()))
1675       CompatIndices.push_back(i);
1676   }
1677 
1678   // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1679   // type compatible with at most one of the types named in its generic
1680   // association list."
1681   if (CompatIndices.size() > 1) {
1682     // We strip parens here because the controlling expression is typically
1683     // parenthesized in macro definitions.
1684     ControllingExpr = ControllingExpr->IgnoreParens();
1685     Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match)
1686         << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1687         << (unsigned)CompatIndices.size();
1688     for (unsigned I : CompatIndices) {
1689       Diag(Types[I]->getTypeLoc().getBeginLoc(),
1690            diag::note_compat_assoc)
1691         << Types[I]->getTypeLoc().getSourceRange()
1692         << Types[I]->getType();
1693     }
1694     return ExprError();
1695   }
1696 
1697   // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1698   // its controlling expression shall have type compatible with exactly one of
1699   // the types named in its generic association list."
1700   if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1701     // We strip parens here because the controlling expression is typically
1702     // parenthesized in macro definitions.
1703     ControllingExpr = ControllingExpr->IgnoreParens();
1704     Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match)
1705         << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1706     return ExprError();
1707   }
1708 
1709   // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1710   // type name that is compatible with the type of the controlling expression,
1711   // then the result expression of the generic selection is the expression
1712   // in that generic association. Otherwise, the result expression of the
1713   // generic selection is the expression in the default generic association."
1714   unsigned ResultIndex =
1715     CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1716 
1717   return GenericSelectionExpr::Create(
1718       Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1719       ContainsUnexpandedParameterPack, ResultIndex);
1720 }
1721 
1722 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1723 /// location of the token and the offset of the ud-suffix within it.
1724 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1725                                      unsigned Offset) {
1726   return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1727                                         S.getLangOpts());
1728 }
1729 
1730 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1731 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
1732 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1733                                                  IdentifierInfo *UDSuffix,
1734                                                  SourceLocation UDSuffixLoc,
1735                                                  ArrayRef<Expr*> Args,
1736                                                  SourceLocation LitEndLoc) {
1737   assert(Args.size() <= 2 && "too many arguments for literal operator");
1738 
1739   QualType ArgTy[2];
1740   for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1741     ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1742     if (ArgTy[ArgIdx]->isArrayType())
1743       ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1744   }
1745 
1746   DeclarationName OpName =
1747     S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1748   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1749   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1750 
1751   LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1752   if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1753                               /*AllowRaw*/ false, /*AllowTemplate*/ false,
1754                               /*AllowStringTemplate*/ false,
1755                               /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
1756     return ExprError();
1757 
1758   return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1759 }
1760 
1761 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1762 /// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
1763 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1764 /// multiple tokens.  However, the common case is that StringToks points to one
1765 /// string.
1766 ///
1767 ExprResult
1768 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
1769   assert(!StringToks.empty() && "Must have at least one string!");
1770 
1771   StringLiteralParser Literal(StringToks, PP);
1772   if (Literal.hadError)
1773     return ExprError();
1774 
1775   SmallVector<SourceLocation, 4> StringTokLocs;
1776   for (const Token &Tok : StringToks)
1777     StringTokLocs.push_back(Tok.getLocation());
1778 
1779   QualType CharTy = Context.CharTy;
1780   StringLiteral::StringKind Kind = StringLiteral::Ascii;
1781   if (Literal.isWide()) {
1782     CharTy = Context.getWideCharType();
1783     Kind = StringLiteral::Wide;
1784   } else if (Literal.isUTF8()) {
1785     if (getLangOpts().Char8)
1786       CharTy = Context.Char8Ty;
1787     Kind = StringLiteral::UTF8;
1788   } else if (Literal.isUTF16()) {
1789     CharTy = Context.Char16Ty;
1790     Kind = StringLiteral::UTF16;
1791   } else if (Literal.isUTF32()) {
1792     CharTy = Context.Char32Ty;
1793     Kind = StringLiteral::UTF32;
1794   } else if (Literal.isPascal()) {
1795     CharTy = Context.UnsignedCharTy;
1796   }
1797 
1798   // Warn on initializing an array of char from a u8 string literal; this
1799   // becomes ill-formed in C++2a.
1800   if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus20 &&
1801       !getLangOpts().Char8 && Kind == StringLiteral::UTF8) {
1802     Diag(StringTokLocs.front(), diag::warn_cxx20_compat_utf8_string);
1803 
1804     // Create removals for all 'u8' prefixes in the string literal(s). This
1805     // ensures C++2a compatibility (but may change the program behavior when
1806     // built by non-Clang compilers for which the execution character set is
1807     // not always UTF-8).
1808     auto RemovalDiag = PDiag(diag::note_cxx20_compat_utf8_string_remove_u8);
1809     SourceLocation RemovalDiagLoc;
1810     for (const Token &Tok : StringToks) {
1811       if (Tok.getKind() == tok::utf8_string_literal) {
1812         if (RemovalDiagLoc.isInvalid())
1813           RemovalDiagLoc = Tok.getLocation();
1814         RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange(
1815             Tok.getLocation(),
1816             Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2,
1817                                            getSourceManager(), getLangOpts())));
1818       }
1819     }
1820     Diag(RemovalDiagLoc, RemovalDiag);
1821   }
1822 
1823   QualType StrTy =
1824       Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars());
1825 
1826   // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1827   StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1828                                              Kind, Literal.Pascal, StrTy,
1829                                              &StringTokLocs[0],
1830                                              StringTokLocs.size());
1831   if (Literal.getUDSuffix().empty())
1832     return Lit;
1833 
1834   // We're building a user-defined literal.
1835   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1836   SourceLocation UDSuffixLoc =
1837     getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1838                    Literal.getUDSuffixOffset());
1839 
1840   // Make sure we're allowed user-defined literals here.
1841   if (!UDLScope)
1842     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1843 
1844   // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1845   //   operator "" X (str, len)
1846   QualType SizeType = Context.getSizeType();
1847 
1848   DeclarationName OpName =
1849     Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1850   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1851   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1852 
1853   QualType ArgTy[] = {
1854     Context.getArrayDecayedType(StrTy), SizeType
1855   };
1856 
1857   LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1858   switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1859                                 /*AllowRaw*/ false, /*AllowTemplate*/ false,
1860                                 /*AllowStringTemplate*/ true,
1861                                 /*DiagnoseMissing*/ true)) {
1862 
1863   case LOLR_Cooked: {
1864     llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1865     IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1866                                                     StringTokLocs[0]);
1867     Expr *Args[] = { Lit, LenArg };
1868 
1869     return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1870   }
1871 
1872   case LOLR_StringTemplate: {
1873     TemplateArgumentListInfo ExplicitArgs;
1874 
1875     unsigned CharBits = Context.getIntWidth(CharTy);
1876     bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1877     llvm::APSInt Value(CharBits, CharIsUnsigned);
1878 
1879     TemplateArgument TypeArg(CharTy);
1880     TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1881     ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1882 
1883     for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1884       Value = Lit->getCodeUnit(I);
1885       TemplateArgument Arg(Context, Value, CharTy);
1886       TemplateArgumentLocInfo ArgInfo;
1887       ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1888     }
1889     return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1890                                     &ExplicitArgs);
1891   }
1892   case LOLR_Raw:
1893   case LOLR_Template:
1894   case LOLR_ErrorNoDiagnostic:
1895     llvm_unreachable("unexpected literal operator lookup result");
1896   case LOLR_Error:
1897     return ExprError();
1898   }
1899   llvm_unreachable("unexpected literal operator lookup result");
1900 }
1901 
1902 DeclRefExpr *
1903 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1904                        SourceLocation Loc,
1905                        const CXXScopeSpec *SS) {
1906   DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1907   return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1908 }
1909 
1910 DeclRefExpr *
1911 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1912                        const DeclarationNameInfo &NameInfo,
1913                        const CXXScopeSpec *SS, NamedDecl *FoundD,
1914                        SourceLocation TemplateKWLoc,
1915                        const TemplateArgumentListInfo *TemplateArgs) {
1916   NestedNameSpecifierLoc NNS =
1917       SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc();
1918   return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc,
1919                           TemplateArgs);
1920 }
1921 
1922 NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) {
1923   // A declaration named in an unevaluated operand never constitutes an odr-use.
1924   if (isUnevaluatedContext())
1925     return NOUR_Unevaluated;
1926 
1927   // C++2a [basic.def.odr]p4:
1928   //   A variable x whose name appears as a potentially-evaluated expression e
1929   //   is odr-used by e unless [...] x is a reference that is usable in
1930   //   constant expressions.
1931   if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
1932     if (VD->getType()->isReferenceType() &&
1933         !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) &&
1934         VD->isUsableInConstantExpressions(Context))
1935       return NOUR_Constant;
1936   }
1937 
1938   // All remaining non-variable cases constitute an odr-use. For variables, we
1939   // need to wait and see how the expression is used.
1940   return NOUR_None;
1941 }
1942 
1943 /// BuildDeclRefExpr - Build an expression that references a
1944 /// declaration that does not require a closure capture.
1945 DeclRefExpr *
1946 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1947                        const DeclarationNameInfo &NameInfo,
1948                        NestedNameSpecifierLoc NNS, NamedDecl *FoundD,
1949                        SourceLocation TemplateKWLoc,
1950                        const TemplateArgumentListInfo *TemplateArgs) {
1951   bool RefersToCapturedVariable =
1952       isa<VarDecl>(D) &&
1953       NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
1954 
1955   DeclRefExpr *E = DeclRefExpr::Create(
1956       Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty,
1957       VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D));
1958   MarkDeclRefReferenced(E);
1959 
1960   // C++ [except.spec]p17:
1961   //   An exception-specification is considered to be needed when:
1962   //   - in an expression, the function is the unique lookup result or
1963   //     the selected member of a set of overloaded functions.
1964   //
1965   // We delay doing this until after we've built the function reference and
1966   // marked it as used so that:
1967   //  a) if the function is defaulted, we get errors from defining it before /
1968   //     instead of errors from computing its exception specification, and
1969   //  b) if the function is a defaulted comparison, we can use the body we
1970   //     build when defining it as input to the exception specification
1971   //     computation rather than computing a new body.
1972   if (auto *FPT = Ty->getAs<FunctionProtoType>()) {
1973     if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
1974       if (auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT))
1975         E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers()));
1976     }
1977   }
1978 
1979   if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
1980       Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() &&
1981       !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc()))
1982     getCurFunction()->recordUseOfWeak(E);
1983 
1984   FieldDecl *FD = dyn_cast<FieldDecl>(D);
1985   if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
1986     FD = IFD->getAnonField();
1987   if (FD) {
1988     UnusedPrivateFields.remove(FD);
1989     // Just in case we're building an illegal pointer-to-member.
1990     if (FD->isBitField())
1991       E->setObjectKind(OK_BitField);
1992   }
1993 
1994   // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
1995   // designates a bit-field.
1996   if (auto *BD = dyn_cast<BindingDecl>(D))
1997     if (auto *BE = BD->getBinding())
1998       E->setObjectKind(BE->getObjectKind());
1999 
2000   return E;
2001 }
2002 
2003 /// Decomposes the given name into a DeclarationNameInfo, its location, and
2004 /// possibly a list of template arguments.
2005 ///
2006 /// If this produces template arguments, it is permitted to call
2007 /// DecomposeTemplateName.
2008 ///
2009 /// This actually loses a lot of source location information for
2010 /// non-standard name kinds; we should consider preserving that in
2011 /// some way.
2012 void
2013 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
2014                              TemplateArgumentListInfo &Buffer,
2015                              DeclarationNameInfo &NameInfo,
2016                              const TemplateArgumentListInfo *&TemplateArgs) {
2017   if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) {
2018     Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
2019     Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
2020 
2021     ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
2022                                        Id.TemplateId->NumArgs);
2023     translateTemplateArguments(TemplateArgsPtr, Buffer);
2024 
2025     TemplateName TName = Id.TemplateId->Template.get();
2026     SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
2027     NameInfo = Context.getNameForTemplate(TName, TNameLoc);
2028     TemplateArgs = &Buffer;
2029   } else {
2030     NameInfo = GetNameFromUnqualifiedId(Id);
2031     TemplateArgs = nullptr;
2032   }
2033 }
2034 
2035 static void emitEmptyLookupTypoDiagnostic(
2036     const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
2037     DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
2038     unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
2039   DeclContext *Ctx =
2040       SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
2041   if (!TC) {
2042     // Emit a special diagnostic for failed member lookups.
2043     // FIXME: computing the declaration context might fail here (?)
2044     if (Ctx)
2045       SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
2046                                                  << SS.getRange();
2047     else
2048       SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
2049     return;
2050   }
2051 
2052   std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
2053   bool DroppedSpecifier =
2054       TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
2055   unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
2056                         ? diag::note_implicit_param_decl
2057                         : diag::note_previous_decl;
2058   if (!Ctx)
2059     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
2060                          SemaRef.PDiag(NoteID));
2061   else
2062     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
2063                                  << Typo << Ctx << DroppedSpecifier
2064                                  << SS.getRange(),
2065                          SemaRef.PDiag(NoteID));
2066 }
2067 
2068 /// Diagnose an empty lookup.
2069 ///
2070 /// \return false if new lookup candidates were found
2071 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
2072                                CorrectionCandidateCallback &CCC,
2073                                TemplateArgumentListInfo *ExplicitTemplateArgs,
2074                                ArrayRef<Expr *> Args, TypoExpr **Out) {
2075   DeclarationName Name = R.getLookupName();
2076 
2077   unsigned diagnostic = diag::err_undeclared_var_use;
2078   unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
2079   if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
2080       Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
2081       Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
2082     diagnostic = diag::err_undeclared_use;
2083     diagnostic_suggest = diag::err_undeclared_use_suggest;
2084   }
2085 
2086   // If the original lookup was an unqualified lookup, fake an
2087   // unqualified lookup.  This is useful when (for example) the
2088   // original lookup would not have found something because it was a
2089   // dependent name.
2090   DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
2091   while (DC) {
2092     if (isa<CXXRecordDecl>(DC)) {
2093       LookupQualifiedName(R, DC);
2094 
2095       if (!R.empty()) {
2096         // Don't give errors about ambiguities in this lookup.
2097         R.suppressDiagnostics();
2098 
2099         // During a default argument instantiation the CurContext points
2100         // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
2101         // function parameter list, hence add an explicit check.
2102         bool isDefaultArgument =
2103             !CodeSynthesisContexts.empty() &&
2104             CodeSynthesisContexts.back().Kind ==
2105                 CodeSynthesisContext::DefaultFunctionArgumentInstantiation;
2106         CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
2107         bool isInstance = CurMethod &&
2108                           CurMethod->isInstance() &&
2109                           DC == CurMethod->getParent() && !isDefaultArgument;
2110 
2111         // Give a code modification hint to insert 'this->'.
2112         // TODO: fixit for inserting 'Base<T>::' in the other cases.
2113         // Actually quite difficult!
2114         if (getLangOpts().MSVCCompat)
2115           diagnostic = diag::ext_found_via_dependent_bases_lookup;
2116         if (isInstance) {
2117           Diag(R.getNameLoc(), diagnostic) << Name
2118             << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
2119           CheckCXXThisCapture(R.getNameLoc());
2120         } else {
2121           Diag(R.getNameLoc(), diagnostic) << Name;
2122         }
2123 
2124         // Do we really want to note all of these?
2125         for (NamedDecl *D : R)
2126           Diag(D->getLocation(), diag::note_dependent_var_use);
2127 
2128         // Return true if we are inside a default argument instantiation
2129         // and the found name refers to an instance member function, otherwise
2130         // the function calling DiagnoseEmptyLookup will try to create an
2131         // implicit member call and this is wrong for default argument.
2132         if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
2133           Diag(R.getNameLoc(), diag::err_member_call_without_object);
2134           return true;
2135         }
2136 
2137         // Tell the callee to try to recover.
2138         return false;
2139       }
2140 
2141       R.clear();
2142     }
2143 
2144     DC = DC->getLookupParent();
2145   }
2146 
2147   // We didn't find anything, so try to correct for a typo.
2148   TypoCorrection Corrected;
2149   if (S && Out) {
2150     SourceLocation TypoLoc = R.getNameLoc();
2151     assert(!ExplicitTemplateArgs &&
2152            "Diagnosing an empty lookup with explicit template args!");
2153     *Out = CorrectTypoDelayed(
2154         R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
2155         [=](const TypoCorrection &TC) {
2156           emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
2157                                         diagnostic, diagnostic_suggest);
2158         },
2159         nullptr, CTK_ErrorRecovery);
2160     if (*Out)
2161       return true;
2162   } else if (S &&
2163              (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
2164                                       S, &SS, CCC, CTK_ErrorRecovery))) {
2165     std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
2166     bool DroppedSpecifier =
2167         Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
2168     R.setLookupName(Corrected.getCorrection());
2169 
2170     bool AcceptableWithRecovery = false;
2171     bool AcceptableWithoutRecovery = false;
2172     NamedDecl *ND = Corrected.getFoundDecl();
2173     if (ND) {
2174       if (Corrected.isOverloaded()) {
2175         OverloadCandidateSet OCS(R.getNameLoc(),
2176                                  OverloadCandidateSet::CSK_Normal);
2177         OverloadCandidateSet::iterator Best;
2178         for (NamedDecl *CD : Corrected) {
2179           if (FunctionTemplateDecl *FTD =
2180                    dyn_cast<FunctionTemplateDecl>(CD))
2181             AddTemplateOverloadCandidate(
2182                 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
2183                 Args, OCS);
2184           else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
2185             if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
2186               AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
2187                                    Args, OCS);
2188         }
2189         switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
2190         case OR_Success:
2191           ND = Best->FoundDecl;
2192           Corrected.setCorrectionDecl(ND);
2193           break;
2194         default:
2195           // FIXME: Arbitrarily pick the first declaration for the note.
2196           Corrected.setCorrectionDecl(ND);
2197           break;
2198         }
2199       }
2200       R.addDecl(ND);
2201       if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2202         CXXRecordDecl *Record = nullptr;
2203         if (Corrected.getCorrectionSpecifier()) {
2204           const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
2205           Record = Ty->getAsCXXRecordDecl();
2206         }
2207         if (!Record)
2208           Record = cast<CXXRecordDecl>(
2209               ND->getDeclContext()->getRedeclContext());
2210         R.setNamingClass(Record);
2211       }
2212 
2213       auto *UnderlyingND = ND->getUnderlyingDecl();
2214       AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2215                                isa<FunctionTemplateDecl>(UnderlyingND);
2216       // FIXME: If we ended up with a typo for a type name or
2217       // Objective-C class name, we're in trouble because the parser
2218       // is in the wrong place to recover. Suggest the typo
2219       // correction, but don't make it a fix-it since we're not going
2220       // to recover well anyway.
2221       AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) ||
2222                                   getAsTypeTemplateDecl(UnderlyingND) ||
2223                                   isa<ObjCInterfaceDecl>(UnderlyingND);
2224     } else {
2225       // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2226       // because we aren't able to recover.
2227       AcceptableWithoutRecovery = true;
2228     }
2229 
2230     if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2231       unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2232                             ? diag::note_implicit_param_decl
2233                             : diag::note_previous_decl;
2234       if (SS.isEmpty())
2235         diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
2236                      PDiag(NoteID), AcceptableWithRecovery);
2237       else
2238         diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
2239                                   << Name << computeDeclContext(SS, false)
2240                                   << DroppedSpecifier << SS.getRange(),
2241                      PDiag(NoteID), AcceptableWithRecovery);
2242 
2243       // Tell the callee whether to try to recover.
2244       return !AcceptableWithRecovery;
2245     }
2246   }
2247   R.clear();
2248 
2249   // Emit a special diagnostic for failed member lookups.
2250   // FIXME: computing the declaration context might fail here (?)
2251   if (!SS.isEmpty()) {
2252     Diag(R.getNameLoc(), diag::err_no_member)
2253       << Name << computeDeclContext(SS, false)
2254       << SS.getRange();
2255     return true;
2256   }
2257 
2258   // Give up, we can't recover.
2259   Diag(R.getNameLoc(), diagnostic) << Name;
2260   return true;
2261 }
2262 
2263 /// In Microsoft mode, if we are inside a template class whose parent class has
2264 /// dependent base classes, and we can't resolve an unqualified identifier, then
2265 /// assume the identifier is a member of a dependent base class.  We can only
2266 /// recover successfully in static methods, instance methods, and other contexts
2267 /// where 'this' is available.  This doesn't precisely match MSVC's
2268 /// instantiation model, but it's close enough.
2269 static Expr *
2270 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
2271                                DeclarationNameInfo &NameInfo,
2272                                SourceLocation TemplateKWLoc,
2273                                const TemplateArgumentListInfo *TemplateArgs) {
2274   // Only try to recover from lookup into dependent bases in static methods or
2275   // contexts where 'this' is available.
2276   QualType ThisType = S.getCurrentThisType();
2277   const CXXRecordDecl *RD = nullptr;
2278   if (!ThisType.isNull())
2279     RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2280   else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2281     RD = MD->getParent();
2282   if (!RD || !RD->hasAnyDependentBases())
2283     return nullptr;
2284 
2285   // Diagnose this as unqualified lookup into a dependent base class.  If 'this'
2286   // is available, suggest inserting 'this->' as a fixit.
2287   SourceLocation Loc = NameInfo.getLoc();
2288   auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2289   DB << NameInfo.getName() << RD;
2290 
2291   if (!ThisType.isNull()) {
2292     DB << FixItHint::CreateInsertion(Loc, "this->");
2293     return CXXDependentScopeMemberExpr::Create(
2294         Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2295         /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2296         /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
2297   }
2298 
2299   // Synthesize a fake NNS that points to the derived class.  This will
2300   // perform name lookup during template instantiation.
2301   CXXScopeSpec SS;
2302   auto *NNS =
2303       NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2304   SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2305   return DependentScopeDeclRefExpr::Create(
2306       Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2307       TemplateArgs);
2308 }
2309 
2310 ExprResult
2311 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2312                         SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2313                         bool HasTrailingLParen, bool IsAddressOfOperand,
2314                         CorrectionCandidateCallback *CCC,
2315                         bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2316   assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2317          "cannot be direct & operand and have a trailing lparen");
2318   if (SS.isInvalid())
2319     return ExprError();
2320 
2321   TemplateArgumentListInfo TemplateArgsBuffer;
2322 
2323   // Decompose the UnqualifiedId into the following data.
2324   DeclarationNameInfo NameInfo;
2325   const TemplateArgumentListInfo *TemplateArgs;
2326   DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2327 
2328   DeclarationName Name = NameInfo.getName();
2329   IdentifierInfo *II = Name.getAsIdentifierInfo();
2330   SourceLocation NameLoc = NameInfo.getLoc();
2331 
2332   if (II && II->isEditorPlaceholder()) {
2333     // FIXME: When typed placeholders are supported we can create a typed
2334     // placeholder expression node.
2335     return ExprError();
2336   }
2337 
2338   // C++ [temp.dep.expr]p3:
2339   //   An id-expression is type-dependent if it contains:
2340   //     -- an identifier that was declared with a dependent type,
2341   //        (note: handled after lookup)
2342   //     -- a template-id that is dependent,
2343   //        (note: handled in BuildTemplateIdExpr)
2344   //     -- a conversion-function-id that specifies a dependent type,
2345   //     -- a nested-name-specifier that contains a class-name that
2346   //        names a dependent type.
2347   // Determine whether this is a member of an unknown specialization;
2348   // we need to handle these differently.
2349   bool DependentID = false;
2350   if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2351       Name.getCXXNameType()->isDependentType()) {
2352     DependentID = true;
2353   } else if (SS.isSet()) {
2354     if (DeclContext *DC = computeDeclContext(SS, false)) {
2355       if (RequireCompleteDeclContext(SS, DC))
2356         return ExprError();
2357     } else {
2358       DependentID = true;
2359     }
2360   }
2361 
2362   if (DependentID)
2363     return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2364                                       IsAddressOfOperand, TemplateArgs);
2365 
2366   // Perform the required lookup.
2367   LookupResult R(*this, NameInfo,
2368                  (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam)
2369                      ? LookupObjCImplicitSelfParam
2370                      : LookupOrdinaryName);
2371   if (TemplateKWLoc.isValid() || TemplateArgs) {
2372     // Lookup the template name again to correctly establish the context in
2373     // which it was found. This is really unfortunate as we already did the
2374     // lookup to determine that it was a template name in the first place. If
2375     // this becomes a performance hit, we can work harder to preserve those
2376     // results until we get here but it's likely not worth it.
2377     bool MemberOfUnknownSpecialization;
2378     AssumedTemplateKind AssumedTemplate;
2379     if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2380                            MemberOfUnknownSpecialization, TemplateKWLoc,
2381                            &AssumedTemplate))
2382       return ExprError();
2383 
2384     if (MemberOfUnknownSpecialization ||
2385         (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2386       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2387                                         IsAddressOfOperand, TemplateArgs);
2388   } else {
2389     bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2390     LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2391 
2392     // If the result might be in a dependent base class, this is a dependent
2393     // id-expression.
2394     if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2395       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2396                                         IsAddressOfOperand, TemplateArgs);
2397 
2398     // If this reference is in an Objective-C method, then we need to do
2399     // some special Objective-C lookup, too.
2400     if (IvarLookupFollowUp) {
2401       ExprResult E(LookupInObjCMethod(R, S, II, true));
2402       if (E.isInvalid())
2403         return ExprError();
2404 
2405       if (Expr *Ex = E.getAs<Expr>())
2406         return Ex;
2407     }
2408   }
2409 
2410   if (R.isAmbiguous())
2411     return ExprError();
2412 
2413   // This could be an implicitly declared function reference (legal in C90,
2414   // extension in C99, forbidden in C++).
2415   if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2416     NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2417     if (D) R.addDecl(D);
2418   }
2419 
2420   // Determine whether this name might be a candidate for
2421   // argument-dependent lookup.
2422   bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2423 
2424   if (R.empty() && !ADL) {
2425     if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2426       if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2427                                                    TemplateKWLoc, TemplateArgs))
2428         return E;
2429     }
2430 
2431     // Don't diagnose an empty lookup for inline assembly.
2432     if (IsInlineAsmIdentifier)
2433       return ExprError();
2434 
2435     // If this name wasn't predeclared and if this is not a function
2436     // call, diagnose the problem.
2437     TypoExpr *TE = nullptr;
2438     DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep()
2439                                                        : nullptr);
2440     DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;
2441     assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2442            "Typo correction callback misconfigured");
2443     if (CCC) {
2444       // Make sure the callback knows what the typo being diagnosed is.
2445       CCC->setTypoName(II);
2446       if (SS.isValid())
2447         CCC->setTypoNNS(SS.getScopeRep());
2448     }
2449     // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2450     // a template name, but we happen to have always already looked up the name
2451     // before we get here if it must be a template name.
2452     if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr,
2453                             None, &TE)) {
2454       if (TE && KeywordReplacement) {
2455         auto &State = getTypoExprState(TE);
2456         auto BestTC = State.Consumer->getNextCorrection();
2457         if (BestTC.isKeyword()) {
2458           auto *II = BestTC.getCorrectionAsIdentifierInfo();
2459           if (State.DiagHandler)
2460             State.DiagHandler(BestTC);
2461           KeywordReplacement->startToken();
2462           KeywordReplacement->setKind(II->getTokenID());
2463           KeywordReplacement->setIdentifierInfo(II);
2464           KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2465           // Clean up the state associated with the TypoExpr, since it has
2466           // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2467           clearDelayedTypo(TE);
2468           // Signal that a correction to a keyword was performed by returning a
2469           // valid-but-null ExprResult.
2470           return (Expr*)nullptr;
2471         }
2472         State.Consumer->resetCorrectionStream();
2473       }
2474       return TE ? TE : ExprError();
2475     }
2476 
2477     assert(!R.empty() &&
2478            "DiagnoseEmptyLookup returned false but added no results");
2479 
2480     // If we found an Objective-C instance variable, let
2481     // LookupInObjCMethod build the appropriate expression to
2482     // reference the ivar.
2483     if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2484       R.clear();
2485       ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2486       // In a hopelessly buggy code, Objective-C instance variable
2487       // lookup fails and no expression will be built to reference it.
2488       if (!E.isInvalid() && !E.get())
2489         return ExprError();
2490       return E;
2491     }
2492   }
2493 
2494   // This is guaranteed from this point on.
2495   assert(!R.empty() || ADL);
2496 
2497   // Check whether this might be a C++ implicit instance member access.
2498   // C++ [class.mfct.non-static]p3:
2499   //   When an id-expression that is not part of a class member access
2500   //   syntax and not used to form a pointer to member is used in the
2501   //   body of a non-static member function of class X, if name lookup
2502   //   resolves the name in the id-expression to a non-static non-type
2503   //   member of some class C, the id-expression is transformed into a
2504   //   class member access expression using (*this) as the
2505   //   postfix-expression to the left of the . operator.
2506   //
2507   // But we don't actually need to do this for '&' operands if R
2508   // resolved to a function or overloaded function set, because the
2509   // expression is ill-formed if it actually works out to be a
2510   // non-static member function:
2511   //
2512   // C++ [expr.ref]p4:
2513   //   Otherwise, if E1.E2 refers to a non-static member function. . .
2514   //   [t]he expression can be used only as the left-hand operand of a
2515   //   member function call.
2516   //
2517   // There are other safeguards against such uses, but it's important
2518   // to get this right here so that we don't end up making a
2519   // spuriously dependent expression if we're inside a dependent
2520   // instance method.
2521   if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2522     bool MightBeImplicitMember;
2523     if (!IsAddressOfOperand)
2524       MightBeImplicitMember = true;
2525     else if (!SS.isEmpty())
2526       MightBeImplicitMember = false;
2527     else if (R.isOverloadedResult())
2528       MightBeImplicitMember = false;
2529     else if (R.isUnresolvableResult())
2530       MightBeImplicitMember = true;
2531     else
2532       MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2533                               isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2534                               isa<MSPropertyDecl>(R.getFoundDecl());
2535 
2536     if (MightBeImplicitMember)
2537       return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2538                                              R, TemplateArgs, S);
2539   }
2540 
2541   if (TemplateArgs || TemplateKWLoc.isValid()) {
2542 
2543     // In C++1y, if this is a variable template id, then check it
2544     // in BuildTemplateIdExpr().
2545     // The single lookup result must be a variable template declaration.
2546     if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId &&
2547         Id.TemplateId->Kind == TNK_Var_template) {
2548       assert(R.getAsSingle<VarTemplateDecl>() &&
2549              "There should only be one declaration found.");
2550     }
2551 
2552     return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2553   }
2554 
2555   return BuildDeclarationNameExpr(SS, R, ADL);
2556 }
2557 
2558 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2559 /// declaration name, generally during template instantiation.
2560 /// There's a large number of things which don't need to be done along
2561 /// this path.
2562 ExprResult Sema::BuildQualifiedDeclarationNameExpr(
2563     CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2564     bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2565   DeclContext *DC = computeDeclContext(SS, false);
2566   if (!DC)
2567     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2568                                      NameInfo, /*TemplateArgs=*/nullptr);
2569 
2570   if (RequireCompleteDeclContext(SS, DC))
2571     return ExprError();
2572 
2573   LookupResult R(*this, NameInfo, LookupOrdinaryName);
2574   LookupQualifiedName(R, DC);
2575 
2576   if (R.isAmbiguous())
2577     return ExprError();
2578 
2579   if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2580     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2581                                      NameInfo, /*TemplateArgs=*/nullptr);
2582 
2583   if (R.empty()) {
2584     // Don't diagnose problems with invalid record decl, the secondary no_member
2585     // diagnostic during template instantiation is likely bogus, e.g. if a class
2586     // is invalid because it's derived from an invalid base class, then missing
2587     // members were likely supposed to be inherited.
2588     if (const auto *CD = dyn_cast<CXXRecordDecl>(DC))
2589       if (CD->isInvalidDecl())
2590         return ExprError();
2591     Diag(NameInfo.getLoc(), diag::err_no_member)
2592       << NameInfo.getName() << DC << SS.getRange();
2593     return ExprError();
2594   }
2595 
2596   if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2597     // Diagnose a missing typename if this resolved unambiguously to a type in
2598     // a dependent context.  If we can recover with a type, downgrade this to
2599     // a warning in Microsoft compatibility mode.
2600     unsigned DiagID = diag::err_typename_missing;
2601     if (RecoveryTSI && getLangOpts().MSVCCompat)
2602       DiagID = diag::ext_typename_missing;
2603     SourceLocation Loc = SS.getBeginLoc();
2604     auto D = Diag(Loc, DiagID);
2605     D << SS.getScopeRep() << NameInfo.getName().getAsString()
2606       << SourceRange(Loc, NameInfo.getEndLoc());
2607 
2608     // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2609     // context.
2610     if (!RecoveryTSI)
2611       return ExprError();
2612 
2613     // Only issue the fixit if we're prepared to recover.
2614     D << FixItHint::CreateInsertion(Loc, "typename ");
2615 
2616     // Recover by pretending this was an elaborated type.
2617     QualType Ty = Context.getTypeDeclType(TD);
2618     TypeLocBuilder TLB;
2619     TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2620 
2621     QualType ET = getElaboratedType(ETK_None, SS, Ty);
2622     ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2623     QTL.setElaboratedKeywordLoc(SourceLocation());
2624     QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2625 
2626     *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2627 
2628     return ExprEmpty();
2629   }
2630 
2631   // Defend against this resolving to an implicit member access. We usually
2632   // won't get here if this might be a legitimate a class member (we end up in
2633   // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2634   // a pointer-to-member or in an unevaluated context in C++11.
2635   if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2636     return BuildPossibleImplicitMemberExpr(SS,
2637                                            /*TemplateKWLoc=*/SourceLocation(),
2638                                            R, /*TemplateArgs=*/nullptr, S);
2639 
2640   return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2641 }
2642 
2643 /// The parser has read a name in, and Sema has detected that we're currently
2644 /// inside an ObjC method. Perform some additional checks and determine if we
2645 /// should form a reference to an ivar.
2646 ///
2647 /// Ideally, most of this would be done by lookup, but there's
2648 /// actually quite a lot of extra work involved.
2649 DeclResult Sema::LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S,
2650                                         IdentifierInfo *II) {
2651   SourceLocation Loc = Lookup.getNameLoc();
2652   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2653 
2654   // Check for error condition which is already reported.
2655   if (!CurMethod)
2656     return DeclResult(true);
2657 
2658   // There are two cases to handle here.  1) scoped lookup could have failed,
2659   // in which case we should look for an ivar.  2) scoped lookup could have
2660   // found a decl, but that decl is outside the current instance method (i.e.
2661   // a global variable).  In these two cases, we do a lookup for an ivar with
2662   // this name, if the lookup sucedes, we replace it our current decl.
2663 
2664   // If we're in a class method, we don't normally want to look for
2665   // ivars.  But if we don't find anything else, and there's an
2666   // ivar, that's an error.
2667   bool IsClassMethod = CurMethod->isClassMethod();
2668 
2669   bool LookForIvars;
2670   if (Lookup.empty())
2671     LookForIvars = true;
2672   else if (IsClassMethod)
2673     LookForIvars = false;
2674   else
2675     LookForIvars = (Lookup.isSingleResult() &&
2676                     Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2677   ObjCInterfaceDecl *IFace = nullptr;
2678   if (LookForIvars) {
2679     IFace = CurMethod->getClassInterface();
2680     ObjCInterfaceDecl *ClassDeclared;
2681     ObjCIvarDecl *IV = nullptr;
2682     if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2683       // Diagnose using an ivar in a class method.
2684       if (IsClassMethod) {
2685         Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
2686         return DeclResult(true);
2687       }
2688 
2689       // Diagnose the use of an ivar outside of the declaring class.
2690       if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2691           !declaresSameEntity(ClassDeclared, IFace) &&
2692           !getLangOpts().DebuggerSupport)
2693         Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
2694 
2695       // Success.
2696       return IV;
2697     }
2698   } else if (CurMethod->isInstanceMethod()) {
2699     // We should warn if a local variable hides an ivar.
2700     if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2701       ObjCInterfaceDecl *ClassDeclared;
2702       if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2703         if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2704             declaresSameEntity(IFace, ClassDeclared))
2705           Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2706       }
2707     }
2708   } else if (Lookup.isSingleResult() &&
2709              Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2710     // If accessing a stand-alone ivar in a class method, this is an error.
2711     if (const ObjCIvarDecl *IV =
2712             dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) {
2713       Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
2714       return DeclResult(true);
2715     }
2716   }
2717 
2718   // Didn't encounter an error, didn't find an ivar.
2719   return DeclResult(false);
2720 }
2721 
2722 ExprResult Sema::BuildIvarRefExpr(Scope *S, SourceLocation Loc,
2723                                   ObjCIvarDecl *IV) {
2724   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2725   assert(CurMethod && CurMethod->isInstanceMethod() &&
2726          "should not reference ivar from this context");
2727 
2728   ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
2729   assert(IFace && "should not reference ivar from this context");
2730 
2731   // If we're referencing an invalid decl, just return this as a silent
2732   // error node.  The error diagnostic was already emitted on the decl.
2733   if (IV->isInvalidDecl())
2734     return ExprError();
2735 
2736   // Check if referencing a field with __attribute__((deprecated)).
2737   if (DiagnoseUseOfDecl(IV, Loc))
2738     return ExprError();
2739 
2740   // FIXME: This should use a new expr for a direct reference, don't
2741   // turn this into Self->ivar, just return a BareIVarExpr or something.
2742   IdentifierInfo &II = Context.Idents.get("self");
2743   UnqualifiedId SelfName;
2744   SelfName.setIdentifier(&II, SourceLocation());
2745   SelfName.setKind(UnqualifiedIdKind::IK_ImplicitSelfParam);
2746   CXXScopeSpec SelfScopeSpec;
2747   SourceLocation TemplateKWLoc;
2748   ExprResult SelfExpr =
2749       ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName,
2750                         /*HasTrailingLParen=*/false,
2751                         /*IsAddressOfOperand=*/false);
2752   if (SelfExpr.isInvalid())
2753     return ExprError();
2754 
2755   SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2756   if (SelfExpr.isInvalid())
2757     return ExprError();
2758 
2759   MarkAnyDeclReferenced(Loc, IV, true);
2760 
2761   ObjCMethodFamily MF = CurMethod->getMethodFamily();
2762   if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2763       !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2764     Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2765 
2766   ObjCIvarRefExpr *Result = new (Context)
2767       ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2768                       IV->getLocation(), SelfExpr.get(), true, true);
2769 
2770   if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2771     if (!isUnevaluatedContext() &&
2772         !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2773       getCurFunction()->recordUseOfWeak(Result);
2774   }
2775   if (getLangOpts().ObjCAutoRefCount)
2776     if (const BlockDecl *BD = CurContext->getInnermostBlockDecl())
2777       ImplicitlyRetainedSelfLocs.push_back({Loc, BD});
2778 
2779   return Result;
2780 }
2781 
2782 /// The parser has read a name in, and Sema has detected that we're currently
2783 /// inside an ObjC method. Perform some additional checks and determine if we
2784 /// should form a reference to an ivar. If so, build an expression referencing
2785 /// that ivar.
2786 ExprResult
2787 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2788                          IdentifierInfo *II, bool AllowBuiltinCreation) {
2789   // FIXME: Integrate this lookup step into LookupParsedName.
2790   DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II);
2791   if (Ivar.isInvalid())
2792     return ExprError();
2793   if (Ivar.isUsable())
2794     return BuildIvarRefExpr(S, Lookup.getNameLoc(),
2795                             cast<ObjCIvarDecl>(Ivar.get()));
2796 
2797   if (Lookup.empty() && II && AllowBuiltinCreation)
2798     LookupBuiltin(Lookup);
2799 
2800   // Sentinel value saying that we didn't do anything special.
2801   return ExprResult(false);
2802 }
2803 
2804 /// Cast a base object to a member's actual type.
2805 ///
2806 /// Logically this happens in three phases:
2807 ///
2808 /// * First we cast from the base type to the naming class.
2809 ///   The naming class is the class into which we were looking
2810 ///   when we found the member;  it's the qualifier type if a
2811 ///   qualifier was provided, and otherwise it's the base type.
2812 ///
2813 /// * Next we cast from the naming class to the declaring class.
2814 ///   If the member we found was brought into a class's scope by
2815 ///   a using declaration, this is that class;  otherwise it's
2816 ///   the class declaring the member.
2817 ///
2818 /// * Finally we cast from the declaring class to the "true"
2819 ///   declaring class of the member.  This conversion does not
2820 ///   obey access control.
2821 ExprResult
2822 Sema::PerformObjectMemberConversion(Expr *From,
2823                                     NestedNameSpecifier *Qualifier,
2824                                     NamedDecl *FoundDecl,
2825                                     NamedDecl *Member) {
2826   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2827   if (!RD)
2828     return From;
2829 
2830   QualType DestRecordType;
2831   QualType DestType;
2832   QualType FromRecordType;
2833   QualType FromType = From->getType();
2834   bool PointerConversions = false;
2835   if (isa<FieldDecl>(Member)) {
2836     DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2837     auto FromPtrType = FromType->getAs<PointerType>();
2838     DestRecordType = Context.getAddrSpaceQualType(
2839         DestRecordType, FromPtrType
2840                             ? FromType->getPointeeType().getAddressSpace()
2841                             : FromType.getAddressSpace());
2842 
2843     if (FromPtrType) {
2844       DestType = Context.getPointerType(DestRecordType);
2845       FromRecordType = FromPtrType->getPointeeType();
2846       PointerConversions = true;
2847     } else {
2848       DestType = DestRecordType;
2849       FromRecordType = FromType;
2850     }
2851   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2852     if (Method->isStatic())
2853       return From;
2854 
2855     DestType = Method->getThisType();
2856     DestRecordType = DestType->getPointeeType();
2857 
2858     if (FromType->getAs<PointerType>()) {
2859       FromRecordType = FromType->getPointeeType();
2860       PointerConversions = true;
2861     } else {
2862       FromRecordType = FromType;
2863       DestType = DestRecordType;
2864     }
2865 
2866     LangAS FromAS = FromRecordType.getAddressSpace();
2867     LangAS DestAS = DestRecordType.getAddressSpace();
2868     if (FromAS != DestAS) {
2869       QualType FromRecordTypeWithoutAS =
2870           Context.removeAddrSpaceQualType(FromRecordType);
2871       QualType FromTypeWithDestAS =
2872           Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS);
2873       if (PointerConversions)
2874         FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS);
2875       From = ImpCastExprToType(From, FromTypeWithDestAS,
2876                                CK_AddressSpaceConversion, From->getValueKind())
2877                  .get();
2878     }
2879   } else {
2880     // No conversion necessary.
2881     return From;
2882   }
2883 
2884   if (DestType->isDependentType() || FromType->isDependentType())
2885     return From;
2886 
2887   // If the unqualified types are the same, no conversion is necessary.
2888   if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2889     return From;
2890 
2891   SourceRange FromRange = From->getSourceRange();
2892   SourceLocation FromLoc = FromRange.getBegin();
2893 
2894   ExprValueKind VK = From->getValueKind();
2895 
2896   // C++ [class.member.lookup]p8:
2897   //   [...] Ambiguities can often be resolved by qualifying a name with its
2898   //   class name.
2899   //
2900   // If the member was a qualified name and the qualified referred to a
2901   // specific base subobject type, we'll cast to that intermediate type
2902   // first and then to the object in which the member is declared. That allows
2903   // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2904   //
2905   //   class Base { public: int x; };
2906   //   class Derived1 : public Base { };
2907   //   class Derived2 : public Base { };
2908   //   class VeryDerived : public Derived1, public Derived2 { void f(); };
2909   //
2910   //   void VeryDerived::f() {
2911   //     x = 17; // error: ambiguous base subobjects
2912   //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
2913   //   }
2914   if (Qualifier && Qualifier->getAsType()) {
2915     QualType QType = QualType(Qualifier->getAsType(), 0);
2916     assert(QType->isRecordType() && "lookup done with non-record type");
2917 
2918     QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2919 
2920     // In C++98, the qualifier type doesn't actually have to be a base
2921     // type of the object type, in which case we just ignore it.
2922     // Otherwise build the appropriate casts.
2923     if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
2924       CXXCastPath BasePath;
2925       if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2926                                        FromLoc, FromRange, &BasePath))
2927         return ExprError();
2928 
2929       if (PointerConversions)
2930         QType = Context.getPointerType(QType);
2931       From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2932                                VK, &BasePath).get();
2933 
2934       FromType = QType;
2935       FromRecordType = QRecordType;
2936 
2937       // If the qualifier type was the same as the destination type,
2938       // we're done.
2939       if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2940         return From;
2941     }
2942   }
2943 
2944   bool IgnoreAccess = false;
2945 
2946   // If we actually found the member through a using declaration, cast
2947   // down to the using declaration's type.
2948   //
2949   // Pointer equality is fine here because only one declaration of a
2950   // class ever has member declarations.
2951   if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2952     assert(isa<UsingShadowDecl>(FoundDecl));
2953     QualType URecordType = Context.getTypeDeclType(
2954                            cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2955 
2956     // We only need to do this if the naming-class to declaring-class
2957     // conversion is non-trivial.
2958     if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2959       assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType));
2960       CXXCastPath BasePath;
2961       if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2962                                        FromLoc, FromRange, &BasePath))
2963         return ExprError();
2964 
2965       QualType UType = URecordType;
2966       if (PointerConversions)
2967         UType = Context.getPointerType(UType);
2968       From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2969                                VK, &BasePath).get();
2970       FromType = UType;
2971       FromRecordType = URecordType;
2972     }
2973 
2974     // We don't do access control for the conversion from the
2975     // declaring class to the true declaring class.
2976     IgnoreAccess = true;
2977   }
2978 
2979   CXXCastPath BasePath;
2980   if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2981                                    FromLoc, FromRange, &BasePath,
2982                                    IgnoreAccess))
2983     return ExprError();
2984 
2985   return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2986                            VK, &BasePath);
2987 }
2988 
2989 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2990                                       const LookupResult &R,
2991                                       bool HasTrailingLParen) {
2992   // Only when used directly as the postfix-expression of a call.
2993   if (!HasTrailingLParen)
2994     return false;
2995 
2996   // Never if a scope specifier was provided.
2997   if (SS.isSet())
2998     return false;
2999 
3000   // Only in C++ or ObjC++.
3001   if (!getLangOpts().CPlusPlus)
3002     return false;
3003 
3004   // Turn off ADL when we find certain kinds of declarations during
3005   // normal lookup:
3006   for (NamedDecl *D : R) {
3007     // C++0x [basic.lookup.argdep]p3:
3008     //     -- a declaration of a class member
3009     // Since using decls preserve this property, we check this on the
3010     // original decl.
3011     if (D->isCXXClassMember())
3012       return false;
3013 
3014     // C++0x [basic.lookup.argdep]p3:
3015     //     -- a block-scope function declaration that is not a
3016     //        using-declaration
3017     // NOTE: we also trigger this for function templates (in fact, we
3018     // don't check the decl type at all, since all other decl types
3019     // turn off ADL anyway).
3020     if (isa<UsingShadowDecl>(D))
3021       D = cast<UsingShadowDecl>(D)->getTargetDecl();
3022     else if (D->getLexicalDeclContext()->isFunctionOrMethod())
3023       return false;
3024 
3025     // C++0x [basic.lookup.argdep]p3:
3026     //     -- a declaration that is neither a function or a function
3027     //        template
3028     // And also for builtin functions.
3029     if (isa<FunctionDecl>(D)) {
3030       FunctionDecl *FDecl = cast<FunctionDecl>(D);
3031 
3032       // But also builtin functions.
3033       if (FDecl->getBuiltinID() && FDecl->isImplicit())
3034         return false;
3035     } else if (!isa<FunctionTemplateDecl>(D))
3036       return false;
3037   }
3038 
3039   return true;
3040 }
3041 
3042 
3043 /// Diagnoses obvious problems with the use of the given declaration
3044 /// as an expression.  This is only actually called for lookups that
3045 /// were not overloaded, and it doesn't promise that the declaration
3046 /// will in fact be used.
3047 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
3048   if (D->isInvalidDecl())
3049     return true;
3050 
3051   if (isa<TypedefNameDecl>(D)) {
3052     S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
3053     return true;
3054   }
3055 
3056   if (isa<ObjCInterfaceDecl>(D)) {
3057     S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
3058     return true;
3059   }
3060 
3061   if (isa<NamespaceDecl>(D)) {
3062     S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
3063     return true;
3064   }
3065 
3066   return false;
3067 }
3068 
3069 // Certain multiversion types should be treated as overloaded even when there is
3070 // only one result.
3071 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) {
3072   assert(R.isSingleResult() && "Expected only a single result");
3073   const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
3074   return FD &&
3075          (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
3076 }
3077 
3078 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
3079                                           LookupResult &R, bool NeedsADL,
3080                                           bool AcceptInvalidDecl) {
3081   // If this is a single, fully-resolved result and we don't need ADL,
3082   // just build an ordinary singleton decl ref.
3083   if (!NeedsADL && R.isSingleResult() &&
3084       !R.getAsSingle<FunctionTemplateDecl>() &&
3085       !ShouldLookupResultBeMultiVersionOverload(R))
3086     return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
3087                                     R.getRepresentativeDecl(), nullptr,
3088                                     AcceptInvalidDecl);
3089 
3090   // We only need to check the declaration if there's exactly one
3091   // result, because in the overloaded case the results can only be
3092   // functions and function templates.
3093   if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) &&
3094       CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
3095     return ExprError();
3096 
3097   // Otherwise, just build an unresolved lookup expression.  Suppress
3098   // any lookup-related diagnostics; we'll hash these out later, when
3099   // we've picked a target.
3100   R.suppressDiagnostics();
3101 
3102   UnresolvedLookupExpr *ULE
3103     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
3104                                    SS.getWithLocInContext(Context),
3105                                    R.getLookupNameInfo(),
3106                                    NeedsADL, R.isOverloadedResult(),
3107                                    R.begin(), R.end());
3108 
3109   return ULE;
3110 }
3111 
3112 static void
3113 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
3114                                    ValueDecl *var, DeclContext *DC);
3115 
3116 /// Complete semantic analysis for a reference to the given declaration.
3117 ExprResult Sema::BuildDeclarationNameExpr(
3118     const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
3119     NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
3120     bool AcceptInvalidDecl) {
3121   assert(D && "Cannot refer to a NULL declaration");
3122   assert(!isa<FunctionTemplateDecl>(D) &&
3123          "Cannot refer unambiguously to a function template");
3124 
3125   SourceLocation Loc = NameInfo.getLoc();
3126   if (CheckDeclInExpr(*this, Loc, D))
3127     return ExprError();
3128 
3129   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
3130     // Specifically diagnose references to class templates that are missing
3131     // a template argument list.
3132     diagnoseMissingTemplateArguments(TemplateName(Template), Loc);
3133     return ExprError();
3134   }
3135 
3136   // Make sure that we're referring to a value.
3137   ValueDecl *VD = dyn_cast<ValueDecl>(D);
3138   if (!VD) {
3139     Diag(Loc, diag::err_ref_non_value)
3140       << D << SS.getRange();
3141     Diag(D->getLocation(), diag::note_declared_at);
3142     return ExprError();
3143   }
3144 
3145   // Check whether this declaration can be used. Note that we suppress
3146   // this check when we're going to perform argument-dependent lookup
3147   // on this function name, because this might not be the function
3148   // that overload resolution actually selects.
3149   if (DiagnoseUseOfDecl(VD, Loc))
3150     return ExprError();
3151 
3152   // Only create DeclRefExpr's for valid Decl's.
3153   if (VD->isInvalidDecl() && !AcceptInvalidDecl)
3154     return ExprError();
3155 
3156   // Handle members of anonymous structs and unions.  If we got here,
3157   // and the reference is to a class member indirect field, then this
3158   // must be the subject of a pointer-to-member expression.
3159   if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
3160     if (!indirectField->isCXXClassMember())
3161       return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
3162                                                       indirectField);
3163 
3164   {
3165     QualType type = VD->getType();
3166     if (type.isNull())
3167       return ExprError();
3168     ExprValueKind valueKind = VK_RValue;
3169 
3170     // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of
3171     // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value,
3172     // is expanded by some outer '...' in the context of the use.
3173     type = type.getNonPackExpansionType();
3174 
3175     switch (D->getKind()) {
3176     // Ignore all the non-ValueDecl kinds.
3177 #define ABSTRACT_DECL(kind)
3178 #define VALUE(type, base)
3179 #define DECL(type, base) \
3180     case Decl::type:
3181 #include "clang/AST/DeclNodes.inc"
3182       llvm_unreachable("invalid value decl kind");
3183 
3184     // These shouldn't make it here.
3185     case Decl::ObjCAtDefsField:
3186       llvm_unreachable("forming non-member reference to ivar?");
3187 
3188     // Enum constants are always r-values and never references.
3189     // Unresolved using declarations are dependent.
3190     case Decl::EnumConstant:
3191     case Decl::UnresolvedUsingValue:
3192     case Decl::OMPDeclareReduction:
3193     case Decl::OMPDeclareMapper:
3194       valueKind = VK_RValue;
3195       break;
3196 
3197     // Fields and indirect fields that got here must be for
3198     // pointer-to-member expressions; we just call them l-values for
3199     // internal consistency, because this subexpression doesn't really
3200     // exist in the high-level semantics.
3201     case Decl::Field:
3202     case Decl::IndirectField:
3203     case Decl::ObjCIvar:
3204       assert(getLangOpts().CPlusPlus &&
3205              "building reference to field in C?");
3206 
3207       // These can't have reference type in well-formed programs, but
3208       // for internal consistency we do this anyway.
3209       type = type.getNonReferenceType();
3210       valueKind = VK_LValue;
3211       break;
3212 
3213     // Non-type template parameters are either l-values or r-values
3214     // depending on the type.
3215     case Decl::NonTypeTemplateParm: {
3216       if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
3217         type = reftype->getPointeeType();
3218         valueKind = VK_LValue; // even if the parameter is an r-value reference
3219         break;
3220       }
3221 
3222       // For non-references, we need to strip qualifiers just in case
3223       // the template parameter was declared as 'const int' or whatever.
3224       valueKind = VK_RValue;
3225       type = type.getUnqualifiedType();
3226       break;
3227     }
3228 
3229     case Decl::Var:
3230     case Decl::VarTemplateSpecialization:
3231     case Decl::VarTemplatePartialSpecialization:
3232     case Decl::Decomposition:
3233     case Decl::OMPCapturedExpr:
3234       // In C, "extern void blah;" is valid and is an r-value.
3235       if (!getLangOpts().CPlusPlus &&
3236           !type.hasQualifiers() &&
3237           type->isVoidType()) {
3238         valueKind = VK_RValue;
3239         break;
3240       }
3241       LLVM_FALLTHROUGH;
3242 
3243     case Decl::ImplicitParam:
3244     case Decl::ParmVar: {
3245       // These are always l-values.
3246       valueKind = VK_LValue;
3247       type = type.getNonReferenceType();
3248 
3249       // FIXME: Does the addition of const really only apply in
3250       // potentially-evaluated contexts? Since the variable isn't actually
3251       // captured in an unevaluated context, it seems that the answer is no.
3252       if (!isUnevaluatedContext()) {
3253         QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
3254         if (!CapturedType.isNull())
3255           type = CapturedType;
3256       }
3257 
3258       break;
3259     }
3260 
3261     case Decl::Binding: {
3262       // These are always lvalues.
3263       valueKind = VK_LValue;
3264       type = type.getNonReferenceType();
3265       // FIXME: Support lambda-capture of BindingDecls, once CWG actually
3266       // decides how that's supposed to work.
3267       auto *BD = cast<BindingDecl>(VD);
3268       if (BD->getDeclContext() != CurContext) {
3269         auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl());
3270         if (DD && DD->hasLocalStorage())
3271           diagnoseUncapturableValueReference(*this, Loc, BD, CurContext);
3272       }
3273       break;
3274     }
3275 
3276     case Decl::Function: {
3277       if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
3278         if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
3279           type = Context.BuiltinFnTy;
3280           valueKind = VK_RValue;
3281           break;
3282         }
3283       }
3284 
3285       const FunctionType *fty = type->castAs<FunctionType>();
3286 
3287       // If we're referring to a function with an __unknown_anytype
3288       // result type, make the entire expression __unknown_anytype.
3289       if (fty->getReturnType() == Context.UnknownAnyTy) {
3290         type = Context.UnknownAnyTy;
3291         valueKind = VK_RValue;
3292         break;
3293       }
3294 
3295       // Functions are l-values in C++.
3296       if (getLangOpts().CPlusPlus) {
3297         valueKind = VK_LValue;
3298         break;
3299       }
3300 
3301       // C99 DR 316 says that, if a function type comes from a
3302       // function definition (without a prototype), that type is only
3303       // used for checking compatibility. Therefore, when referencing
3304       // the function, we pretend that we don't have the full function
3305       // type.
3306       if (!cast<FunctionDecl>(VD)->hasPrototype() &&
3307           isa<FunctionProtoType>(fty))
3308         type = Context.getFunctionNoProtoType(fty->getReturnType(),
3309                                               fty->getExtInfo());
3310 
3311       // Functions are r-values in C.
3312       valueKind = VK_RValue;
3313       break;
3314     }
3315 
3316     case Decl::CXXDeductionGuide:
3317       llvm_unreachable("building reference to deduction guide");
3318 
3319     case Decl::MSProperty:
3320     case Decl::MSGuid:
3321       // FIXME: Should MSGuidDecl be subject to capture in OpenMP,
3322       // or duplicated between host and device?
3323       valueKind = VK_LValue;
3324       break;
3325 
3326     case Decl::CXXMethod:
3327       // If we're referring to a method with an __unknown_anytype
3328       // result type, make the entire expression __unknown_anytype.
3329       // This should only be possible with a type written directly.
3330       if (const FunctionProtoType *proto
3331             = dyn_cast<FunctionProtoType>(VD->getType()))
3332         if (proto->getReturnType() == Context.UnknownAnyTy) {
3333           type = Context.UnknownAnyTy;
3334           valueKind = VK_RValue;
3335           break;
3336         }
3337 
3338       // C++ methods are l-values if static, r-values if non-static.
3339       if (cast<CXXMethodDecl>(VD)->isStatic()) {
3340         valueKind = VK_LValue;
3341         break;
3342       }
3343       LLVM_FALLTHROUGH;
3344 
3345     case Decl::CXXConversion:
3346     case Decl::CXXDestructor:
3347     case Decl::CXXConstructor:
3348       valueKind = VK_RValue;
3349       break;
3350     }
3351 
3352     return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3353                             /*FIXME: TemplateKWLoc*/ SourceLocation(),
3354                             TemplateArgs);
3355   }
3356 }
3357 
3358 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3359                                     SmallString<32> &Target) {
3360   Target.resize(CharByteWidth * (Source.size() + 1));
3361   char *ResultPtr = &Target[0];
3362   const llvm::UTF8 *ErrorPtr;
3363   bool success =
3364       llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3365   (void)success;
3366   assert(success);
3367   Target.resize(ResultPtr - &Target[0]);
3368 }
3369 
3370 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3371                                      PredefinedExpr::IdentKind IK) {
3372   // Pick the current block, lambda, captured statement or function.
3373   Decl *currentDecl = nullptr;
3374   if (const BlockScopeInfo *BSI = getCurBlock())
3375     currentDecl = BSI->TheDecl;
3376   else if (const LambdaScopeInfo *LSI = getCurLambda())
3377     currentDecl = LSI->CallOperator;
3378   else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3379     currentDecl = CSI->TheCapturedDecl;
3380   else
3381     currentDecl = getCurFunctionOrMethodDecl();
3382 
3383   if (!currentDecl) {
3384     Diag(Loc, diag::ext_predef_outside_function);
3385     currentDecl = Context.getTranslationUnitDecl();
3386   }
3387 
3388   QualType ResTy;
3389   StringLiteral *SL = nullptr;
3390   if (cast<DeclContext>(currentDecl)->isDependentContext())
3391     ResTy = Context.DependentTy;
3392   else {
3393     // Pre-defined identifiers are of type char[x], where x is the length of
3394     // the string.
3395     auto Str = PredefinedExpr::ComputeName(IK, currentDecl);
3396     unsigned Length = Str.length();
3397 
3398     llvm::APInt LengthI(32, Length + 1);
3399     if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) {
3400       ResTy =
3401           Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst());
3402       SmallString<32> RawChars;
3403       ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3404                               Str, RawChars);
3405       ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3406                                            ArrayType::Normal,
3407                                            /*IndexTypeQuals*/ 0);
3408       SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3409                                  /*Pascal*/ false, ResTy, Loc);
3410     } else {
3411       ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
3412       ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3413                                            ArrayType::Normal,
3414                                            /*IndexTypeQuals*/ 0);
3415       SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3416                                  /*Pascal*/ false, ResTy, Loc);
3417     }
3418   }
3419 
3420   return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL);
3421 }
3422 
3423 static std::pair<QualType, StringLiteral *>
3424 GetUniqueStableNameInfo(ASTContext &Context, QualType OpType,
3425                         SourceLocation OpLoc, PredefinedExpr::IdentKind K) {
3426   std::pair<QualType, StringLiteral*> Result{{}, nullptr};
3427 
3428   if (OpType->isDependentType()) {
3429       Result.first = Context.DependentTy;
3430       return Result;
3431   }
3432 
3433   std::string Str = PredefinedExpr::ComputeName(Context, K, OpType);
3434   llvm::APInt Length(32, Str.length() + 1);
3435   Result.first =
3436       Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
3437   Result.first = Context.getConstantArrayType(
3438       Result.first, Length, nullptr, ArrayType::Normal, /*IndexTypeQuals*/ 0);
3439   Result.second = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3440                                         /*Pascal*/ false, Result.first, OpLoc);
3441   return Result;
3442 }
3443 
3444 ExprResult Sema::BuildUniqueStableName(SourceLocation OpLoc,
3445                                        TypeSourceInfo *Operand) {
3446   QualType ResultTy;
3447   StringLiteral *SL;
3448   std::tie(ResultTy, SL) = GetUniqueStableNameInfo(
3449       Context, Operand->getType(), OpLoc, PredefinedExpr::UniqueStableNameType);
3450 
3451   return PredefinedExpr::Create(Context, OpLoc, ResultTy,
3452                                 PredefinedExpr::UniqueStableNameType, SL,
3453                                 Operand);
3454 }
3455 
3456 ExprResult Sema::BuildUniqueStableName(SourceLocation OpLoc,
3457                                        Expr *E) {
3458   QualType ResultTy;
3459   StringLiteral *SL;
3460   std::tie(ResultTy, SL) = GetUniqueStableNameInfo(
3461       Context, E->getType(), OpLoc, PredefinedExpr::UniqueStableNameExpr);
3462 
3463   return PredefinedExpr::Create(Context, OpLoc, ResultTy,
3464                                 PredefinedExpr::UniqueStableNameExpr, SL, E);
3465 }
3466 
3467 ExprResult Sema::ActOnUniqueStableNameExpr(SourceLocation OpLoc,
3468                                            SourceLocation L, SourceLocation R,
3469                                            ParsedType Ty) {
3470   TypeSourceInfo *TInfo = nullptr;
3471   QualType T = GetTypeFromParser(Ty, &TInfo);
3472 
3473   if (T.isNull())
3474     return ExprError();
3475   if (!TInfo)
3476     TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
3477 
3478   return BuildUniqueStableName(OpLoc, TInfo);
3479 }
3480 
3481 ExprResult Sema::ActOnUniqueStableNameExpr(SourceLocation OpLoc,
3482                                            SourceLocation L, SourceLocation R,
3483                                            Expr *E) {
3484   return BuildUniqueStableName(OpLoc, E);
3485 }
3486 
3487 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3488   PredefinedExpr::IdentKind IK;
3489 
3490   switch (Kind) {
3491   default: llvm_unreachable("Unknown simple primary expr!");
3492   case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3493   case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break;
3494   case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS]
3495   case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS]
3496   case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS]
3497   case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS]
3498   case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break;
3499   }
3500 
3501   return BuildPredefinedExpr(Loc, IK);
3502 }
3503 
3504 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3505   SmallString<16> CharBuffer;
3506   bool Invalid = false;
3507   StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3508   if (Invalid)
3509     return ExprError();
3510 
3511   CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3512                             PP, Tok.getKind());
3513   if (Literal.hadError())
3514     return ExprError();
3515 
3516   QualType Ty;
3517   if (Literal.isWide())
3518     Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3519   else if (Literal.isUTF8() && getLangOpts().Char8)
3520     Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3521   else if (Literal.isUTF16())
3522     Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3523   else if (Literal.isUTF32())
3524     Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3525   else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3526     Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
3527   else
3528     Ty = Context.CharTy;  // 'x' -> char in C++
3529 
3530   CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3531   if (Literal.isWide())
3532     Kind = CharacterLiteral::Wide;
3533   else if (Literal.isUTF16())
3534     Kind = CharacterLiteral::UTF16;
3535   else if (Literal.isUTF32())
3536     Kind = CharacterLiteral::UTF32;
3537   else if (Literal.isUTF8())
3538     Kind = CharacterLiteral::UTF8;
3539 
3540   Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3541                                              Tok.getLocation());
3542 
3543   if (Literal.getUDSuffix().empty())
3544     return Lit;
3545 
3546   // We're building a user-defined literal.
3547   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3548   SourceLocation UDSuffixLoc =
3549     getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3550 
3551   // Make sure we're allowed user-defined literals here.
3552   if (!UDLScope)
3553     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3554 
3555   // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3556   //   operator "" X (ch)
3557   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3558                                         Lit, Tok.getLocation());
3559 }
3560 
3561 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3562   unsigned IntSize = Context.getTargetInfo().getIntWidth();
3563   return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3564                                 Context.IntTy, Loc);
3565 }
3566 
3567 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3568                                   QualType Ty, SourceLocation Loc) {
3569   const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3570 
3571   using llvm::APFloat;
3572   APFloat Val(Format);
3573 
3574   APFloat::opStatus result = Literal.GetFloatValue(Val);
3575 
3576   // Overflow is always an error, but underflow is only an error if
3577   // we underflowed to zero (APFloat reports denormals as underflow).
3578   if ((result & APFloat::opOverflow) ||
3579       ((result & APFloat::opUnderflow) && Val.isZero())) {
3580     unsigned diagnostic;
3581     SmallString<20> buffer;
3582     if (result & APFloat::opOverflow) {
3583       diagnostic = diag::warn_float_overflow;
3584       APFloat::getLargest(Format).toString(buffer);
3585     } else {
3586       diagnostic = diag::warn_float_underflow;
3587       APFloat::getSmallest(Format).toString(buffer);
3588     }
3589 
3590     S.Diag(Loc, diagnostic)
3591       << Ty
3592       << StringRef(buffer.data(), buffer.size());
3593   }
3594 
3595   bool isExact = (result == APFloat::opOK);
3596   return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3597 }
3598 
3599 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3600   assert(E && "Invalid expression");
3601 
3602   if (E->isValueDependent())
3603     return false;
3604 
3605   QualType QT = E->getType();
3606   if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3607     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3608     return true;
3609   }
3610 
3611   llvm::APSInt ValueAPS;
3612   ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3613 
3614   if (R.isInvalid())
3615     return true;
3616 
3617   bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3618   if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3619     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3620         << ValueAPS.toString(10) << ValueIsPositive;
3621     return true;
3622   }
3623 
3624   return false;
3625 }
3626 
3627 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3628   // Fast path for a single digit (which is quite common).  A single digit
3629   // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3630   if (Tok.getLength() == 1) {
3631     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3632     return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3633   }
3634 
3635   SmallString<128> SpellingBuffer;
3636   // NumericLiteralParser wants to overread by one character.  Add padding to
3637   // the buffer in case the token is copied to the buffer.  If getSpelling()
3638   // returns a StringRef to the memory buffer, it should have a null char at
3639   // the EOF, so it is also safe.
3640   SpellingBuffer.resize(Tok.getLength() + 1);
3641 
3642   // Get the spelling of the token, which eliminates trigraphs, etc.
3643   bool Invalid = false;
3644   StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3645   if (Invalid)
3646     return ExprError();
3647 
3648   NumericLiteralParser Literal(TokSpelling, Tok.getLocation(),
3649                                PP.getSourceManager(), PP.getLangOpts(),
3650                                PP.getTargetInfo(), PP.getDiagnostics());
3651   if (Literal.hadError)
3652     return ExprError();
3653 
3654   if (Literal.hasUDSuffix()) {
3655     // We're building a user-defined literal.
3656     IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3657     SourceLocation UDSuffixLoc =
3658       getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3659 
3660     // Make sure we're allowed user-defined literals here.
3661     if (!UDLScope)
3662       return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3663 
3664     QualType CookedTy;
3665     if (Literal.isFloatingLiteral()) {
3666       // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3667       // long double, the literal is treated as a call of the form
3668       //   operator "" X (f L)
3669       CookedTy = Context.LongDoubleTy;
3670     } else {
3671       // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3672       // unsigned long long, the literal is treated as a call of the form
3673       //   operator "" X (n ULL)
3674       CookedTy = Context.UnsignedLongLongTy;
3675     }
3676 
3677     DeclarationName OpName =
3678       Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3679     DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3680     OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3681 
3682     SourceLocation TokLoc = Tok.getLocation();
3683 
3684     // Perform literal operator lookup to determine if we're building a raw
3685     // literal or a cooked one.
3686     LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3687     switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3688                                   /*AllowRaw*/ true, /*AllowTemplate*/ true,
3689                                   /*AllowStringTemplate*/ false,
3690                                   /*DiagnoseMissing*/ !Literal.isImaginary)) {
3691     case LOLR_ErrorNoDiagnostic:
3692       // Lookup failure for imaginary constants isn't fatal, there's still the
3693       // GNU extension producing _Complex types.
3694       break;
3695     case LOLR_Error:
3696       return ExprError();
3697     case LOLR_Cooked: {
3698       Expr *Lit;
3699       if (Literal.isFloatingLiteral()) {
3700         Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3701       } else {
3702         llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3703         if (Literal.GetIntegerValue(ResultVal))
3704           Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3705               << /* Unsigned */ 1;
3706         Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3707                                      Tok.getLocation());
3708       }
3709       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3710     }
3711 
3712     case LOLR_Raw: {
3713       // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3714       // literal is treated as a call of the form
3715       //   operator "" X ("n")
3716       unsigned Length = Literal.getUDSuffixOffset();
3717       QualType StrTy = Context.getConstantArrayType(
3718           Context.adjustStringLiteralBaseType(Context.CharTy.withConst()),
3719           llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0);
3720       Expr *Lit = StringLiteral::Create(
3721           Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3722           /*Pascal*/false, StrTy, &TokLoc, 1);
3723       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3724     }
3725 
3726     case LOLR_Template: {
3727       // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3728       // template), L is treated as a call fo the form
3729       //   operator "" X <'c1', 'c2', ... 'ck'>()
3730       // where n is the source character sequence c1 c2 ... ck.
3731       TemplateArgumentListInfo ExplicitArgs;
3732       unsigned CharBits = Context.getIntWidth(Context.CharTy);
3733       bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3734       llvm::APSInt Value(CharBits, CharIsUnsigned);
3735       for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3736         Value = TokSpelling[I];
3737         TemplateArgument Arg(Context, Value, Context.CharTy);
3738         TemplateArgumentLocInfo ArgInfo;
3739         ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3740       }
3741       return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3742                                       &ExplicitArgs);
3743     }
3744     case LOLR_StringTemplate:
3745       llvm_unreachable("unexpected literal operator lookup result");
3746     }
3747   }
3748 
3749   Expr *Res;
3750 
3751   if (Literal.isFixedPointLiteral()) {
3752     QualType Ty;
3753 
3754     if (Literal.isAccum) {
3755       if (Literal.isHalf) {
3756         Ty = Context.ShortAccumTy;
3757       } else if (Literal.isLong) {
3758         Ty = Context.LongAccumTy;
3759       } else {
3760         Ty = Context.AccumTy;
3761       }
3762     } else if (Literal.isFract) {
3763       if (Literal.isHalf) {
3764         Ty = Context.ShortFractTy;
3765       } else if (Literal.isLong) {
3766         Ty = Context.LongFractTy;
3767       } else {
3768         Ty = Context.FractTy;
3769       }
3770     }
3771 
3772     if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
3773 
3774     bool isSigned = !Literal.isUnsigned;
3775     unsigned scale = Context.getFixedPointScale(Ty);
3776     unsigned bit_width = Context.getTypeInfo(Ty).Width;
3777 
3778     llvm::APInt Val(bit_width, 0, isSigned);
3779     bool Overflowed = Literal.GetFixedPointValue(Val, scale);
3780     bool ValIsZero = Val.isNullValue() && !Overflowed;
3781 
3782     auto MaxVal = Context.getFixedPointMax(Ty).getValue();
3783     if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
3784       // Clause 6.4.4 - The value of a constant shall be in the range of
3785       // representable values for its type, with exception for constants of a
3786       // fract type with a value of exactly 1; such a constant shall denote
3787       // the maximal value for the type.
3788       --Val;
3789     else if (Val.ugt(MaxVal) || Overflowed)
3790       Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
3791 
3792     Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty,
3793                                               Tok.getLocation(), scale);
3794   } else if (Literal.isFloatingLiteral()) {
3795     QualType Ty;
3796     if (Literal.isHalf){
3797       if (getOpenCLOptions().isEnabled("cl_khr_fp16"))
3798         Ty = Context.HalfTy;
3799       else {
3800         Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3801         return ExprError();
3802       }
3803     } else if (Literal.isFloat)
3804       Ty = Context.FloatTy;
3805     else if (Literal.isLong)
3806       Ty = Context.LongDoubleTy;
3807     else if (Literal.isFloat16)
3808       Ty = Context.Float16Ty;
3809     else if (Literal.isFloat128)
3810       Ty = Context.Float128Ty;
3811     else
3812       Ty = Context.DoubleTy;
3813 
3814     Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3815 
3816     if (Ty == Context.DoubleTy) {
3817       if (getLangOpts().SinglePrecisionConstants) {
3818         const BuiltinType *BTy = Ty->getAs<BuiltinType>();
3819         if (BTy->getKind() != BuiltinType::Float) {
3820           Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3821         }
3822       } else if (getLangOpts().OpenCL &&
3823                  !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
3824         // Impose single-precision float type when cl_khr_fp64 is not enabled.
3825         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
3826         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3827       }
3828     }
3829   } else if (!Literal.isIntegerLiteral()) {
3830     return ExprError();
3831   } else {
3832     QualType Ty;
3833 
3834     // 'long long' is a C99 or C++11 feature.
3835     if (!getLangOpts().C99 && Literal.isLongLong) {
3836       if (getLangOpts().CPlusPlus)
3837         Diag(Tok.getLocation(),
3838              getLangOpts().CPlusPlus11 ?
3839              diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3840       else
3841         Diag(Tok.getLocation(), diag::ext_c99_longlong);
3842     }
3843 
3844     // Get the value in the widest-possible width.
3845     unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3846     llvm::APInt ResultVal(MaxWidth, 0);
3847 
3848     if (Literal.GetIntegerValue(ResultVal)) {
3849       // If this value didn't fit into uintmax_t, error and force to ull.
3850       Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3851           << /* Unsigned */ 1;
3852       Ty = Context.UnsignedLongLongTy;
3853       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3854              "long long is not intmax_t?");
3855     } else {
3856       // If this value fits into a ULL, try to figure out what else it fits into
3857       // according to the rules of C99 6.4.4.1p5.
3858 
3859       // Octal, Hexadecimal, and integers with a U suffix are allowed to
3860       // be an unsigned int.
3861       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3862 
3863       // Check from smallest to largest, picking the smallest type we can.
3864       unsigned Width = 0;
3865 
3866       // Microsoft specific integer suffixes are explicitly sized.
3867       if (Literal.MicrosoftInteger) {
3868         if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3869           Width = 8;
3870           Ty = Context.CharTy;
3871         } else {
3872           Width = Literal.MicrosoftInteger;
3873           Ty = Context.getIntTypeForBitwidth(Width,
3874                                              /*Signed=*/!Literal.isUnsigned);
3875         }
3876       }
3877 
3878       if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
3879         // Are int/unsigned possibilities?
3880         unsigned IntSize = Context.getTargetInfo().getIntWidth();
3881 
3882         // Does it fit in a unsigned int?
3883         if (ResultVal.isIntN(IntSize)) {
3884           // Does it fit in a signed int?
3885           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3886             Ty = Context.IntTy;
3887           else if (AllowUnsigned)
3888             Ty = Context.UnsignedIntTy;
3889           Width = IntSize;
3890         }
3891       }
3892 
3893       // Are long/unsigned long possibilities?
3894       if (Ty.isNull() && !Literal.isLongLong) {
3895         unsigned LongSize = Context.getTargetInfo().getLongWidth();
3896 
3897         // Does it fit in a unsigned long?
3898         if (ResultVal.isIntN(LongSize)) {
3899           // Does it fit in a signed long?
3900           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3901             Ty = Context.LongTy;
3902           else if (AllowUnsigned)
3903             Ty = Context.UnsignedLongTy;
3904           // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
3905           // is compatible.
3906           else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
3907             const unsigned LongLongSize =
3908                 Context.getTargetInfo().getLongLongWidth();
3909             Diag(Tok.getLocation(),
3910                  getLangOpts().CPlusPlus
3911                      ? Literal.isLong
3912                            ? diag::warn_old_implicitly_unsigned_long_cxx
3913                            : /*C++98 UB*/ diag::
3914                                  ext_old_implicitly_unsigned_long_cxx
3915                      : diag::warn_old_implicitly_unsigned_long)
3916                 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
3917                                             : /*will be ill-formed*/ 1);
3918             Ty = Context.UnsignedLongTy;
3919           }
3920           Width = LongSize;
3921         }
3922       }
3923 
3924       // Check long long if needed.
3925       if (Ty.isNull()) {
3926         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3927 
3928         // Does it fit in a unsigned long long?
3929         if (ResultVal.isIntN(LongLongSize)) {
3930           // Does it fit in a signed long long?
3931           // To be compatible with MSVC, hex integer literals ending with the
3932           // LL or i64 suffix are always signed in Microsoft mode.
3933           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3934               (getLangOpts().MSVCCompat && Literal.isLongLong)))
3935             Ty = Context.LongLongTy;
3936           else if (AllowUnsigned)
3937             Ty = Context.UnsignedLongLongTy;
3938           Width = LongLongSize;
3939         }
3940       }
3941 
3942       // If we still couldn't decide a type, we probably have something that
3943       // does not fit in a signed long long, but has no U suffix.
3944       if (Ty.isNull()) {
3945         Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
3946         Ty = Context.UnsignedLongLongTy;
3947         Width = Context.getTargetInfo().getLongLongWidth();
3948       }
3949 
3950       if (ResultVal.getBitWidth() != Width)
3951         ResultVal = ResultVal.trunc(Width);
3952     }
3953     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3954   }
3955 
3956   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3957   if (Literal.isImaginary) {
3958     Res = new (Context) ImaginaryLiteral(Res,
3959                                         Context.getComplexType(Res->getType()));
3960 
3961     Diag(Tok.getLocation(), diag::ext_imaginary_constant);
3962   }
3963   return Res;
3964 }
3965 
3966 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
3967   assert(E && "ActOnParenExpr() missing expr");
3968   return new (Context) ParenExpr(L, R, E);
3969 }
3970 
3971 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3972                                          SourceLocation Loc,
3973                                          SourceRange ArgRange) {
3974   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3975   // scalar or vector data type argument..."
3976   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3977   // type (C99 6.2.5p18) or void.
3978   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3979     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3980       << T << ArgRange;
3981     return true;
3982   }
3983 
3984   assert((T->isVoidType() || !T->isIncompleteType()) &&
3985          "Scalar types should always be complete");
3986   return false;
3987 }
3988 
3989 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3990                                            SourceLocation Loc,
3991                                            SourceRange ArgRange,
3992                                            UnaryExprOrTypeTrait TraitKind) {
3993   // Invalid types must be hard errors for SFINAE in C++.
3994   if (S.LangOpts.CPlusPlus)
3995     return true;
3996 
3997   // C99 6.5.3.4p1:
3998   if (T->isFunctionType() &&
3999       (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
4000        TraitKind == UETT_PreferredAlignOf)) {
4001     // sizeof(function)/alignof(function) is allowed as an extension.
4002     S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
4003         << getTraitSpelling(TraitKind) << ArgRange;
4004     return false;
4005   }
4006 
4007   // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
4008   // this is an error (OpenCL v1.1 s6.3.k)
4009   if (T->isVoidType()) {
4010     unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
4011                                         : diag::ext_sizeof_alignof_void_type;
4012     S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange;
4013     return false;
4014   }
4015 
4016   return true;
4017 }
4018 
4019 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
4020                                              SourceLocation Loc,
4021                                              SourceRange ArgRange,
4022                                              UnaryExprOrTypeTrait TraitKind) {
4023   // Reject sizeof(interface) and sizeof(interface<proto>) if the
4024   // runtime doesn't allow it.
4025   if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
4026     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
4027       << T << (TraitKind == UETT_SizeOf)
4028       << ArgRange;
4029     return true;
4030   }
4031 
4032   return false;
4033 }
4034 
4035 /// Check whether E is a pointer from a decayed array type (the decayed
4036 /// pointer type is equal to T) and emit a warning if it is.
4037 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
4038                                      Expr *E) {
4039   // Don't warn if the operation changed the type.
4040   if (T != E->getType())
4041     return;
4042 
4043   // Now look for array decays.
4044   ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
4045   if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
4046     return;
4047 
4048   S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
4049                                              << ICE->getType()
4050                                              << ICE->getSubExpr()->getType();
4051 }
4052 
4053 /// Check the constraints on expression operands to unary type expression
4054 /// and type traits.
4055 ///
4056 /// Completes any types necessary and validates the constraints on the operand
4057 /// expression. The logic mostly mirrors the type-based overload, but may modify
4058 /// the expression as it completes the type for that expression through template
4059 /// instantiation, etc.
4060 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
4061                                             UnaryExprOrTypeTrait ExprKind) {
4062   QualType ExprTy = E->getType();
4063   assert(!ExprTy->isReferenceType());
4064 
4065   bool IsUnevaluatedOperand =
4066       (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf ||
4067        ExprKind == UETT_PreferredAlignOf);
4068   if (IsUnevaluatedOperand) {
4069     ExprResult Result = CheckUnevaluatedOperand(E);
4070     if (Result.isInvalid())
4071       return true;
4072     E = Result.get();
4073   }
4074 
4075   if (ExprKind == UETT_VecStep)
4076     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
4077                                         E->getSourceRange());
4078 
4079   // Explicitly list some types as extensions.
4080   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
4081                                       E->getSourceRange(), ExprKind))
4082     return false;
4083 
4084   // 'alignof' applied to an expression only requires the base element type of
4085   // the expression to be complete. 'sizeof' requires the expression's type to
4086   // be complete (and will attempt to complete it if it's an array of unknown
4087   // bound).
4088   if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4089     if (RequireCompleteSizedType(
4090             E->getExprLoc(), Context.getBaseElementType(E->getType()),
4091             diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4092             getTraitSpelling(ExprKind), E->getSourceRange()))
4093       return true;
4094   } else {
4095     if (RequireCompleteSizedExprType(
4096             E, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4097             getTraitSpelling(ExprKind), E->getSourceRange()))
4098       return true;
4099   }
4100 
4101   // Completing the expression's type may have changed it.
4102   ExprTy = E->getType();
4103   assert(!ExprTy->isReferenceType());
4104 
4105   if (ExprTy->isFunctionType()) {
4106     Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
4107         << getTraitSpelling(ExprKind) << E->getSourceRange();
4108     return true;
4109   }
4110 
4111   // The operand for sizeof and alignof is in an unevaluated expression context,
4112   // so side effects could result in unintended consequences.
4113   if (IsUnevaluatedOperand && !inTemplateInstantiation() &&
4114       E->HasSideEffects(Context, false))
4115     Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
4116 
4117   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
4118                                        E->getSourceRange(), ExprKind))
4119     return true;
4120 
4121   if (ExprKind == UETT_SizeOf) {
4122     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
4123       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
4124         QualType OType = PVD->getOriginalType();
4125         QualType Type = PVD->getType();
4126         if (Type->isPointerType() && OType->isArrayType()) {
4127           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
4128             << Type << OType;
4129           Diag(PVD->getLocation(), diag::note_declared_at);
4130         }
4131       }
4132     }
4133 
4134     // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
4135     // decays into a pointer and returns an unintended result. This is most
4136     // likely a typo for "sizeof(array) op x".
4137     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
4138       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4139                                BO->getLHS());
4140       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4141                                BO->getRHS());
4142     }
4143   }
4144 
4145   return false;
4146 }
4147 
4148 /// Check the constraints on operands to unary expression and type
4149 /// traits.
4150 ///
4151 /// This will complete any types necessary, and validate the various constraints
4152 /// on those operands.
4153 ///
4154 /// The UsualUnaryConversions() function is *not* called by this routine.
4155 /// C99 6.3.2.1p[2-4] all state:
4156 ///   Except when it is the operand of the sizeof operator ...
4157 ///
4158 /// C++ [expr.sizeof]p4
4159 ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
4160 ///   standard conversions are not applied to the operand of sizeof.
4161 ///
4162 /// This policy is followed for all of the unary trait expressions.
4163 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
4164                                             SourceLocation OpLoc,
4165                                             SourceRange ExprRange,
4166                                             UnaryExprOrTypeTrait ExprKind) {
4167   if (ExprType->isDependentType())
4168     return false;
4169 
4170   // C++ [expr.sizeof]p2:
4171   //     When applied to a reference or a reference type, the result
4172   //     is the size of the referenced type.
4173   // C++11 [expr.alignof]p3:
4174   //     When alignof is applied to a reference type, the result
4175   //     shall be the alignment of the referenced type.
4176   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
4177     ExprType = Ref->getPointeeType();
4178 
4179   // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
4180   //   When alignof or _Alignof is applied to an array type, the result
4181   //   is the alignment of the element type.
4182   if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4183       ExprKind == UETT_OpenMPRequiredSimdAlign)
4184     ExprType = Context.getBaseElementType(ExprType);
4185 
4186   if (ExprKind == UETT_VecStep)
4187     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
4188 
4189   // Explicitly list some types as extensions.
4190   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
4191                                       ExprKind))
4192     return false;
4193 
4194   if (RequireCompleteSizedType(
4195           OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4196           getTraitSpelling(ExprKind), ExprRange))
4197     return true;
4198 
4199   if (ExprType->isFunctionType()) {
4200     Diag(OpLoc, diag::err_sizeof_alignof_function_type)
4201         << getTraitSpelling(ExprKind) << ExprRange;
4202     return true;
4203   }
4204 
4205   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
4206                                        ExprKind))
4207     return true;
4208 
4209   return false;
4210 }
4211 
4212 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
4213   // Cannot know anything else if the expression is dependent.
4214   if (E->isTypeDependent())
4215     return false;
4216 
4217   if (E->getObjectKind() == OK_BitField) {
4218     S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
4219        << 1 << E->getSourceRange();
4220     return true;
4221   }
4222 
4223   ValueDecl *D = nullptr;
4224   Expr *Inner = E->IgnoreParens();
4225   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) {
4226     D = DRE->getDecl();
4227   } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) {
4228     D = ME->getMemberDecl();
4229   }
4230 
4231   // If it's a field, require the containing struct to have a
4232   // complete definition so that we can compute the layout.
4233   //
4234   // This can happen in C++11 onwards, either by naming the member
4235   // in a way that is not transformed into a member access expression
4236   // (in an unevaluated operand, for instance), or by naming the member
4237   // in a trailing-return-type.
4238   //
4239   // For the record, since __alignof__ on expressions is a GCC
4240   // extension, GCC seems to permit this but always gives the
4241   // nonsensical answer 0.
4242   //
4243   // We don't really need the layout here --- we could instead just
4244   // directly check for all the appropriate alignment-lowing
4245   // attributes --- but that would require duplicating a lot of
4246   // logic that just isn't worth duplicating for such a marginal
4247   // use-case.
4248   if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
4249     // Fast path this check, since we at least know the record has a
4250     // definition if we can find a member of it.
4251     if (!FD->getParent()->isCompleteDefinition()) {
4252       S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
4253         << E->getSourceRange();
4254       return true;
4255     }
4256 
4257     // Otherwise, if it's a field, and the field doesn't have
4258     // reference type, then it must have a complete type (or be a
4259     // flexible array member, which we explicitly want to
4260     // white-list anyway), which makes the following checks trivial.
4261     if (!FD->getType()->isReferenceType())
4262       return false;
4263   }
4264 
4265   return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4266 }
4267 
4268 bool Sema::CheckVecStepExpr(Expr *E) {
4269   E = E->IgnoreParens();
4270 
4271   // Cannot know anything else if the expression is dependent.
4272   if (E->isTypeDependent())
4273     return false;
4274 
4275   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
4276 }
4277 
4278 static void captureVariablyModifiedType(ASTContext &Context, QualType T,
4279                                         CapturingScopeInfo *CSI) {
4280   assert(T->isVariablyModifiedType());
4281   assert(CSI != nullptr);
4282 
4283   // We're going to walk down into the type and look for VLA expressions.
4284   do {
4285     const Type *Ty = T.getTypePtr();
4286     switch (Ty->getTypeClass()) {
4287 #define TYPE(Class, Base)
4288 #define ABSTRACT_TYPE(Class, Base)
4289 #define NON_CANONICAL_TYPE(Class, Base)
4290 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
4291 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4292 #include "clang/AST/TypeNodes.inc"
4293       T = QualType();
4294       break;
4295     // These types are never variably-modified.
4296     case Type::Builtin:
4297     case Type::Complex:
4298     case Type::Vector:
4299     case Type::ExtVector:
4300     case Type::ConstantMatrix:
4301     case Type::Record:
4302     case Type::Enum:
4303     case Type::Elaborated:
4304     case Type::TemplateSpecialization:
4305     case Type::ObjCObject:
4306     case Type::ObjCInterface:
4307     case Type::ObjCObjectPointer:
4308     case Type::ObjCTypeParam:
4309     case Type::Pipe:
4310     case Type::ExtInt:
4311       llvm_unreachable("type class is never variably-modified!");
4312     case Type::Adjusted:
4313       T = cast<AdjustedType>(Ty)->getOriginalType();
4314       break;
4315     case Type::Decayed:
4316       T = cast<DecayedType>(Ty)->getPointeeType();
4317       break;
4318     case Type::Pointer:
4319       T = cast<PointerType>(Ty)->getPointeeType();
4320       break;
4321     case Type::BlockPointer:
4322       T = cast<BlockPointerType>(Ty)->getPointeeType();
4323       break;
4324     case Type::LValueReference:
4325     case Type::RValueReference:
4326       T = cast<ReferenceType>(Ty)->getPointeeType();
4327       break;
4328     case Type::MemberPointer:
4329       T = cast<MemberPointerType>(Ty)->getPointeeType();
4330       break;
4331     case Type::ConstantArray:
4332     case Type::IncompleteArray:
4333       // Losing element qualification here is fine.
4334       T = cast<ArrayType>(Ty)->getElementType();
4335       break;
4336     case Type::VariableArray: {
4337       // Losing element qualification here is fine.
4338       const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
4339 
4340       // Unknown size indication requires no size computation.
4341       // Otherwise, evaluate and record it.
4342       auto Size = VAT->getSizeExpr();
4343       if (Size && !CSI->isVLATypeCaptured(VAT) &&
4344           (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI)))
4345         CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType());
4346 
4347       T = VAT->getElementType();
4348       break;
4349     }
4350     case Type::FunctionProto:
4351     case Type::FunctionNoProto:
4352       T = cast<FunctionType>(Ty)->getReturnType();
4353       break;
4354     case Type::Paren:
4355     case Type::TypeOf:
4356     case Type::UnaryTransform:
4357     case Type::Attributed:
4358     case Type::SubstTemplateTypeParm:
4359     case Type::MacroQualified:
4360       // Keep walking after single level desugaring.
4361       T = T.getSingleStepDesugaredType(Context);
4362       break;
4363     case Type::Typedef:
4364       T = cast<TypedefType>(Ty)->desugar();
4365       break;
4366     case Type::Decltype:
4367       T = cast<DecltypeType>(Ty)->desugar();
4368       break;
4369     case Type::Auto:
4370     case Type::DeducedTemplateSpecialization:
4371       T = cast<DeducedType>(Ty)->getDeducedType();
4372       break;
4373     case Type::TypeOfExpr:
4374       T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
4375       break;
4376     case Type::Atomic:
4377       T = cast<AtomicType>(Ty)->getValueType();
4378       break;
4379     }
4380   } while (!T.isNull() && T->isVariablyModifiedType());
4381 }
4382 
4383 /// Build a sizeof or alignof expression given a type operand.
4384 ExprResult
4385 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4386                                      SourceLocation OpLoc,
4387                                      UnaryExprOrTypeTrait ExprKind,
4388                                      SourceRange R) {
4389   if (!TInfo)
4390     return ExprError();
4391 
4392   QualType T = TInfo->getType();
4393 
4394   if (!T->isDependentType() &&
4395       CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
4396     return ExprError();
4397 
4398   if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4399     if (auto *TT = T->getAs<TypedefType>()) {
4400       for (auto I = FunctionScopes.rbegin(),
4401                 E = std::prev(FunctionScopes.rend());
4402            I != E; ++I) {
4403         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4404         if (CSI == nullptr)
4405           break;
4406         DeclContext *DC = nullptr;
4407         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4408           DC = LSI->CallOperator;
4409         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4410           DC = CRSI->TheCapturedDecl;
4411         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4412           DC = BSI->TheDecl;
4413         if (DC) {
4414           if (DC->containsDecl(TT->getDecl()))
4415             break;
4416           captureVariablyModifiedType(Context, T, CSI);
4417         }
4418       }
4419     }
4420   }
4421 
4422   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4423   return new (Context) UnaryExprOrTypeTraitExpr(
4424       ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4425 }
4426 
4427 /// Build a sizeof or alignof expression given an expression
4428 /// operand.
4429 ExprResult
4430 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4431                                      UnaryExprOrTypeTrait ExprKind) {
4432   ExprResult PE = CheckPlaceholderExpr(E);
4433   if (PE.isInvalid())
4434     return ExprError();
4435 
4436   E = PE.get();
4437 
4438   // Verify that the operand is valid.
4439   bool isInvalid = false;
4440   if (E->isTypeDependent()) {
4441     // Delay type-checking for type-dependent expressions.
4442   } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4443     isInvalid = CheckAlignOfExpr(*this, E, ExprKind);
4444   } else if (ExprKind == UETT_VecStep) {
4445     isInvalid = CheckVecStepExpr(E);
4446   } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4447       Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4448       isInvalid = true;
4449   } else if (E->refersToBitField()) {  // C99 6.5.3.4p1.
4450     Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4451     isInvalid = true;
4452   } else {
4453     isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
4454   }
4455 
4456   if (isInvalid)
4457     return ExprError();
4458 
4459   if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4460     PE = TransformToPotentiallyEvaluated(E);
4461     if (PE.isInvalid()) return ExprError();
4462     E = PE.get();
4463   }
4464 
4465   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4466   return new (Context) UnaryExprOrTypeTraitExpr(
4467       ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4468 }
4469 
4470 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4471 /// expr and the same for @c alignof and @c __alignof
4472 /// Note that the ArgRange is invalid if isType is false.
4473 ExprResult
4474 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4475                                     UnaryExprOrTypeTrait ExprKind, bool IsType,
4476                                     void *TyOrEx, SourceRange ArgRange) {
4477   // If error parsing type, ignore.
4478   if (!TyOrEx) return ExprError();
4479 
4480   if (IsType) {
4481     TypeSourceInfo *TInfo;
4482     (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4483     return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4484   }
4485 
4486   Expr *ArgEx = (Expr *)TyOrEx;
4487   ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4488   return Result;
4489 }
4490 
4491 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4492                                      bool IsReal) {
4493   if (V.get()->isTypeDependent())
4494     return S.Context.DependentTy;
4495 
4496   // _Real and _Imag are only l-values for normal l-values.
4497   if (V.get()->getObjectKind() != OK_Ordinary) {
4498     V = S.DefaultLvalueConversion(V.get());
4499     if (V.isInvalid())
4500       return QualType();
4501   }
4502 
4503   // These operators return the element type of a complex type.
4504   if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4505     return CT->getElementType();
4506 
4507   // Otherwise they pass through real integer and floating point types here.
4508   if (V.get()->getType()->isArithmeticType())
4509     return V.get()->getType();
4510 
4511   // Test for placeholders.
4512   ExprResult PR = S.CheckPlaceholderExpr(V.get());
4513   if (PR.isInvalid()) return QualType();
4514   if (PR.get() != V.get()) {
4515     V = PR;
4516     return CheckRealImagOperand(S, V, Loc, IsReal);
4517   }
4518 
4519   // Reject anything else.
4520   S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4521     << (IsReal ? "__real" : "__imag");
4522   return QualType();
4523 }
4524 
4525 
4526 
4527 ExprResult
4528 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4529                           tok::TokenKind Kind, Expr *Input) {
4530   UnaryOperatorKind Opc;
4531   switch (Kind) {
4532   default: llvm_unreachable("Unknown unary op!");
4533   case tok::plusplus:   Opc = UO_PostInc; break;
4534   case tok::minusminus: Opc = UO_PostDec; break;
4535   }
4536 
4537   // Since this might is a postfix expression, get rid of ParenListExprs.
4538   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4539   if (Result.isInvalid()) return ExprError();
4540   Input = Result.get();
4541 
4542   return BuildUnaryOp(S, OpLoc, Opc, Input);
4543 }
4544 
4545 /// Diagnose if arithmetic on the given ObjC pointer is illegal.
4546 ///
4547 /// \return true on error
4548 static bool checkArithmeticOnObjCPointer(Sema &S,
4549                                          SourceLocation opLoc,
4550                                          Expr *op) {
4551   assert(op->getType()->isObjCObjectPointerType());
4552   if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4553       !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4554     return false;
4555 
4556   S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4557     << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4558     << op->getSourceRange();
4559   return true;
4560 }
4561 
4562 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4563   auto *BaseNoParens = Base->IgnoreParens();
4564   if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4565     return MSProp->getPropertyDecl()->getType()->isArrayType();
4566   return isa<MSPropertySubscriptExpr>(BaseNoParens);
4567 }
4568 
4569 ExprResult
4570 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
4571                               Expr *idx, SourceLocation rbLoc) {
4572   if (base && !base->getType().isNull() &&
4573       base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection))
4574     return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
4575                                     SourceLocation(), /*Length*/ nullptr,
4576                                     /*Stride=*/nullptr, rbLoc);
4577 
4578   // Since this might be a postfix expression, get rid of ParenListExprs.
4579   if (isa<ParenListExpr>(base)) {
4580     ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4581     if (result.isInvalid()) return ExprError();
4582     base = result.get();
4583   }
4584 
4585   // Check if base and idx form a MatrixSubscriptExpr.
4586   //
4587   // Helper to check for comma expressions, which are not allowed as indices for
4588   // matrix subscript expressions.
4589   auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) {
4590     if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) {
4591       Diag(E->getExprLoc(), diag::err_matrix_subscript_comma)
4592           << SourceRange(base->getBeginLoc(), rbLoc);
4593       return true;
4594     }
4595     return false;
4596   };
4597   // The matrix subscript operator ([][])is considered a single operator.
4598   // Separating the index expressions by parenthesis is not allowed.
4599   if (base->getType()->isSpecificPlaceholderType(
4600           BuiltinType::IncompleteMatrixIdx) &&
4601       !isa<MatrixSubscriptExpr>(base)) {
4602     Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index)
4603         << SourceRange(base->getBeginLoc(), rbLoc);
4604     return ExprError();
4605   }
4606   // If the base is a MatrixSubscriptExpr, try to create a new
4607   // MatrixSubscriptExpr.
4608   auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base);
4609   if (matSubscriptE) {
4610     if (CheckAndReportCommaError(idx))
4611       return ExprError();
4612 
4613     assert(matSubscriptE->isIncomplete() &&
4614            "base has to be an incomplete matrix subscript");
4615     return CreateBuiltinMatrixSubscriptExpr(
4616         matSubscriptE->getBase(), matSubscriptE->getRowIdx(), idx, rbLoc);
4617   }
4618 
4619   // Handle any non-overload placeholder types in the base and index
4620   // expressions.  We can't handle overloads here because the other
4621   // operand might be an overloadable type, in which case the overload
4622   // resolution for the operator overload should get the first crack
4623   // at the overload.
4624   bool IsMSPropertySubscript = false;
4625   if (base->getType()->isNonOverloadPlaceholderType()) {
4626     IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4627     if (!IsMSPropertySubscript) {
4628       ExprResult result = CheckPlaceholderExpr(base);
4629       if (result.isInvalid())
4630         return ExprError();
4631       base = result.get();
4632     }
4633   }
4634 
4635   // If the base is a matrix type, try to create a new MatrixSubscriptExpr.
4636   if (base->getType()->isMatrixType()) {
4637     if (CheckAndReportCommaError(idx))
4638       return ExprError();
4639 
4640     return CreateBuiltinMatrixSubscriptExpr(base, idx, nullptr, rbLoc);
4641   }
4642 
4643   // A comma-expression as the index is deprecated in C++2a onwards.
4644   if (getLangOpts().CPlusPlus20 &&
4645       ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) ||
4646        (isa<CXXOperatorCallExpr>(idx) &&
4647         cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma))) {
4648     Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript)
4649         << SourceRange(base->getBeginLoc(), rbLoc);
4650   }
4651 
4652   if (idx->getType()->isNonOverloadPlaceholderType()) {
4653     ExprResult result = CheckPlaceholderExpr(idx);
4654     if (result.isInvalid()) return ExprError();
4655     idx = result.get();
4656   }
4657 
4658   // Build an unanalyzed expression if either operand is type-dependent.
4659   if (getLangOpts().CPlusPlus &&
4660       (base->isTypeDependent() || idx->isTypeDependent())) {
4661     return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
4662                                             VK_LValue, OK_Ordinary, rbLoc);
4663   }
4664 
4665   // MSDN, property (C++)
4666   // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4667   // This attribute can also be used in the declaration of an empty array in a
4668   // class or structure definition. For example:
4669   // __declspec(property(get=GetX, put=PutX)) int x[];
4670   // The above statement indicates that x[] can be used with one or more array
4671   // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4672   // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4673   if (IsMSPropertySubscript) {
4674     // Build MS property subscript expression if base is MS property reference
4675     // or MS property subscript.
4676     return new (Context) MSPropertySubscriptExpr(
4677         base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
4678   }
4679 
4680   // Use C++ overloaded-operator rules if either operand has record
4681   // type.  The spec says to do this if either type is *overloadable*,
4682   // but enum types can't declare subscript operators or conversion
4683   // operators, so there's nothing interesting for overload resolution
4684   // to do if there aren't any record types involved.
4685   //
4686   // ObjC pointers have their own subscripting logic that is not tied
4687   // to overload resolution and so should not take this path.
4688   if (getLangOpts().CPlusPlus &&
4689       (base->getType()->isRecordType() ||
4690        (!base->getType()->isObjCObjectPointerType() &&
4691         idx->getType()->isRecordType()))) {
4692     return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
4693   }
4694 
4695   ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
4696 
4697   if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get()))
4698     CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get()));
4699 
4700   return Res;
4701 }
4702 
4703 ExprResult Sema::tryConvertExprToType(Expr *E, QualType Ty) {
4704   InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty);
4705   InitializationKind Kind =
4706       InitializationKind::CreateCopy(E->getBeginLoc(), SourceLocation());
4707   InitializationSequence InitSeq(*this, Entity, Kind, E);
4708   return InitSeq.Perform(*this, Entity, Kind, E);
4709 }
4710 
4711 ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx,
4712                                                   Expr *ColumnIdx,
4713                                                   SourceLocation RBLoc) {
4714   ExprResult BaseR = CheckPlaceholderExpr(Base);
4715   if (BaseR.isInvalid())
4716     return BaseR;
4717   Base = BaseR.get();
4718 
4719   ExprResult RowR = CheckPlaceholderExpr(RowIdx);
4720   if (RowR.isInvalid())
4721     return RowR;
4722   RowIdx = RowR.get();
4723 
4724   if (!ColumnIdx)
4725     return new (Context) MatrixSubscriptExpr(
4726         Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc);
4727 
4728   // Build an unanalyzed expression if any of the operands is type-dependent.
4729   if (Base->isTypeDependent() || RowIdx->isTypeDependent() ||
4730       ColumnIdx->isTypeDependent())
4731     return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
4732                                              Context.DependentTy, RBLoc);
4733 
4734   ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx);
4735   if (ColumnR.isInvalid())
4736     return ColumnR;
4737   ColumnIdx = ColumnR.get();
4738 
4739   // Check that IndexExpr is an integer expression. If it is a constant
4740   // expression, check that it is less than Dim (= the number of elements in the
4741   // corresponding dimension).
4742   auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim,
4743                           bool IsColumnIdx) -> Expr * {
4744     if (!IndexExpr->getType()->isIntegerType() &&
4745         !IndexExpr->isTypeDependent()) {
4746       Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer)
4747           << IsColumnIdx;
4748       return nullptr;
4749     }
4750 
4751     if (Optional<llvm::APSInt> Idx =
4752             IndexExpr->getIntegerConstantExpr(Context)) {
4753       if ((*Idx < 0 || *Idx >= Dim)) {
4754         Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range)
4755             << IsColumnIdx << Dim;
4756         return nullptr;
4757       }
4758     }
4759 
4760     ExprResult ConvExpr =
4761         tryConvertExprToType(IndexExpr, Context.getSizeType());
4762     assert(!ConvExpr.isInvalid() &&
4763            "should be able to convert any integer type to size type");
4764     return ConvExpr.get();
4765   };
4766 
4767   auto *MTy = Base->getType()->getAs<ConstantMatrixType>();
4768   RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false);
4769   ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true);
4770   if (!RowIdx || !ColumnIdx)
4771     return ExprError();
4772 
4773   return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
4774                                            MTy->getElementType(), RBLoc);
4775 }
4776 
4777 void Sema::CheckAddressOfNoDeref(const Expr *E) {
4778   ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4779   const Expr *StrippedExpr = E->IgnoreParenImpCasts();
4780 
4781   // For expressions like `&(*s).b`, the base is recorded and what should be
4782   // checked.
4783   const MemberExpr *Member = nullptr;
4784   while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow())
4785     StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
4786 
4787   LastRecord.PossibleDerefs.erase(StrippedExpr);
4788 }
4789 
4790 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
4791   QualType ResultTy = E->getType();
4792   ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4793 
4794   // Bail if the element is an array since it is not memory access.
4795   if (isa<ArrayType>(ResultTy))
4796     return;
4797 
4798   if (ResultTy->hasAttr(attr::NoDeref)) {
4799     LastRecord.PossibleDerefs.insert(E);
4800     return;
4801   }
4802 
4803   // Check if the base type is a pointer to a member access of a struct
4804   // marked with noderef.
4805   const Expr *Base = E->getBase();
4806   QualType BaseTy = Base->getType();
4807   if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy)))
4808     // Not a pointer access
4809     return;
4810 
4811   const MemberExpr *Member = nullptr;
4812   while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) &&
4813          Member->isArrow())
4814     Base = Member->getBase();
4815 
4816   if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) {
4817     if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))
4818       LastRecord.PossibleDerefs.insert(E);
4819   }
4820 }
4821 
4822 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4823                                           Expr *LowerBound,
4824                                           SourceLocation ColonLocFirst,
4825                                           SourceLocation ColonLocSecond,
4826                                           Expr *Length, Expr *Stride,
4827                                           SourceLocation RBLoc) {
4828   if (Base->getType()->isPlaceholderType() &&
4829       !Base->getType()->isSpecificPlaceholderType(
4830           BuiltinType::OMPArraySection)) {
4831     ExprResult Result = CheckPlaceholderExpr(Base);
4832     if (Result.isInvalid())
4833       return ExprError();
4834     Base = Result.get();
4835   }
4836   if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
4837     ExprResult Result = CheckPlaceholderExpr(LowerBound);
4838     if (Result.isInvalid())
4839       return ExprError();
4840     Result = DefaultLvalueConversion(Result.get());
4841     if (Result.isInvalid())
4842       return ExprError();
4843     LowerBound = Result.get();
4844   }
4845   if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
4846     ExprResult Result = CheckPlaceholderExpr(Length);
4847     if (Result.isInvalid())
4848       return ExprError();
4849     Result = DefaultLvalueConversion(Result.get());
4850     if (Result.isInvalid())
4851       return ExprError();
4852     Length = Result.get();
4853   }
4854   if (Stride && Stride->getType()->isNonOverloadPlaceholderType()) {
4855     ExprResult Result = CheckPlaceholderExpr(Stride);
4856     if (Result.isInvalid())
4857       return ExprError();
4858     Result = DefaultLvalueConversion(Result.get());
4859     if (Result.isInvalid())
4860       return ExprError();
4861     Stride = Result.get();
4862   }
4863 
4864   // Build an unanalyzed expression if either operand is type-dependent.
4865   if (Base->isTypeDependent() ||
4866       (LowerBound &&
4867        (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
4868       (Length && (Length->isTypeDependent() || Length->isValueDependent())) ||
4869       (Stride && (Stride->isTypeDependent() || Stride->isValueDependent()))) {
4870     return new (Context) OMPArraySectionExpr(
4871         Base, LowerBound, Length, Stride, Context.DependentTy, VK_LValue,
4872         OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc);
4873   }
4874 
4875   // Perform default conversions.
4876   QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
4877   QualType ResultTy;
4878   if (OriginalTy->isAnyPointerType()) {
4879     ResultTy = OriginalTy->getPointeeType();
4880   } else if (OriginalTy->isArrayType()) {
4881     ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
4882   } else {
4883     return ExprError(
4884         Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
4885         << Base->getSourceRange());
4886   }
4887   // C99 6.5.2.1p1
4888   if (LowerBound) {
4889     auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
4890                                                       LowerBound);
4891     if (Res.isInvalid())
4892       return ExprError(Diag(LowerBound->getExprLoc(),
4893                             diag::err_omp_typecheck_section_not_integer)
4894                        << 0 << LowerBound->getSourceRange());
4895     LowerBound = Res.get();
4896 
4897     if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4898         LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4899       Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
4900           << 0 << LowerBound->getSourceRange();
4901   }
4902   if (Length) {
4903     auto Res =
4904         PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
4905     if (Res.isInvalid())
4906       return ExprError(Diag(Length->getExprLoc(),
4907                             diag::err_omp_typecheck_section_not_integer)
4908                        << 1 << Length->getSourceRange());
4909     Length = Res.get();
4910 
4911     if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4912         Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4913       Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
4914           << 1 << Length->getSourceRange();
4915   }
4916   if (Stride) {
4917     ExprResult Res =
4918         PerformOpenMPImplicitIntegerConversion(Stride->getExprLoc(), Stride);
4919     if (Res.isInvalid())
4920       return ExprError(Diag(Stride->getExprLoc(),
4921                             diag::err_omp_typecheck_section_not_integer)
4922                        << 1 << Stride->getSourceRange());
4923     Stride = Res.get();
4924 
4925     if (Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4926         Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4927       Diag(Stride->getExprLoc(), diag::warn_omp_section_is_char)
4928           << 1 << Stride->getSourceRange();
4929   }
4930 
4931   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4932   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4933   // type. Note that functions are not objects, and that (in C99 parlance)
4934   // incomplete types are not object types.
4935   if (ResultTy->isFunctionType()) {
4936     Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
4937         << ResultTy << Base->getSourceRange();
4938     return ExprError();
4939   }
4940 
4941   if (RequireCompleteType(Base->getExprLoc(), ResultTy,
4942                           diag::err_omp_section_incomplete_type, Base))
4943     return ExprError();
4944 
4945   if (LowerBound && !OriginalTy->isAnyPointerType()) {
4946     Expr::EvalResult Result;
4947     if (LowerBound->EvaluateAsInt(Result, Context)) {
4948       // OpenMP 5.0, [2.1.5 Array Sections]
4949       // The array section must be a subset of the original array.
4950       llvm::APSInt LowerBoundValue = Result.Val.getInt();
4951       if (LowerBoundValue.isNegative()) {
4952         Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
4953             << LowerBound->getSourceRange();
4954         return ExprError();
4955       }
4956     }
4957   }
4958 
4959   if (Length) {
4960     Expr::EvalResult Result;
4961     if (Length->EvaluateAsInt(Result, Context)) {
4962       // OpenMP 5.0, [2.1.5 Array Sections]
4963       // The length must evaluate to non-negative integers.
4964       llvm::APSInt LengthValue = Result.Val.getInt();
4965       if (LengthValue.isNegative()) {
4966         Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
4967             << LengthValue.toString(/*Radix=*/10, /*Signed=*/true)
4968             << Length->getSourceRange();
4969         return ExprError();
4970       }
4971     }
4972   } else if (ColonLocFirst.isValid() &&
4973              (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
4974                                       !OriginalTy->isVariableArrayType()))) {
4975     // OpenMP 5.0, [2.1.5 Array Sections]
4976     // When the size of the array dimension is not known, the length must be
4977     // specified explicitly.
4978     Diag(ColonLocFirst, diag::err_omp_section_length_undefined)
4979         << (!OriginalTy.isNull() && OriginalTy->isArrayType());
4980     return ExprError();
4981   }
4982 
4983   if (Stride) {
4984     Expr::EvalResult Result;
4985     if (Stride->EvaluateAsInt(Result, Context)) {
4986       // OpenMP 5.0, [2.1.5 Array Sections]
4987       // The stride must evaluate to a positive integer.
4988       llvm::APSInt StrideValue = Result.Val.getInt();
4989       if (!StrideValue.isStrictlyPositive()) {
4990         Diag(Stride->getExprLoc(), diag::err_omp_section_stride_non_positive)
4991             << StrideValue.toString(/*Radix=*/10, /*Signed=*/true)
4992             << Stride->getSourceRange();
4993         return ExprError();
4994       }
4995     }
4996   }
4997 
4998   if (!Base->getType()->isSpecificPlaceholderType(
4999           BuiltinType::OMPArraySection)) {
5000     ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
5001     if (Result.isInvalid())
5002       return ExprError();
5003     Base = Result.get();
5004   }
5005   return new (Context) OMPArraySectionExpr(
5006       Base, LowerBound, Length, Stride, Context.OMPArraySectionTy, VK_LValue,
5007       OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc);
5008 }
5009 
5010 ExprResult Sema::ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc,
5011                                           SourceLocation RParenLoc,
5012                                           ArrayRef<Expr *> Dims,
5013                                           ArrayRef<SourceRange> Brackets) {
5014   if (Base->getType()->isPlaceholderType()) {
5015     ExprResult Result = CheckPlaceholderExpr(Base);
5016     if (Result.isInvalid())
5017       return ExprError();
5018     Result = DefaultLvalueConversion(Result.get());
5019     if (Result.isInvalid())
5020       return ExprError();
5021     Base = Result.get();
5022   }
5023   QualType BaseTy = Base->getType();
5024   // Delay analysis of the types/expressions if instantiation/specialization is
5025   // required.
5026   if (!BaseTy->isPointerType() && Base->isTypeDependent())
5027     return OMPArrayShapingExpr::Create(Context, Context.DependentTy, Base,
5028                                        LParenLoc, RParenLoc, Dims, Brackets);
5029   if (!BaseTy->isPointerType() ||
5030       (!Base->isTypeDependent() &&
5031        BaseTy->getPointeeType()->isIncompleteType()))
5032     return ExprError(Diag(Base->getExprLoc(),
5033                           diag::err_omp_non_pointer_type_array_shaping_base)
5034                      << Base->getSourceRange());
5035 
5036   SmallVector<Expr *, 4> NewDims;
5037   bool ErrorFound = false;
5038   for (Expr *Dim : Dims) {
5039     if (Dim->getType()->isPlaceholderType()) {
5040       ExprResult Result = CheckPlaceholderExpr(Dim);
5041       if (Result.isInvalid()) {
5042         ErrorFound = true;
5043         continue;
5044       }
5045       Result = DefaultLvalueConversion(Result.get());
5046       if (Result.isInvalid()) {
5047         ErrorFound = true;
5048         continue;
5049       }
5050       Dim = Result.get();
5051     }
5052     if (!Dim->isTypeDependent()) {
5053       ExprResult Result =
5054           PerformOpenMPImplicitIntegerConversion(Dim->getExprLoc(), Dim);
5055       if (Result.isInvalid()) {
5056         ErrorFound = true;
5057         Diag(Dim->getExprLoc(), diag::err_omp_typecheck_shaping_not_integer)
5058             << Dim->getSourceRange();
5059         continue;
5060       }
5061       Dim = Result.get();
5062       Expr::EvalResult EvResult;
5063       if (!Dim->isValueDependent() && Dim->EvaluateAsInt(EvResult, Context)) {
5064         // OpenMP 5.0, [2.1.4 Array Shaping]
5065         // Each si is an integral type expression that must evaluate to a
5066         // positive integer.
5067         llvm::APSInt Value = EvResult.Val.getInt();
5068         if (!Value.isStrictlyPositive()) {
5069           Diag(Dim->getExprLoc(), diag::err_omp_shaping_dimension_not_positive)
5070               << Value.toString(/*Radix=*/10, /*Signed=*/true)
5071               << Dim->getSourceRange();
5072           ErrorFound = true;
5073           continue;
5074         }
5075       }
5076     }
5077     NewDims.push_back(Dim);
5078   }
5079   if (ErrorFound)
5080     return ExprError();
5081   return OMPArrayShapingExpr::Create(Context, Context.OMPArrayShapingTy, Base,
5082                                      LParenLoc, RParenLoc, NewDims, Brackets);
5083 }
5084 
5085 ExprResult Sema::ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc,
5086                                       SourceLocation LLoc, SourceLocation RLoc,
5087                                       ArrayRef<OMPIteratorData> Data) {
5088   SmallVector<OMPIteratorExpr::IteratorDefinition, 4> ID;
5089   bool IsCorrect = true;
5090   for (const OMPIteratorData &D : Data) {
5091     TypeSourceInfo *TInfo = nullptr;
5092     SourceLocation StartLoc;
5093     QualType DeclTy;
5094     if (!D.Type.getAsOpaquePtr()) {
5095       // OpenMP 5.0, 2.1.6 Iterators
5096       // In an iterator-specifier, if the iterator-type is not specified then
5097       // the type of that iterator is of int type.
5098       DeclTy = Context.IntTy;
5099       StartLoc = D.DeclIdentLoc;
5100     } else {
5101       DeclTy = GetTypeFromParser(D.Type, &TInfo);
5102       StartLoc = TInfo->getTypeLoc().getBeginLoc();
5103     }
5104 
5105     bool IsDeclTyDependent = DeclTy->isDependentType() ||
5106                              DeclTy->containsUnexpandedParameterPack() ||
5107                              DeclTy->isInstantiationDependentType();
5108     if (!IsDeclTyDependent) {
5109       if (!DeclTy->isIntegralType(Context) && !DeclTy->isAnyPointerType()) {
5110         // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++
5111         // The iterator-type must be an integral or pointer type.
5112         Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer)
5113             << DeclTy;
5114         IsCorrect = false;
5115         continue;
5116       }
5117       if (DeclTy.isConstant(Context)) {
5118         // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++
5119         // The iterator-type must not be const qualified.
5120         Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer)
5121             << DeclTy;
5122         IsCorrect = false;
5123         continue;
5124       }
5125     }
5126 
5127     // Iterator declaration.
5128     assert(D.DeclIdent && "Identifier expected.");
5129     // Always try to create iterator declarator to avoid extra error messages
5130     // about unknown declarations use.
5131     auto *VD = VarDecl::Create(Context, CurContext, StartLoc, D.DeclIdentLoc,
5132                                D.DeclIdent, DeclTy, TInfo, SC_None);
5133     VD->setImplicit();
5134     if (S) {
5135       // Check for conflicting previous declaration.
5136       DeclarationNameInfo NameInfo(VD->getDeclName(), D.DeclIdentLoc);
5137       LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5138                             ForVisibleRedeclaration);
5139       Previous.suppressDiagnostics();
5140       LookupName(Previous, S);
5141 
5142       FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false,
5143                            /*AllowInlineNamespace=*/false);
5144       if (!Previous.empty()) {
5145         NamedDecl *Old = Previous.getRepresentativeDecl();
5146         Diag(D.DeclIdentLoc, diag::err_redefinition) << VD->getDeclName();
5147         Diag(Old->getLocation(), diag::note_previous_definition);
5148       } else {
5149         PushOnScopeChains(VD, S);
5150       }
5151     } else {
5152       CurContext->addDecl(VD);
5153     }
5154     Expr *Begin = D.Range.Begin;
5155     if (!IsDeclTyDependent && Begin && !Begin->isTypeDependent()) {
5156       ExprResult BeginRes =
5157           PerformImplicitConversion(Begin, DeclTy, AA_Converting);
5158       Begin = BeginRes.get();
5159     }
5160     Expr *End = D.Range.End;
5161     if (!IsDeclTyDependent && End && !End->isTypeDependent()) {
5162       ExprResult EndRes = PerformImplicitConversion(End, DeclTy, AA_Converting);
5163       End = EndRes.get();
5164     }
5165     Expr *Step = D.Range.Step;
5166     if (!IsDeclTyDependent && Step && !Step->isTypeDependent()) {
5167       if (!Step->getType()->isIntegralType(Context)) {
5168         Diag(Step->getExprLoc(), diag::err_omp_iterator_step_not_integral)
5169             << Step << Step->getSourceRange();
5170         IsCorrect = false;
5171         continue;
5172       }
5173       Optional<llvm::APSInt> Result = Step->getIntegerConstantExpr(Context);
5174       // OpenMP 5.0, 2.1.6 Iterators, Restrictions
5175       // If the step expression of a range-specification equals zero, the
5176       // behavior is unspecified.
5177       if (Result && Result->isNullValue()) {
5178         Diag(Step->getExprLoc(), diag::err_omp_iterator_step_constant_zero)
5179             << Step << Step->getSourceRange();
5180         IsCorrect = false;
5181         continue;
5182       }
5183     }
5184     if (!Begin || !End || !IsCorrect) {
5185       IsCorrect = false;
5186       continue;
5187     }
5188     OMPIteratorExpr::IteratorDefinition &IDElem = ID.emplace_back();
5189     IDElem.IteratorDecl = VD;
5190     IDElem.AssignmentLoc = D.AssignLoc;
5191     IDElem.Range.Begin = Begin;
5192     IDElem.Range.End = End;
5193     IDElem.Range.Step = Step;
5194     IDElem.ColonLoc = D.ColonLoc;
5195     IDElem.SecondColonLoc = D.SecColonLoc;
5196   }
5197   if (!IsCorrect) {
5198     // Invalidate all created iterator declarations if error is found.
5199     for (const OMPIteratorExpr::IteratorDefinition &D : ID) {
5200       if (Decl *ID = D.IteratorDecl)
5201         ID->setInvalidDecl();
5202     }
5203     return ExprError();
5204   }
5205   SmallVector<OMPIteratorHelperData, 4> Helpers;
5206   if (!CurContext->isDependentContext()) {
5207     // Build number of ityeration for each iteration range.
5208     // Ni = ((Stepi > 0) ? ((Endi + Stepi -1 - Begini)/Stepi) :
5209     // ((Begini-Stepi-1-Endi) / -Stepi);
5210     for (OMPIteratorExpr::IteratorDefinition &D : ID) {
5211       // (Endi - Begini)
5212       ExprResult Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, D.Range.End,
5213                                           D.Range.Begin);
5214       if(!Res.isUsable()) {
5215         IsCorrect = false;
5216         continue;
5217       }
5218       ExprResult St, St1;
5219       if (D.Range.Step) {
5220         St = D.Range.Step;
5221         // (Endi - Begini) + Stepi
5222         Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res.get(), St.get());
5223         if (!Res.isUsable()) {
5224           IsCorrect = false;
5225           continue;
5226         }
5227         // (Endi - Begini) + Stepi - 1
5228         Res =
5229             CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res.get(),
5230                                ActOnIntegerConstant(D.AssignmentLoc, 1).get());
5231         if (!Res.isUsable()) {
5232           IsCorrect = false;
5233           continue;
5234         }
5235         // ((Endi - Begini) + Stepi - 1) / Stepi
5236         Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res.get(), St.get());
5237         if (!Res.isUsable()) {
5238           IsCorrect = false;
5239           continue;
5240         }
5241         St1 = CreateBuiltinUnaryOp(D.AssignmentLoc, UO_Minus, D.Range.Step);
5242         // (Begini - Endi)
5243         ExprResult Res1 = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub,
5244                                              D.Range.Begin, D.Range.End);
5245         if (!Res1.isUsable()) {
5246           IsCorrect = false;
5247           continue;
5248         }
5249         // (Begini - Endi) - Stepi
5250         Res1 =
5251             CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res1.get(), St1.get());
5252         if (!Res1.isUsable()) {
5253           IsCorrect = false;
5254           continue;
5255         }
5256         // (Begini - Endi) - Stepi - 1
5257         Res1 =
5258             CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res1.get(),
5259                                ActOnIntegerConstant(D.AssignmentLoc, 1).get());
5260         if (!Res1.isUsable()) {
5261           IsCorrect = false;
5262           continue;
5263         }
5264         // ((Begini - Endi) - Stepi - 1) / (-Stepi)
5265         Res1 =
5266             CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res1.get(), St1.get());
5267         if (!Res1.isUsable()) {
5268           IsCorrect = false;
5269           continue;
5270         }
5271         // Stepi > 0.
5272         ExprResult CmpRes =
5273             CreateBuiltinBinOp(D.AssignmentLoc, BO_GT, D.Range.Step,
5274                                ActOnIntegerConstant(D.AssignmentLoc, 0).get());
5275         if (!CmpRes.isUsable()) {
5276           IsCorrect = false;
5277           continue;
5278         }
5279         Res = ActOnConditionalOp(D.AssignmentLoc, D.AssignmentLoc, CmpRes.get(),
5280                                  Res.get(), Res1.get());
5281         if (!Res.isUsable()) {
5282           IsCorrect = false;
5283           continue;
5284         }
5285       }
5286       Res = ActOnFinishFullExpr(Res.get(), /*DiscardedValue=*/false);
5287       if (!Res.isUsable()) {
5288         IsCorrect = false;
5289         continue;
5290       }
5291 
5292       // Build counter update.
5293       // Build counter.
5294       auto *CounterVD =
5295           VarDecl::Create(Context, CurContext, D.IteratorDecl->getBeginLoc(),
5296                           D.IteratorDecl->getBeginLoc(), nullptr,
5297                           Res.get()->getType(), nullptr, SC_None);
5298       CounterVD->setImplicit();
5299       ExprResult RefRes =
5300           BuildDeclRefExpr(CounterVD, CounterVD->getType(), VK_LValue,
5301                            D.IteratorDecl->getBeginLoc());
5302       // Build counter update.
5303       // I = Begini + counter * Stepi;
5304       ExprResult UpdateRes;
5305       if (D.Range.Step) {
5306         UpdateRes = CreateBuiltinBinOp(
5307             D.AssignmentLoc, BO_Mul,
5308             DefaultLvalueConversion(RefRes.get()).get(), St.get());
5309       } else {
5310         UpdateRes = DefaultLvalueConversion(RefRes.get());
5311       }
5312       if (!UpdateRes.isUsable()) {
5313         IsCorrect = false;
5314         continue;
5315       }
5316       UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, D.Range.Begin,
5317                                      UpdateRes.get());
5318       if (!UpdateRes.isUsable()) {
5319         IsCorrect = false;
5320         continue;
5321       }
5322       ExprResult VDRes =
5323           BuildDeclRefExpr(cast<VarDecl>(D.IteratorDecl),
5324                            cast<VarDecl>(D.IteratorDecl)->getType(), VK_LValue,
5325                            D.IteratorDecl->getBeginLoc());
5326       UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Assign, VDRes.get(),
5327                                      UpdateRes.get());
5328       if (!UpdateRes.isUsable()) {
5329         IsCorrect = false;
5330         continue;
5331       }
5332       UpdateRes =
5333           ActOnFinishFullExpr(UpdateRes.get(), /*DiscardedValue=*/true);
5334       if (!UpdateRes.isUsable()) {
5335         IsCorrect = false;
5336         continue;
5337       }
5338       ExprResult CounterUpdateRes =
5339           CreateBuiltinUnaryOp(D.AssignmentLoc, UO_PreInc, RefRes.get());
5340       if (!CounterUpdateRes.isUsable()) {
5341         IsCorrect = false;
5342         continue;
5343       }
5344       CounterUpdateRes =
5345           ActOnFinishFullExpr(CounterUpdateRes.get(), /*DiscardedValue=*/true);
5346       if (!CounterUpdateRes.isUsable()) {
5347         IsCorrect = false;
5348         continue;
5349       }
5350       OMPIteratorHelperData &HD = Helpers.emplace_back();
5351       HD.CounterVD = CounterVD;
5352       HD.Upper = Res.get();
5353       HD.Update = UpdateRes.get();
5354       HD.CounterUpdate = CounterUpdateRes.get();
5355     }
5356   } else {
5357     Helpers.assign(ID.size(), {});
5358   }
5359   if (!IsCorrect) {
5360     // Invalidate all created iterator declarations if error is found.
5361     for (const OMPIteratorExpr::IteratorDefinition &D : ID) {
5362       if (Decl *ID = D.IteratorDecl)
5363         ID->setInvalidDecl();
5364     }
5365     return ExprError();
5366   }
5367   return OMPIteratorExpr::Create(Context, Context.OMPIteratorTy, IteratorKwLoc,
5368                                  LLoc, RLoc, ID, Helpers);
5369 }
5370 
5371 ExprResult
5372 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
5373                                       Expr *Idx, SourceLocation RLoc) {
5374   Expr *LHSExp = Base;
5375   Expr *RHSExp = Idx;
5376 
5377   ExprValueKind VK = VK_LValue;
5378   ExprObjectKind OK = OK_Ordinary;
5379 
5380   // Per C++ core issue 1213, the result is an xvalue if either operand is
5381   // a non-lvalue array, and an lvalue otherwise.
5382   if (getLangOpts().CPlusPlus11) {
5383     for (auto *Op : {LHSExp, RHSExp}) {
5384       Op = Op->IgnoreImplicit();
5385       if (Op->getType()->isArrayType() && !Op->isLValue())
5386         VK = VK_XValue;
5387     }
5388   }
5389 
5390   // Perform default conversions.
5391   if (!LHSExp->getType()->getAs<VectorType>()) {
5392     ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
5393     if (Result.isInvalid())
5394       return ExprError();
5395     LHSExp = Result.get();
5396   }
5397   ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
5398   if (Result.isInvalid())
5399     return ExprError();
5400   RHSExp = Result.get();
5401 
5402   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
5403 
5404   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
5405   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
5406   // in the subscript position. As a result, we need to derive the array base
5407   // and index from the expression types.
5408   Expr *BaseExpr, *IndexExpr;
5409   QualType ResultType;
5410   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
5411     BaseExpr = LHSExp;
5412     IndexExpr = RHSExp;
5413     ResultType = Context.DependentTy;
5414   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
5415     BaseExpr = LHSExp;
5416     IndexExpr = RHSExp;
5417     ResultType = PTy->getPointeeType();
5418   } else if (const ObjCObjectPointerType *PTy =
5419                LHSTy->getAs<ObjCObjectPointerType>()) {
5420     BaseExpr = LHSExp;
5421     IndexExpr = RHSExp;
5422 
5423     // Use custom logic if this should be the pseudo-object subscript
5424     // expression.
5425     if (!LangOpts.isSubscriptPointerArithmetic())
5426       return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
5427                                           nullptr);
5428 
5429     ResultType = PTy->getPointeeType();
5430   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
5431      // Handle the uncommon case of "123[Ptr]".
5432     BaseExpr = RHSExp;
5433     IndexExpr = LHSExp;
5434     ResultType = PTy->getPointeeType();
5435   } else if (const ObjCObjectPointerType *PTy =
5436                RHSTy->getAs<ObjCObjectPointerType>()) {
5437      // Handle the uncommon case of "123[Ptr]".
5438     BaseExpr = RHSExp;
5439     IndexExpr = LHSExp;
5440     ResultType = PTy->getPointeeType();
5441     if (!LangOpts.isSubscriptPointerArithmetic()) {
5442       Diag(LLoc, diag::err_subscript_nonfragile_interface)
5443         << ResultType << BaseExpr->getSourceRange();
5444       return ExprError();
5445     }
5446   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
5447     BaseExpr = LHSExp;    // vectors: V[123]
5448     IndexExpr = RHSExp;
5449     // We apply C++ DR1213 to vector subscripting too.
5450     if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_RValue) {
5451       ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
5452       if (Materialized.isInvalid())
5453         return ExprError();
5454       LHSExp = Materialized.get();
5455     }
5456     VK = LHSExp->getValueKind();
5457     if (VK != VK_RValue)
5458       OK = OK_VectorComponent;
5459 
5460     ResultType = VTy->getElementType();
5461     QualType BaseType = BaseExpr->getType();
5462     Qualifiers BaseQuals = BaseType.getQualifiers();
5463     Qualifiers MemberQuals = ResultType.getQualifiers();
5464     Qualifiers Combined = BaseQuals + MemberQuals;
5465     if (Combined != MemberQuals)
5466       ResultType = Context.getQualifiedType(ResultType, Combined);
5467   } else if (LHSTy->isArrayType()) {
5468     // If we see an array that wasn't promoted by
5469     // DefaultFunctionArrayLvalueConversion, it must be an array that
5470     // wasn't promoted because of the C90 rule that doesn't
5471     // allow promoting non-lvalue arrays.  Warn, then
5472     // force the promotion here.
5473     Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5474         << LHSExp->getSourceRange();
5475     LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
5476                                CK_ArrayToPointerDecay).get();
5477     LHSTy = LHSExp->getType();
5478 
5479     BaseExpr = LHSExp;
5480     IndexExpr = RHSExp;
5481     ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
5482   } else if (RHSTy->isArrayType()) {
5483     // Same as previous, except for 123[f().a] case
5484     Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5485         << RHSExp->getSourceRange();
5486     RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
5487                                CK_ArrayToPointerDecay).get();
5488     RHSTy = RHSExp->getType();
5489 
5490     BaseExpr = RHSExp;
5491     IndexExpr = LHSExp;
5492     ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
5493   } else {
5494     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
5495        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
5496   }
5497   // C99 6.5.2.1p1
5498   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
5499     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
5500                      << IndexExpr->getSourceRange());
5501 
5502   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5503        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5504          && !IndexExpr->isTypeDependent())
5505     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
5506 
5507   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5508   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5509   // type. Note that Functions are not objects, and that (in C99 parlance)
5510   // incomplete types are not object types.
5511   if (ResultType->isFunctionType()) {
5512     Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type)
5513         << ResultType << BaseExpr->getSourceRange();
5514     return ExprError();
5515   }
5516 
5517   if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
5518     // GNU extension: subscripting on pointer to void
5519     Diag(LLoc, diag::ext_gnu_subscript_void_type)
5520       << BaseExpr->getSourceRange();
5521 
5522     // C forbids expressions of unqualified void type from being l-values.
5523     // See IsCForbiddenLValueType.
5524     if (!ResultType.hasQualifiers()) VK = VK_RValue;
5525   } else if (!ResultType->isDependentType() &&
5526              RequireCompleteSizedType(
5527                  LLoc, ResultType,
5528                  diag::err_subscript_incomplete_or_sizeless_type, BaseExpr))
5529     return ExprError();
5530 
5531   assert(VK == VK_RValue || LangOpts.CPlusPlus ||
5532          !ResultType.isCForbiddenLValueType());
5533 
5534   if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() &&
5535       FunctionScopes.size() > 1) {
5536     if (auto *TT =
5537             LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) {
5538       for (auto I = FunctionScopes.rbegin(),
5539                 E = std::prev(FunctionScopes.rend());
5540            I != E; ++I) {
5541         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
5542         if (CSI == nullptr)
5543           break;
5544         DeclContext *DC = nullptr;
5545         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
5546           DC = LSI->CallOperator;
5547         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
5548           DC = CRSI->TheCapturedDecl;
5549         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
5550           DC = BSI->TheDecl;
5551         if (DC) {
5552           if (DC->containsDecl(TT->getDecl()))
5553             break;
5554           captureVariablyModifiedType(
5555               Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI);
5556         }
5557       }
5558     }
5559   }
5560 
5561   return new (Context)
5562       ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
5563 }
5564 
5565 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
5566                                   ParmVarDecl *Param) {
5567   if (Param->hasUnparsedDefaultArg()) {
5568     // If we've already cleared out the location for the default argument,
5569     // that means we're parsing it right now.
5570     if (!UnparsedDefaultArgLocs.count(Param)) {
5571       Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
5572       Diag(CallLoc, diag::note_recursive_default_argument_used_here);
5573       Param->setInvalidDecl();
5574       return true;
5575     }
5576 
5577     Diag(CallLoc, diag::err_use_of_default_argument_to_function_declared_later)
5578         << FD << cast<CXXRecordDecl>(FD->getDeclContext());
5579     Diag(UnparsedDefaultArgLocs[Param],
5580          diag::note_default_argument_declared_here);
5581     return true;
5582   }
5583 
5584   if (Param->hasUninstantiatedDefaultArg() &&
5585       InstantiateDefaultArgument(CallLoc, FD, Param))
5586     return true;
5587 
5588   assert(Param->hasInit() && "default argument but no initializer?");
5589 
5590   // If the default expression creates temporaries, we need to
5591   // push them to the current stack of expression temporaries so they'll
5592   // be properly destroyed.
5593   // FIXME: We should really be rebuilding the default argument with new
5594   // bound temporaries; see the comment in PR5810.
5595   // We don't need to do that with block decls, though, because
5596   // blocks in default argument expression can never capture anything.
5597   if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
5598     // Set the "needs cleanups" bit regardless of whether there are
5599     // any explicit objects.
5600     Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
5601 
5602     // Append all the objects to the cleanup list.  Right now, this
5603     // should always be a no-op, because blocks in default argument
5604     // expressions should never be able to capture anything.
5605     assert(!Init->getNumObjects() &&
5606            "default argument expression has capturing blocks?");
5607   }
5608 
5609   // We already type-checked the argument, so we know it works.
5610   // Just mark all of the declarations in this potentially-evaluated expression
5611   // as being "referenced".
5612   EnterExpressionEvaluationContext EvalContext(
5613       *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
5614   MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
5615                                    /*SkipLocalVariables=*/true);
5616   return false;
5617 }
5618 
5619 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
5620                                         FunctionDecl *FD, ParmVarDecl *Param) {
5621   assert(Param->hasDefaultArg() && "can't build nonexistent default arg");
5622   if (CheckCXXDefaultArgExpr(CallLoc, FD, Param))
5623     return ExprError();
5624   return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext);
5625 }
5626 
5627 Sema::VariadicCallType
5628 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
5629                           Expr *Fn) {
5630   if (Proto && Proto->isVariadic()) {
5631     if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
5632       return VariadicConstructor;
5633     else if (Fn && Fn->getType()->isBlockPointerType())
5634       return VariadicBlock;
5635     else if (FDecl) {
5636       if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5637         if (Method->isInstance())
5638           return VariadicMethod;
5639     } else if (Fn && Fn->getType() == Context.BoundMemberTy)
5640       return VariadicMethod;
5641     return VariadicFunction;
5642   }
5643   return VariadicDoesNotApply;
5644 }
5645 
5646 namespace {
5647 class FunctionCallCCC final : public FunctionCallFilterCCC {
5648 public:
5649   FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
5650                   unsigned NumArgs, MemberExpr *ME)
5651       : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
5652         FunctionName(FuncName) {}
5653 
5654   bool ValidateCandidate(const TypoCorrection &candidate) override {
5655     if (!candidate.getCorrectionSpecifier() ||
5656         candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
5657       return false;
5658     }
5659 
5660     return FunctionCallFilterCCC::ValidateCandidate(candidate);
5661   }
5662 
5663   std::unique_ptr<CorrectionCandidateCallback> clone() override {
5664     return std::make_unique<FunctionCallCCC>(*this);
5665   }
5666 
5667 private:
5668   const IdentifierInfo *const FunctionName;
5669 };
5670 }
5671 
5672 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
5673                                                FunctionDecl *FDecl,
5674                                                ArrayRef<Expr *> Args) {
5675   MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
5676   DeclarationName FuncName = FDecl->getDeclName();
5677   SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
5678 
5679   FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
5680   if (TypoCorrection Corrected = S.CorrectTypo(
5681           DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
5682           S.getScopeForContext(S.CurContext), nullptr, CCC,
5683           Sema::CTK_ErrorRecovery)) {
5684     if (NamedDecl *ND = Corrected.getFoundDecl()) {
5685       if (Corrected.isOverloaded()) {
5686         OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
5687         OverloadCandidateSet::iterator Best;
5688         for (NamedDecl *CD : Corrected) {
5689           if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
5690             S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
5691                                    OCS);
5692         }
5693         switch (OCS.BestViableFunction(S, NameLoc, Best)) {
5694         case OR_Success:
5695           ND = Best->FoundDecl;
5696           Corrected.setCorrectionDecl(ND);
5697           break;
5698         default:
5699           break;
5700         }
5701       }
5702       ND = ND->getUnderlyingDecl();
5703       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
5704         return Corrected;
5705     }
5706   }
5707   return TypoCorrection();
5708 }
5709 
5710 /// ConvertArgumentsForCall - Converts the arguments specified in
5711 /// Args/NumArgs to the parameter types of the function FDecl with
5712 /// function prototype Proto. Call is the call expression itself, and
5713 /// Fn is the function expression. For a C++ member function, this
5714 /// routine does not attempt to convert the object argument. Returns
5715 /// true if the call is ill-formed.
5716 bool
5717 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
5718                               FunctionDecl *FDecl,
5719                               const FunctionProtoType *Proto,
5720                               ArrayRef<Expr *> Args,
5721                               SourceLocation RParenLoc,
5722                               bool IsExecConfig) {
5723   // Bail out early if calling a builtin with custom typechecking.
5724   if (FDecl)
5725     if (unsigned ID = FDecl->getBuiltinID())
5726       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
5727         return false;
5728 
5729   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
5730   // assignment, to the types of the corresponding parameter, ...
5731   unsigned NumParams = Proto->getNumParams();
5732   bool Invalid = false;
5733   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
5734   unsigned FnKind = Fn->getType()->isBlockPointerType()
5735                        ? 1 /* block */
5736                        : (IsExecConfig ? 3 /* kernel function (exec config) */
5737                                        : 0 /* function */);
5738 
5739   // If too few arguments are available (and we don't have default
5740   // arguments for the remaining parameters), don't make the call.
5741   if (Args.size() < NumParams) {
5742     if (Args.size() < MinArgs) {
5743       TypoCorrection TC;
5744       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5745         unsigned diag_id =
5746             MinArgs == NumParams && !Proto->isVariadic()
5747                 ? diag::err_typecheck_call_too_few_args_suggest
5748                 : diag::err_typecheck_call_too_few_args_at_least_suggest;
5749         diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
5750                                         << static_cast<unsigned>(Args.size())
5751                                         << TC.getCorrectionRange());
5752       } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
5753         Diag(RParenLoc,
5754              MinArgs == NumParams && !Proto->isVariadic()
5755                  ? diag::err_typecheck_call_too_few_args_one
5756                  : diag::err_typecheck_call_too_few_args_at_least_one)
5757             << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
5758       else
5759         Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
5760                             ? diag::err_typecheck_call_too_few_args
5761                             : diag::err_typecheck_call_too_few_args_at_least)
5762             << FnKind << MinArgs << static_cast<unsigned>(Args.size())
5763             << Fn->getSourceRange();
5764 
5765       // Emit the location of the prototype.
5766       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5767         Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
5768 
5769       return true;
5770     }
5771     // We reserve space for the default arguments when we create
5772     // the call expression, before calling ConvertArgumentsForCall.
5773     assert((Call->getNumArgs() == NumParams) &&
5774            "We should have reserved space for the default arguments before!");
5775   }
5776 
5777   // If too many are passed and not variadic, error on the extras and drop
5778   // them.
5779   if (Args.size() > NumParams) {
5780     if (!Proto->isVariadic()) {
5781       TypoCorrection TC;
5782       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5783         unsigned diag_id =
5784             MinArgs == NumParams && !Proto->isVariadic()
5785                 ? diag::err_typecheck_call_too_many_args_suggest
5786                 : diag::err_typecheck_call_too_many_args_at_most_suggest;
5787         diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
5788                                         << static_cast<unsigned>(Args.size())
5789                                         << TC.getCorrectionRange());
5790       } else if (NumParams == 1 && FDecl &&
5791                  FDecl->getParamDecl(0)->getDeclName())
5792         Diag(Args[NumParams]->getBeginLoc(),
5793              MinArgs == NumParams
5794                  ? diag::err_typecheck_call_too_many_args_one
5795                  : diag::err_typecheck_call_too_many_args_at_most_one)
5796             << FnKind << FDecl->getParamDecl(0)
5797             << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
5798             << SourceRange(Args[NumParams]->getBeginLoc(),
5799                            Args.back()->getEndLoc());
5800       else
5801         Diag(Args[NumParams]->getBeginLoc(),
5802              MinArgs == NumParams
5803                  ? diag::err_typecheck_call_too_many_args
5804                  : diag::err_typecheck_call_too_many_args_at_most)
5805             << FnKind << NumParams << static_cast<unsigned>(Args.size())
5806             << Fn->getSourceRange()
5807             << SourceRange(Args[NumParams]->getBeginLoc(),
5808                            Args.back()->getEndLoc());
5809 
5810       // Emit the location of the prototype.
5811       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5812         Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
5813 
5814       // This deletes the extra arguments.
5815       Call->shrinkNumArgs(NumParams);
5816       return true;
5817     }
5818   }
5819   SmallVector<Expr *, 8> AllArgs;
5820   VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
5821 
5822   Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args,
5823                                    AllArgs, CallType);
5824   if (Invalid)
5825     return true;
5826   unsigned TotalNumArgs = AllArgs.size();
5827   for (unsigned i = 0; i < TotalNumArgs; ++i)
5828     Call->setArg(i, AllArgs[i]);
5829 
5830   return false;
5831 }
5832 
5833 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
5834                                   const FunctionProtoType *Proto,
5835                                   unsigned FirstParam, ArrayRef<Expr *> Args,
5836                                   SmallVectorImpl<Expr *> &AllArgs,
5837                                   VariadicCallType CallType, bool AllowExplicit,
5838                                   bool IsListInitialization) {
5839   unsigned NumParams = Proto->getNumParams();
5840   bool Invalid = false;
5841   size_t ArgIx = 0;
5842   // Continue to check argument types (even if we have too few/many args).
5843   for (unsigned i = FirstParam; i < NumParams; i++) {
5844     QualType ProtoArgType = Proto->getParamType(i);
5845 
5846     Expr *Arg;
5847     ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
5848     if (ArgIx < Args.size()) {
5849       Arg = Args[ArgIx++];
5850 
5851       if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType,
5852                               diag::err_call_incomplete_argument, Arg))
5853         return true;
5854 
5855       // Strip the unbridged-cast placeholder expression off, if applicable.
5856       bool CFAudited = false;
5857       if (Arg->getType() == Context.ARCUnbridgedCastTy &&
5858           FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5859           (!Param || !Param->hasAttr<CFConsumedAttr>()))
5860         Arg = stripARCUnbridgedCast(Arg);
5861       else if (getLangOpts().ObjCAutoRefCount &&
5862                FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5863                (!Param || !Param->hasAttr<CFConsumedAttr>()))
5864         CFAudited = true;
5865 
5866       if (Proto->getExtParameterInfo(i).isNoEscape())
5867         if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
5868           BE->getBlockDecl()->setDoesNotEscape();
5869 
5870       InitializedEntity Entity =
5871           Param ? InitializedEntity::InitializeParameter(Context, Param,
5872                                                          ProtoArgType)
5873                 : InitializedEntity::InitializeParameter(
5874                       Context, ProtoArgType, Proto->isParamConsumed(i));
5875 
5876       // Remember that parameter belongs to a CF audited API.
5877       if (CFAudited)
5878         Entity.setParameterCFAudited();
5879 
5880       ExprResult ArgE = PerformCopyInitialization(
5881           Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
5882       if (ArgE.isInvalid())
5883         return true;
5884 
5885       Arg = ArgE.getAs<Expr>();
5886     } else {
5887       assert(Param && "can't use default arguments without a known callee");
5888 
5889       ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
5890       if (ArgExpr.isInvalid())
5891         return true;
5892 
5893       Arg = ArgExpr.getAs<Expr>();
5894     }
5895 
5896     // Check for array bounds violations for each argument to the call. This
5897     // check only triggers warnings when the argument isn't a more complex Expr
5898     // with its own checking, such as a BinaryOperator.
5899     CheckArrayAccess(Arg);
5900 
5901     // Check for violations of C99 static array rules (C99 6.7.5.3p7).
5902     CheckStaticArrayArgument(CallLoc, Param, Arg);
5903 
5904     AllArgs.push_back(Arg);
5905   }
5906 
5907   // If this is a variadic call, handle args passed through "...".
5908   if (CallType != VariadicDoesNotApply) {
5909     // Assume that extern "C" functions with variadic arguments that
5910     // return __unknown_anytype aren't *really* variadic.
5911     if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
5912         FDecl->isExternC()) {
5913       for (Expr *A : Args.slice(ArgIx)) {
5914         QualType paramType; // ignored
5915         ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
5916         Invalid |= arg.isInvalid();
5917         AllArgs.push_back(arg.get());
5918       }
5919 
5920     // Otherwise do argument promotion, (C99 6.5.2.2p7).
5921     } else {
5922       for (Expr *A : Args.slice(ArgIx)) {
5923         ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
5924         Invalid |= Arg.isInvalid();
5925         AllArgs.push_back(Arg.get());
5926       }
5927     }
5928 
5929     // Check for array bounds violations.
5930     for (Expr *A : Args.slice(ArgIx))
5931       CheckArrayAccess(A);
5932   }
5933   return Invalid;
5934 }
5935 
5936 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
5937   TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
5938   if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
5939     TL = DTL.getOriginalLoc();
5940   if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
5941     S.Diag(PVD->getLocation(), diag::note_callee_static_array)
5942       << ATL.getLocalSourceRange();
5943 }
5944 
5945 /// CheckStaticArrayArgument - If the given argument corresponds to a static
5946 /// array parameter, check that it is non-null, and that if it is formed by
5947 /// array-to-pointer decay, the underlying array is sufficiently large.
5948 ///
5949 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
5950 /// array type derivation, then for each call to the function, the value of the
5951 /// corresponding actual argument shall provide access to the first element of
5952 /// an array with at least as many elements as specified by the size expression.
5953 void
5954 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
5955                                ParmVarDecl *Param,
5956                                const Expr *ArgExpr) {
5957   // Static array parameters are not supported in C++.
5958   if (!Param || getLangOpts().CPlusPlus)
5959     return;
5960 
5961   QualType OrigTy = Param->getOriginalType();
5962 
5963   const ArrayType *AT = Context.getAsArrayType(OrigTy);
5964   if (!AT || AT->getSizeModifier() != ArrayType::Static)
5965     return;
5966 
5967   if (ArgExpr->isNullPointerConstant(Context,
5968                                      Expr::NPC_NeverValueDependent)) {
5969     Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
5970     DiagnoseCalleeStaticArrayParam(*this, Param);
5971     return;
5972   }
5973 
5974   const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
5975   if (!CAT)
5976     return;
5977 
5978   const ConstantArrayType *ArgCAT =
5979     Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType());
5980   if (!ArgCAT)
5981     return;
5982 
5983   if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(),
5984                                              ArgCAT->getElementType())) {
5985     if (ArgCAT->getSize().ult(CAT->getSize())) {
5986       Diag(CallLoc, diag::warn_static_array_too_small)
5987           << ArgExpr->getSourceRange()
5988           << (unsigned)ArgCAT->getSize().getZExtValue()
5989           << (unsigned)CAT->getSize().getZExtValue() << 0;
5990       DiagnoseCalleeStaticArrayParam(*this, Param);
5991     }
5992     return;
5993   }
5994 
5995   Optional<CharUnits> ArgSize =
5996       getASTContext().getTypeSizeInCharsIfKnown(ArgCAT);
5997   Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT);
5998   if (ArgSize && ParmSize && *ArgSize < *ParmSize) {
5999     Diag(CallLoc, diag::warn_static_array_too_small)
6000         << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()
6001         << (unsigned)ParmSize->getQuantity() << 1;
6002     DiagnoseCalleeStaticArrayParam(*this, Param);
6003   }
6004 }
6005 
6006 /// Given a function expression of unknown-any type, try to rebuild it
6007 /// to have a function type.
6008 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
6009 
6010 /// Is the given type a placeholder that we need to lower out
6011 /// immediately during argument processing?
6012 static bool isPlaceholderToRemoveAsArg(QualType type) {
6013   // Placeholders are never sugared.
6014   const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
6015   if (!placeholder) return false;
6016 
6017   switch (placeholder->getKind()) {
6018   // Ignore all the non-placeholder types.
6019 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6020   case BuiltinType::Id:
6021 #include "clang/Basic/OpenCLImageTypes.def"
6022 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6023   case BuiltinType::Id:
6024 #include "clang/Basic/OpenCLExtensionTypes.def"
6025   // In practice we'll never use this, since all SVE types are sugared
6026   // via TypedefTypes rather than exposed directly as BuiltinTypes.
6027 #define SVE_TYPE(Name, Id, SingletonId) \
6028   case BuiltinType::Id:
6029 #include "clang/Basic/AArch64SVEACLETypes.def"
6030 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
6031 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
6032 #include "clang/AST/BuiltinTypes.def"
6033     return false;
6034 
6035   // We cannot lower out overload sets; they might validly be resolved
6036   // by the call machinery.
6037   case BuiltinType::Overload:
6038     return false;
6039 
6040   // Unbridged casts in ARC can be handled in some call positions and
6041   // should be left in place.
6042   case BuiltinType::ARCUnbridgedCast:
6043     return false;
6044 
6045   // Pseudo-objects should be converted as soon as possible.
6046   case BuiltinType::PseudoObject:
6047     return true;
6048 
6049   // The debugger mode could theoretically but currently does not try
6050   // to resolve unknown-typed arguments based on known parameter types.
6051   case BuiltinType::UnknownAny:
6052     return true;
6053 
6054   // These are always invalid as call arguments and should be reported.
6055   case BuiltinType::BoundMember:
6056   case BuiltinType::BuiltinFn:
6057   case BuiltinType::IncompleteMatrixIdx:
6058   case BuiltinType::OMPArraySection:
6059   case BuiltinType::OMPArrayShaping:
6060   case BuiltinType::OMPIterator:
6061     return true;
6062 
6063   }
6064   llvm_unreachable("bad builtin type kind");
6065 }
6066 
6067 /// Check an argument list for placeholders that we won't try to
6068 /// handle later.
6069 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
6070   // Apply this processing to all the arguments at once instead of
6071   // dying at the first failure.
6072   bool hasInvalid = false;
6073   for (size_t i = 0, e = args.size(); i != e; i++) {
6074     if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
6075       ExprResult result = S.CheckPlaceholderExpr(args[i]);
6076       if (result.isInvalid()) hasInvalid = true;
6077       else args[i] = result.get();
6078     }
6079   }
6080   return hasInvalid;
6081 }
6082 
6083 /// If a builtin function has a pointer argument with no explicit address
6084 /// space, then it should be able to accept a pointer to any address
6085 /// space as input.  In order to do this, we need to replace the
6086 /// standard builtin declaration with one that uses the same address space
6087 /// as the call.
6088 ///
6089 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
6090 ///                  it does not contain any pointer arguments without
6091 ///                  an address space qualifer.  Otherwise the rewritten
6092 ///                  FunctionDecl is returned.
6093 /// TODO: Handle pointer return types.
6094 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
6095                                                 FunctionDecl *FDecl,
6096                                                 MultiExprArg ArgExprs) {
6097 
6098   QualType DeclType = FDecl->getType();
6099   const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
6100 
6101   if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT ||
6102       ArgExprs.size() < FT->getNumParams())
6103     return nullptr;
6104 
6105   bool NeedsNewDecl = false;
6106   unsigned i = 0;
6107   SmallVector<QualType, 8> OverloadParams;
6108 
6109   for (QualType ParamType : FT->param_types()) {
6110 
6111     // Convert array arguments to pointer to simplify type lookup.
6112     ExprResult ArgRes =
6113         Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
6114     if (ArgRes.isInvalid())
6115       return nullptr;
6116     Expr *Arg = ArgRes.get();
6117     QualType ArgType = Arg->getType();
6118     if (!ParamType->isPointerType() ||
6119         ParamType.hasAddressSpace() ||
6120         !ArgType->isPointerType() ||
6121         !ArgType->getPointeeType().hasAddressSpace()) {
6122       OverloadParams.push_back(ParamType);
6123       continue;
6124     }
6125 
6126     QualType PointeeType = ParamType->getPointeeType();
6127     if (PointeeType.hasAddressSpace())
6128       continue;
6129 
6130     NeedsNewDecl = true;
6131     LangAS AS = ArgType->getPointeeType().getAddressSpace();
6132 
6133     PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
6134     OverloadParams.push_back(Context.getPointerType(PointeeType));
6135   }
6136 
6137   if (!NeedsNewDecl)
6138     return nullptr;
6139 
6140   FunctionProtoType::ExtProtoInfo EPI;
6141   EPI.Variadic = FT->isVariadic();
6142   QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
6143                                                 OverloadParams, EPI);
6144   DeclContext *Parent = FDecl->getParent();
6145   FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
6146                                                     FDecl->getLocation(),
6147                                                     FDecl->getLocation(),
6148                                                     FDecl->getIdentifier(),
6149                                                     OverloadTy,
6150                                                     /*TInfo=*/nullptr,
6151                                                     SC_Extern, false,
6152                                                     /*hasPrototype=*/true);
6153   SmallVector<ParmVarDecl*, 16> Params;
6154   FT = cast<FunctionProtoType>(OverloadTy);
6155   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
6156     QualType ParamType = FT->getParamType(i);
6157     ParmVarDecl *Parm =
6158         ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
6159                                 SourceLocation(), nullptr, ParamType,
6160                                 /*TInfo=*/nullptr, SC_None, nullptr);
6161     Parm->setScopeInfo(0, i);
6162     Params.push_back(Parm);
6163   }
6164   OverloadDecl->setParams(Params);
6165   Sema->mergeDeclAttributes(OverloadDecl, FDecl);
6166   return OverloadDecl;
6167 }
6168 
6169 static void checkDirectCallValidity(Sema &S, const Expr *Fn,
6170                                     FunctionDecl *Callee,
6171                                     MultiExprArg ArgExprs) {
6172   // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
6173   // similar attributes) really don't like it when functions are called with an
6174   // invalid number of args.
6175   if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
6176                          /*PartialOverloading=*/false) &&
6177       !Callee->isVariadic())
6178     return;
6179   if (Callee->getMinRequiredArguments() > ArgExprs.size())
6180     return;
6181 
6182   if (const EnableIfAttr *Attr =
6183           S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) {
6184     S.Diag(Fn->getBeginLoc(),
6185            isa<CXXMethodDecl>(Callee)
6186                ? diag::err_ovl_no_viable_member_function_in_call
6187                : diag::err_ovl_no_viable_function_in_call)
6188         << Callee << Callee->getSourceRange();
6189     S.Diag(Callee->getLocation(),
6190            diag::note_ovl_candidate_disabled_by_function_cond_attr)
6191         << Attr->getCond()->getSourceRange() << Attr->getMessage();
6192     return;
6193   }
6194 }
6195 
6196 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(
6197     const UnresolvedMemberExpr *const UME, Sema &S) {
6198 
6199   const auto GetFunctionLevelDCIfCXXClass =
6200       [](Sema &S) -> const CXXRecordDecl * {
6201     const DeclContext *const DC = S.getFunctionLevelDeclContext();
6202     if (!DC || !DC->getParent())
6203       return nullptr;
6204 
6205     // If the call to some member function was made from within a member
6206     // function body 'M' return return 'M's parent.
6207     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
6208       return MD->getParent()->getCanonicalDecl();
6209     // else the call was made from within a default member initializer of a
6210     // class, so return the class.
6211     if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
6212       return RD->getCanonicalDecl();
6213     return nullptr;
6214   };
6215   // If our DeclContext is neither a member function nor a class (in the
6216   // case of a lambda in a default member initializer), we can't have an
6217   // enclosing 'this'.
6218 
6219   const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
6220   if (!CurParentClass)
6221     return false;
6222 
6223   // The naming class for implicit member functions call is the class in which
6224   // name lookup starts.
6225   const CXXRecordDecl *const NamingClass =
6226       UME->getNamingClass()->getCanonicalDecl();
6227   assert(NamingClass && "Must have naming class even for implicit access");
6228 
6229   // If the unresolved member functions were found in a 'naming class' that is
6230   // related (either the same or derived from) to the class that contains the
6231   // member function that itself contained the implicit member access.
6232 
6233   return CurParentClass == NamingClass ||
6234          CurParentClass->isDerivedFrom(NamingClass);
6235 }
6236 
6237 static void
6238 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
6239     Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
6240 
6241   if (!UME)
6242     return;
6243 
6244   LambdaScopeInfo *const CurLSI = S.getCurLambda();
6245   // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
6246   // already been captured, or if this is an implicit member function call (if
6247   // it isn't, an attempt to capture 'this' should already have been made).
6248   if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
6249       !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
6250     return;
6251 
6252   // Check if the naming class in which the unresolved members were found is
6253   // related (same as or is a base of) to the enclosing class.
6254 
6255   if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S))
6256     return;
6257 
6258 
6259   DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
6260   // If the enclosing function is not dependent, then this lambda is
6261   // capture ready, so if we can capture this, do so.
6262   if (!EnclosingFunctionCtx->isDependentContext()) {
6263     // If the current lambda and all enclosing lambdas can capture 'this' -
6264     // then go ahead and capture 'this' (since our unresolved overload set
6265     // contains at least one non-static member function).
6266     if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
6267       S.CheckCXXThisCapture(CallLoc);
6268   } else if (S.CurContext->isDependentContext()) {
6269     // ... since this is an implicit member reference, that might potentially
6270     // involve a 'this' capture, mark 'this' for potential capture in
6271     // enclosing lambdas.
6272     if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
6273       CurLSI->addPotentialThisCapture(CallLoc);
6274   }
6275 }
6276 
6277 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
6278                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
6279                                Expr *ExecConfig) {
6280   ExprResult Call =
6281       BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig);
6282   if (Call.isInvalid())
6283     return Call;
6284 
6285   // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier
6286   // language modes.
6287   if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) {
6288     if (ULE->hasExplicitTemplateArgs() &&
6289         ULE->decls_begin() == ULE->decls_end()) {
6290       Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus20
6291                                  ? diag::warn_cxx17_compat_adl_only_template_id
6292                                  : diag::ext_adl_only_template_id)
6293           << ULE->getName();
6294     }
6295   }
6296 
6297   if (LangOpts.OpenMP)
6298     Call = ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc,
6299                            ExecConfig);
6300 
6301   return Call;
6302 }
6303 
6304 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments.
6305 /// This provides the location of the left/right parens and a list of comma
6306 /// locations.
6307 ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
6308                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
6309                                Expr *ExecConfig, bool IsExecConfig) {
6310   // Since this might be a postfix expression, get rid of ParenListExprs.
6311   ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
6312   if (Result.isInvalid()) return ExprError();
6313   Fn = Result.get();
6314 
6315   if (checkArgsForPlaceholders(*this, ArgExprs))
6316     return ExprError();
6317 
6318   if (getLangOpts().CPlusPlus) {
6319     // If this is a pseudo-destructor expression, build the call immediately.
6320     if (isa<CXXPseudoDestructorExpr>(Fn)) {
6321       if (!ArgExprs.empty()) {
6322         // Pseudo-destructor calls should not have any arguments.
6323         Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args)
6324             << FixItHint::CreateRemoval(
6325                    SourceRange(ArgExprs.front()->getBeginLoc(),
6326                                ArgExprs.back()->getEndLoc()));
6327       }
6328 
6329       return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy,
6330                               VK_RValue, RParenLoc, CurFPFeatureOverrides());
6331     }
6332     if (Fn->getType() == Context.PseudoObjectTy) {
6333       ExprResult result = CheckPlaceholderExpr(Fn);
6334       if (result.isInvalid()) return ExprError();
6335       Fn = result.get();
6336     }
6337 
6338     // Determine whether this is a dependent call inside a C++ template,
6339     // in which case we won't do any semantic analysis now.
6340     if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) {
6341       if (ExecConfig) {
6342         return CUDAKernelCallExpr::Create(
6343             Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
6344             Context.DependentTy, VK_RValue, RParenLoc, CurFPFeatureOverrides());
6345       } else {
6346 
6347         tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
6348             *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
6349             Fn->getBeginLoc());
6350 
6351         return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6352                                 VK_RValue, RParenLoc, CurFPFeatureOverrides());
6353       }
6354     }
6355 
6356     // Determine whether this is a call to an object (C++ [over.call.object]).
6357     if (Fn->getType()->isRecordType())
6358       return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
6359                                           RParenLoc);
6360 
6361     if (Fn->getType() == Context.UnknownAnyTy) {
6362       ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6363       if (result.isInvalid()) return ExprError();
6364       Fn = result.get();
6365     }
6366 
6367     if (Fn->getType() == Context.BoundMemberTy) {
6368       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6369                                        RParenLoc);
6370     }
6371   }
6372 
6373   // Check for overloaded calls.  This can happen even in C due to extensions.
6374   if (Fn->getType() == Context.OverloadTy) {
6375     OverloadExpr::FindResult find = OverloadExpr::find(Fn);
6376 
6377     // We aren't supposed to apply this logic if there's an '&' involved.
6378     if (!find.HasFormOfMemberPointer) {
6379       if (Expr::hasAnyTypeDependentArguments(ArgExprs))
6380         return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6381                                 VK_RValue, RParenLoc, CurFPFeatureOverrides());
6382       OverloadExpr *ovl = find.Expression;
6383       if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
6384         return BuildOverloadedCallExpr(
6385             Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6386             /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
6387       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6388                                        RParenLoc);
6389     }
6390   }
6391 
6392   // If we're directly calling a function, get the appropriate declaration.
6393   if (Fn->getType() == Context.UnknownAnyTy) {
6394     ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6395     if (result.isInvalid()) return ExprError();
6396     Fn = result.get();
6397   }
6398 
6399   Expr *NakedFn = Fn->IgnoreParens();
6400 
6401   bool CallingNDeclIndirectly = false;
6402   NamedDecl *NDecl = nullptr;
6403   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
6404     if (UnOp->getOpcode() == UO_AddrOf) {
6405       CallingNDeclIndirectly = true;
6406       NakedFn = UnOp->getSubExpr()->IgnoreParens();
6407     }
6408   }
6409 
6410   if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
6411     NDecl = DRE->getDecl();
6412 
6413     FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
6414     if (FDecl && FDecl->getBuiltinID()) {
6415       // Rewrite the function decl for this builtin by replacing parameters
6416       // with no explicit address space with the address space of the arguments
6417       // in ArgExprs.
6418       if ((FDecl =
6419                rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
6420         NDecl = FDecl;
6421         Fn = DeclRefExpr::Create(
6422             Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
6423             SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl,
6424             nullptr, DRE->isNonOdrUse());
6425       }
6426     }
6427   } else if (isa<MemberExpr>(NakedFn))
6428     NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
6429 
6430   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
6431     if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
6432                                       FD, /*Complain=*/true, Fn->getBeginLoc()))
6433       return ExprError();
6434 
6435     if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn))
6436       return ExprError();
6437 
6438     checkDirectCallValidity(*this, Fn, FD, ArgExprs);
6439   }
6440 
6441   return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
6442                                ExecConfig, IsExecConfig);
6443 }
6444 
6445 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
6446 ///
6447 /// __builtin_astype( value, dst type )
6448 ///
6449 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
6450                                  SourceLocation BuiltinLoc,
6451                                  SourceLocation RParenLoc) {
6452   ExprValueKind VK = VK_RValue;
6453   ExprObjectKind OK = OK_Ordinary;
6454   QualType DstTy = GetTypeFromParser(ParsedDestTy);
6455   QualType SrcTy = E->getType();
6456   if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
6457     return ExprError(Diag(BuiltinLoc,
6458                           diag::err_invalid_astype_of_different_size)
6459                      << DstTy
6460                      << SrcTy
6461                      << E->getSourceRange());
6462   return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
6463 }
6464 
6465 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
6466 /// provided arguments.
6467 ///
6468 /// __builtin_convertvector( value, dst type )
6469 ///
6470 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
6471                                         SourceLocation BuiltinLoc,
6472                                         SourceLocation RParenLoc) {
6473   TypeSourceInfo *TInfo;
6474   GetTypeFromParser(ParsedDestTy, &TInfo);
6475   return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
6476 }
6477 
6478 /// BuildResolvedCallExpr - Build a call to a resolved expression,
6479 /// i.e. an expression not of \p OverloadTy.  The expression should
6480 /// unary-convert to an expression of function-pointer or
6481 /// block-pointer type.
6482 ///
6483 /// \param NDecl the declaration being called, if available
6484 ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
6485                                        SourceLocation LParenLoc,
6486                                        ArrayRef<Expr *> Args,
6487                                        SourceLocation RParenLoc, Expr *Config,
6488                                        bool IsExecConfig, ADLCallKind UsesADL) {
6489   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
6490   unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
6491 
6492   // Functions with 'interrupt' attribute cannot be called directly.
6493   if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
6494     Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
6495     return ExprError();
6496   }
6497 
6498   // Interrupt handlers don't save off the VFP regs automatically on ARM,
6499   // so there's some risk when calling out to non-interrupt handler functions
6500   // that the callee might not preserve them. This is easy to diagnose here,
6501   // but can be very challenging to debug.
6502   if (auto *Caller = getCurFunctionDecl())
6503     if (Caller->hasAttr<ARMInterruptAttr>()) {
6504       bool VFP = Context.getTargetInfo().hasFeature("vfp");
6505       if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>()))
6506         Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention);
6507     }
6508 
6509   // Promote the function operand.
6510   // We special-case function promotion here because we only allow promoting
6511   // builtin functions to function pointers in the callee of a call.
6512   ExprResult Result;
6513   QualType ResultTy;
6514   if (BuiltinID &&
6515       Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
6516     // Extract the return type from the (builtin) function pointer type.
6517     // FIXME Several builtins still have setType in
6518     // Sema::CheckBuiltinFunctionCall. One should review their definitions in
6519     // Builtins.def to ensure they are correct before removing setType calls.
6520     QualType FnPtrTy = Context.getPointerType(FDecl->getType());
6521     Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get();
6522     ResultTy = FDecl->getCallResultType();
6523   } else {
6524     Result = CallExprUnaryConversions(Fn);
6525     ResultTy = Context.BoolTy;
6526   }
6527   if (Result.isInvalid())
6528     return ExprError();
6529   Fn = Result.get();
6530 
6531   // Check for a valid function type, but only if it is not a builtin which
6532   // requires custom type checking. These will be handled by
6533   // CheckBuiltinFunctionCall below just after creation of the call expression.
6534   const FunctionType *FuncT = nullptr;
6535   if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
6536   retry:
6537     if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
6538       // C99 6.5.2.2p1 - "The expression that denotes the called function shall
6539       // have type pointer to function".
6540       FuncT = PT->getPointeeType()->getAs<FunctionType>();
6541       if (!FuncT)
6542         return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
6543                          << Fn->getType() << Fn->getSourceRange());
6544     } else if (const BlockPointerType *BPT =
6545                    Fn->getType()->getAs<BlockPointerType>()) {
6546       FuncT = BPT->getPointeeType()->castAs<FunctionType>();
6547     } else {
6548       // Handle calls to expressions of unknown-any type.
6549       if (Fn->getType() == Context.UnknownAnyTy) {
6550         ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
6551         if (rewrite.isInvalid())
6552           return ExprError();
6553         Fn = rewrite.get();
6554         goto retry;
6555       }
6556 
6557       return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
6558                        << Fn->getType() << Fn->getSourceRange());
6559     }
6560   }
6561 
6562   // Get the number of parameters in the function prototype, if any.
6563   // We will allocate space for max(Args.size(), NumParams) arguments
6564   // in the call expression.
6565   const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT);
6566   unsigned NumParams = Proto ? Proto->getNumParams() : 0;
6567 
6568   CallExpr *TheCall;
6569   if (Config) {
6570     assert(UsesADL == ADLCallKind::NotADL &&
6571            "CUDAKernelCallExpr should not use ADL");
6572     TheCall = CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config),
6573                                          Args, ResultTy, VK_RValue, RParenLoc,
6574                                          CurFPFeatureOverrides(), NumParams);
6575   } else {
6576     TheCall =
6577         CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue, RParenLoc,
6578                          CurFPFeatureOverrides(), NumParams, UsesADL);
6579   }
6580 
6581   if (!getLangOpts().CPlusPlus) {
6582     // Forget about the nulled arguments since typo correction
6583     // do not handle them well.
6584     TheCall->shrinkNumArgs(Args.size());
6585     // C cannot always handle TypoExpr nodes in builtin calls and direct
6586     // function calls as their argument checking don't necessarily handle
6587     // dependent types properly, so make sure any TypoExprs have been
6588     // dealt with.
6589     ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
6590     if (!Result.isUsable()) return ExprError();
6591     CallExpr *TheOldCall = TheCall;
6592     TheCall = dyn_cast<CallExpr>(Result.get());
6593     bool CorrectedTypos = TheCall != TheOldCall;
6594     if (!TheCall) return Result;
6595     Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
6596 
6597     // A new call expression node was created if some typos were corrected.
6598     // However it may not have been constructed with enough storage. In this
6599     // case, rebuild the node with enough storage. The waste of space is
6600     // immaterial since this only happens when some typos were corrected.
6601     if (CorrectedTypos && Args.size() < NumParams) {
6602       if (Config)
6603         TheCall = CUDAKernelCallExpr::Create(
6604             Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_RValue,
6605             RParenLoc, CurFPFeatureOverrides(), NumParams);
6606       else
6607         TheCall =
6608             CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue, RParenLoc,
6609                              CurFPFeatureOverrides(), NumParams, UsesADL);
6610     }
6611     // We can now handle the nulled arguments for the default arguments.
6612     TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams));
6613   }
6614 
6615   // Bail out early if calling a builtin with custom type checking.
6616   if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
6617     return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
6618 
6619   if (getLangOpts().CUDA) {
6620     if (Config) {
6621       // CUDA: Kernel calls must be to global functions
6622       if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
6623         return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
6624             << FDecl << Fn->getSourceRange());
6625 
6626       // CUDA: Kernel function must have 'void' return type
6627       if (!FuncT->getReturnType()->isVoidType() &&
6628           !FuncT->getReturnType()->getAs<AutoType>() &&
6629           !FuncT->getReturnType()->isInstantiationDependentType())
6630         return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
6631             << Fn->getType() << Fn->getSourceRange());
6632     } else {
6633       // CUDA: Calls to global functions must be configured
6634       if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
6635         return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
6636             << FDecl << Fn->getSourceRange());
6637     }
6638   }
6639 
6640   // Check for a valid return type
6641   if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall,
6642                           FDecl))
6643     return ExprError();
6644 
6645   // We know the result type of the call, set it.
6646   TheCall->setType(FuncT->getCallResultType(Context));
6647   TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
6648 
6649   if (Proto) {
6650     if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
6651                                 IsExecConfig))
6652       return ExprError();
6653   } else {
6654     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
6655 
6656     if (FDecl) {
6657       // Check if we have too few/too many template arguments, based
6658       // on our knowledge of the function definition.
6659       const FunctionDecl *Def = nullptr;
6660       if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
6661         Proto = Def->getType()->getAs<FunctionProtoType>();
6662        if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
6663           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
6664           << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
6665       }
6666 
6667       // If the function we're calling isn't a function prototype, but we have
6668       // a function prototype from a prior declaratiom, use that prototype.
6669       if (!FDecl->hasPrototype())
6670         Proto = FDecl->getType()->getAs<FunctionProtoType>();
6671     }
6672 
6673     // Promote the arguments (C99 6.5.2.2p6).
6674     for (unsigned i = 0, e = Args.size(); i != e; i++) {
6675       Expr *Arg = Args[i];
6676 
6677       if (Proto && i < Proto->getNumParams()) {
6678         InitializedEntity Entity = InitializedEntity::InitializeParameter(
6679             Context, Proto->getParamType(i), Proto->isParamConsumed(i));
6680         ExprResult ArgE =
6681             PerformCopyInitialization(Entity, SourceLocation(), Arg);
6682         if (ArgE.isInvalid())
6683           return true;
6684 
6685         Arg = ArgE.getAs<Expr>();
6686 
6687       } else {
6688         ExprResult ArgE = DefaultArgumentPromotion(Arg);
6689 
6690         if (ArgE.isInvalid())
6691           return true;
6692 
6693         Arg = ArgE.getAs<Expr>();
6694       }
6695 
6696       if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(),
6697                               diag::err_call_incomplete_argument, Arg))
6698         return ExprError();
6699 
6700       TheCall->setArg(i, Arg);
6701     }
6702   }
6703 
6704   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
6705     if (!Method->isStatic())
6706       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
6707         << Fn->getSourceRange());
6708 
6709   // Check for sentinels
6710   if (NDecl)
6711     DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
6712 
6713   // Warn for unions passing across security boundary (CMSE).
6714   if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) {
6715     for (unsigned i = 0, e = Args.size(); i != e; i++) {
6716       if (const auto *RT =
6717               dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) {
6718         if (RT->getDecl()->isOrContainsUnion())
6719           Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union)
6720               << 0 << i;
6721       }
6722     }
6723   }
6724 
6725   // Do special checking on direct calls to functions.
6726   if (FDecl) {
6727     if (CheckFunctionCall(FDecl, TheCall, Proto))
6728       return ExprError();
6729 
6730     checkFortifiedBuiltinMemoryFunction(FDecl, TheCall);
6731 
6732     if (BuiltinID)
6733       return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
6734   } else if (NDecl) {
6735     if (CheckPointerCall(NDecl, TheCall, Proto))
6736       return ExprError();
6737   } else {
6738     if (CheckOtherCall(TheCall, Proto))
6739       return ExprError();
6740   }
6741 
6742   return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl);
6743 }
6744 
6745 ExprResult
6746 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
6747                            SourceLocation RParenLoc, Expr *InitExpr) {
6748   assert(Ty && "ActOnCompoundLiteral(): missing type");
6749   assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
6750 
6751   TypeSourceInfo *TInfo;
6752   QualType literalType = GetTypeFromParser(Ty, &TInfo);
6753   if (!TInfo)
6754     TInfo = Context.getTrivialTypeSourceInfo(literalType);
6755 
6756   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
6757 }
6758 
6759 ExprResult
6760 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
6761                                SourceLocation RParenLoc, Expr *LiteralExpr) {
6762   QualType literalType = TInfo->getType();
6763 
6764   if (literalType->isArrayType()) {
6765     if (RequireCompleteSizedType(
6766             LParenLoc, Context.getBaseElementType(literalType),
6767             diag::err_array_incomplete_or_sizeless_type,
6768             SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
6769       return ExprError();
6770     if (literalType->isVariableArrayType())
6771       return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
6772         << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
6773   } else if (!literalType->isDependentType() &&
6774              RequireCompleteType(LParenLoc, literalType,
6775                diag::err_typecheck_decl_incomplete_type,
6776                SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
6777     return ExprError();
6778 
6779   InitializedEntity Entity
6780     = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
6781   InitializationKind Kind
6782     = InitializationKind::CreateCStyleCast(LParenLoc,
6783                                            SourceRange(LParenLoc, RParenLoc),
6784                                            /*InitList=*/true);
6785   InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
6786   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
6787                                       &literalType);
6788   if (Result.isInvalid())
6789     return ExprError();
6790   LiteralExpr = Result.get();
6791 
6792   bool isFileScope = !CurContext->isFunctionOrMethod();
6793 
6794   // In C, compound literals are l-values for some reason.
6795   // For GCC compatibility, in C++, file-scope array compound literals with
6796   // constant initializers are also l-values, and compound literals are
6797   // otherwise prvalues.
6798   //
6799   // (GCC also treats C++ list-initialized file-scope array prvalues with
6800   // constant initializers as l-values, but that's non-conforming, so we don't
6801   // follow it there.)
6802   //
6803   // FIXME: It would be better to handle the lvalue cases as materializing and
6804   // lifetime-extending a temporary object, but our materialized temporaries
6805   // representation only supports lifetime extension from a variable, not "out
6806   // of thin air".
6807   // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
6808   // is bound to the result of applying array-to-pointer decay to the compound
6809   // literal.
6810   // FIXME: GCC supports compound literals of reference type, which should
6811   // obviously have a value kind derived from the kind of reference involved.
6812   ExprValueKind VK =
6813       (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
6814           ? VK_RValue
6815           : VK_LValue;
6816 
6817   if (isFileScope)
6818     if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr))
6819       for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {
6820         Expr *Init = ILE->getInit(i);
6821         ILE->setInit(i, ConstantExpr::Create(Context, Init));
6822       }
6823 
6824   auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
6825                                               VK, LiteralExpr, isFileScope);
6826   if (isFileScope) {
6827     if (!LiteralExpr->isTypeDependent() &&
6828         !LiteralExpr->isValueDependent() &&
6829         !literalType->isDependentType()) // C99 6.5.2.5p3
6830       if (CheckForConstantInitializer(LiteralExpr, literalType))
6831         return ExprError();
6832   } else if (literalType.getAddressSpace() != LangAS::opencl_private &&
6833              literalType.getAddressSpace() != LangAS::Default) {
6834     // Embedded-C extensions to C99 6.5.2.5:
6835     //   "If the compound literal occurs inside the body of a function, the
6836     //   type name shall not be qualified by an address-space qualifier."
6837     Diag(LParenLoc, diag::err_compound_literal_with_address_space)
6838       << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
6839     return ExprError();
6840   }
6841 
6842   if (!isFileScope && !getLangOpts().CPlusPlus) {
6843     // Compound literals that have automatic storage duration are destroyed at
6844     // the end of the scope in C; in C++, they're just temporaries.
6845 
6846     // Emit diagnostics if it is or contains a C union type that is non-trivial
6847     // to destruct.
6848     if (E->getType().hasNonTrivialToPrimitiveDestructCUnion())
6849       checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
6850                             NTCUC_CompoundLiteral, NTCUK_Destruct);
6851 
6852     // Diagnose jumps that enter or exit the lifetime of the compound literal.
6853     if (literalType.isDestructedType()) {
6854       Cleanup.setExprNeedsCleanups(true);
6855       ExprCleanupObjects.push_back(E);
6856       getCurFunction()->setHasBranchProtectedScope();
6857     }
6858   }
6859 
6860   if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
6861       E->getType().hasNonTrivialToPrimitiveCopyCUnion())
6862     checkNonTrivialCUnionInInitializer(E->getInitializer(),
6863                                        E->getInitializer()->getExprLoc());
6864 
6865   return MaybeBindToTemporary(E);
6866 }
6867 
6868 ExprResult
6869 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
6870                     SourceLocation RBraceLoc) {
6871   // Only produce each kind of designated initialization diagnostic once.
6872   SourceLocation FirstDesignator;
6873   bool DiagnosedArrayDesignator = false;
6874   bool DiagnosedNestedDesignator = false;
6875   bool DiagnosedMixedDesignator = false;
6876 
6877   // Check that any designated initializers are syntactically valid in the
6878   // current language mode.
6879   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
6880     if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) {
6881       if (FirstDesignator.isInvalid())
6882         FirstDesignator = DIE->getBeginLoc();
6883 
6884       if (!getLangOpts().CPlusPlus)
6885         break;
6886 
6887       if (!DiagnosedNestedDesignator && DIE->size() > 1) {
6888         DiagnosedNestedDesignator = true;
6889         Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested)
6890           << DIE->getDesignatorsSourceRange();
6891       }
6892 
6893       for (auto &Desig : DIE->designators()) {
6894         if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) {
6895           DiagnosedArrayDesignator = true;
6896           Diag(Desig.getBeginLoc(), diag::ext_designated_init_array)
6897             << Desig.getSourceRange();
6898         }
6899       }
6900 
6901       if (!DiagnosedMixedDesignator &&
6902           !isa<DesignatedInitExpr>(InitArgList[0])) {
6903         DiagnosedMixedDesignator = true;
6904         Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
6905           << DIE->getSourceRange();
6906         Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed)
6907           << InitArgList[0]->getSourceRange();
6908       }
6909     } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator &&
6910                isa<DesignatedInitExpr>(InitArgList[0])) {
6911       DiagnosedMixedDesignator = true;
6912       auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]);
6913       Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
6914         << DIE->getSourceRange();
6915       Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed)
6916         << InitArgList[I]->getSourceRange();
6917     }
6918   }
6919 
6920   if (FirstDesignator.isValid()) {
6921     // Only diagnose designated initiaization as a C++20 extension if we didn't
6922     // already diagnose use of (non-C++20) C99 designator syntax.
6923     if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator &&
6924         !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) {
6925       Diag(FirstDesignator, getLangOpts().CPlusPlus20
6926                                 ? diag::warn_cxx17_compat_designated_init
6927                                 : diag::ext_cxx_designated_init);
6928     } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) {
6929       Diag(FirstDesignator, diag::ext_designated_init);
6930     }
6931   }
6932 
6933   return BuildInitList(LBraceLoc, InitArgList, RBraceLoc);
6934 }
6935 
6936 ExprResult
6937 Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
6938                     SourceLocation RBraceLoc) {
6939   // Semantic analysis for initializers is done by ActOnDeclarator() and
6940   // CheckInitializer() - it requires knowledge of the object being initialized.
6941 
6942   // Immediately handle non-overload placeholders.  Overloads can be
6943   // resolved contextually, but everything else here can't.
6944   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
6945     if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
6946       ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
6947 
6948       // Ignore failures; dropping the entire initializer list because
6949       // of one failure would be terrible for indexing/etc.
6950       if (result.isInvalid()) continue;
6951 
6952       InitArgList[I] = result.get();
6953     }
6954   }
6955 
6956   InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
6957                                                RBraceLoc);
6958   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
6959   return E;
6960 }
6961 
6962 /// Do an explicit extend of the given block pointer if we're in ARC.
6963 void Sema::maybeExtendBlockObject(ExprResult &E) {
6964   assert(E.get()->getType()->isBlockPointerType());
6965   assert(E.get()->isRValue());
6966 
6967   // Only do this in an r-value context.
6968   if (!getLangOpts().ObjCAutoRefCount) return;
6969 
6970   E = ImplicitCastExpr::Create(
6971       Context, E.get()->getType(), CK_ARCExtendBlockObject, E.get(),
6972       /*base path*/ nullptr, VK_RValue, FPOptionsOverride());
6973   Cleanup.setExprNeedsCleanups(true);
6974 }
6975 
6976 /// Prepare a conversion of the given expression to an ObjC object
6977 /// pointer type.
6978 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
6979   QualType type = E.get()->getType();
6980   if (type->isObjCObjectPointerType()) {
6981     return CK_BitCast;
6982   } else if (type->isBlockPointerType()) {
6983     maybeExtendBlockObject(E);
6984     return CK_BlockPointerToObjCPointerCast;
6985   } else {
6986     assert(type->isPointerType());
6987     return CK_CPointerToObjCPointerCast;
6988   }
6989 }
6990 
6991 /// Prepares for a scalar cast, performing all the necessary stages
6992 /// except the final cast and returning the kind required.
6993 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
6994   // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
6995   // Also, callers should have filtered out the invalid cases with
6996   // pointers.  Everything else should be possible.
6997 
6998   QualType SrcTy = Src.get()->getType();
6999   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
7000     return CK_NoOp;
7001 
7002   switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
7003   case Type::STK_MemberPointer:
7004     llvm_unreachable("member pointer type in C");
7005 
7006   case Type::STK_CPointer:
7007   case Type::STK_BlockPointer:
7008   case Type::STK_ObjCObjectPointer:
7009     switch (DestTy->getScalarTypeKind()) {
7010     case Type::STK_CPointer: {
7011       LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
7012       LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
7013       if (SrcAS != DestAS)
7014         return CK_AddressSpaceConversion;
7015       if (Context.hasCvrSimilarType(SrcTy, DestTy))
7016         return CK_NoOp;
7017       return CK_BitCast;
7018     }
7019     case Type::STK_BlockPointer:
7020       return (SrcKind == Type::STK_BlockPointer
7021                 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
7022     case Type::STK_ObjCObjectPointer:
7023       if (SrcKind == Type::STK_ObjCObjectPointer)
7024         return CK_BitCast;
7025       if (SrcKind == Type::STK_CPointer)
7026         return CK_CPointerToObjCPointerCast;
7027       maybeExtendBlockObject(Src);
7028       return CK_BlockPointerToObjCPointerCast;
7029     case Type::STK_Bool:
7030       return CK_PointerToBoolean;
7031     case Type::STK_Integral:
7032       return CK_PointerToIntegral;
7033     case Type::STK_Floating:
7034     case Type::STK_FloatingComplex:
7035     case Type::STK_IntegralComplex:
7036     case Type::STK_MemberPointer:
7037     case Type::STK_FixedPoint:
7038       llvm_unreachable("illegal cast from pointer");
7039     }
7040     llvm_unreachable("Should have returned before this");
7041 
7042   case Type::STK_FixedPoint:
7043     switch (DestTy->getScalarTypeKind()) {
7044     case Type::STK_FixedPoint:
7045       return CK_FixedPointCast;
7046     case Type::STK_Bool:
7047       return CK_FixedPointToBoolean;
7048     case Type::STK_Integral:
7049       return CK_FixedPointToIntegral;
7050     case Type::STK_Floating:
7051     case Type::STK_IntegralComplex:
7052     case Type::STK_FloatingComplex:
7053       Diag(Src.get()->getExprLoc(),
7054            diag::err_unimplemented_conversion_with_fixed_point_type)
7055           << DestTy;
7056       return CK_IntegralCast;
7057     case Type::STK_CPointer:
7058     case Type::STK_ObjCObjectPointer:
7059     case Type::STK_BlockPointer:
7060     case Type::STK_MemberPointer:
7061       llvm_unreachable("illegal cast to pointer type");
7062     }
7063     llvm_unreachable("Should have returned before this");
7064 
7065   case Type::STK_Bool: // casting from bool is like casting from an integer
7066   case Type::STK_Integral:
7067     switch (DestTy->getScalarTypeKind()) {
7068     case Type::STK_CPointer:
7069     case Type::STK_ObjCObjectPointer:
7070     case Type::STK_BlockPointer:
7071       if (Src.get()->isNullPointerConstant(Context,
7072                                            Expr::NPC_ValueDependentIsNull))
7073         return CK_NullToPointer;
7074       return CK_IntegralToPointer;
7075     case Type::STK_Bool:
7076       return CK_IntegralToBoolean;
7077     case Type::STK_Integral:
7078       return CK_IntegralCast;
7079     case Type::STK_Floating:
7080       return CK_IntegralToFloating;
7081     case Type::STK_IntegralComplex:
7082       Src = ImpCastExprToType(Src.get(),
7083                       DestTy->castAs<ComplexType>()->getElementType(),
7084                       CK_IntegralCast);
7085       return CK_IntegralRealToComplex;
7086     case Type::STK_FloatingComplex:
7087       Src = ImpCastExprToType(Src.get(),
7088                       DestTy->castAs<ComplexType>()->getElementType(),
7089                       CK_IntegralToFloating);
7090       return CK_FloatingRealToComplex;
7091     case Type::STK_MemberPointer:
7092       llvm_unreachable("member pointer type in C");
7093     case Type::STK_FixedPoint:
7094       return CK_IntegralToFixedPoint;
7095     }
7096     llvm_unreachable("Should have returned before this");
7097 
7098   case Type::STK_Floating:
7099     switch (DestTy->getScalarTypeKind()) {
7100     case Type::STK_Floating:
7101       return CK_FloatingCast;
7102     case Type::STK_Bool:
7103       return CK_FloatingToBoolean;
7104     case Type::STK_Integral:
7105       return CK_FloatingToIntegral;
7106     case Type::STK_FloatingComplex:
7107       Src = ImpCastExprToType(Src.get(),
7108                               DestTy->castAs<ComplexType>()->getElementType(),
7109                               CK_FloatingCast);
7110       return CK_FloatingRealToComplex;
7111     case Type::STK_IntegralComplex:
7112       Src = ImpCastExprToType(Src.get(),
7113                               DestTy->castAs<ComplexType>()->getElementType(),
7114                               CK_FloatingToIntegral);
7115       return CK_IntegralRealToComplex;
7116     case Type::STK_CPointer:
7117     case Type::STK_ObjCObjectPointer:
7118     case Type::STK_BlockPointer:
7119       llvm_unreachable("valid float->pointer cast?");
7120     case Type::STK_MemberPointer:
7121       llvm_unreachable("member pointer type in C");
7122     case Type::STK_FixedPoint:
7123       Diag(Src.get()->getExprLoc(),
7124            diag::err_unimplemented_conversion_with_fixed_point_type)
7125           << SrcTy;
7126       return CK_IntegralCast;
7127     }
7128     llvm_unreachable("Should have returned before this");
7129 
7130   case Type::STK_FloatingComplex:
7131     switch (DestTy->getScalarTypeKind()) {
7132     case Type::STK_FloatingComplex:
7133       return CK_FloatingComplexCast;
7134     case Type::STK_IntegralComplex:
7135       return CK_FloatingComplexToIntegralComplex;
7136     case Type::STK_Floating: {
7137       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7138       if (Context.hasSameType(ET, DestTy))
7139         return CK_FloatingComplexToReal;
7140       Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
7141       return CK_FloatingCast;
7142     }
7143     case Type::STK_Bool:
7144       return CK_FloatingComplexToBoolean;
7145     case Type::STK_Integral:
7146       Src = ImpCastExprToType(Src.get(),
7147                               SrcTy->castAs<ComplexType>()->getElementType(),
7148                               CK_FloatingComplexToReal);
7149       return CK_FloatingToIntegral;
7150     case Type::STK_CPointer:
7151     case Type::STK_ObjCObjectPointer:
7152     case Type::STK_BlockPointer:
7153       llvm_unreachable("valid complex float->pointer cast?");
7154     case Type::STK_MemberPointer:
7155       llvm_unreachable("member pointer type in C");
7156     case Type::STK_FixedPoint:
7157       Diag(Src.get()->getExprLoc(),
7158            diag::err_unimplemented_conversion_with_fixed_point_type)
7159           << SrcTy;
7160       return CK_IntegralCast;
7161     }
7162     llvm_unreachable("Should have returned before this");
7163 
7164   case Type::STK_IntegralComplex:
7165     switch (DestTy->getScalarTypeKind()) {
7166     case Type::STK_FloatingComplex:
7167       return CK_IntegralComplexToFloatingComplex;
7168     case Type::STK_IntegralComplex:
7169       return CK_IntegralComplexCast;
7170     case Type::STK_Integral: {
7171       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7172       if (Context.hasSameType(ET, DestTy))
7173         return CK_IntegralComplexToReal;
7174       Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
7175       return CK_IntegralCast;
7176     }
7177     case Type::STK_Bool:
7178       return CK_IntegralComplexToBoolean;
7179     case Type::STK_Floating:
7180       Src = ImpCastExprToType(Src.get(),
7181                               SrcTy->castAs<ComplexType>()->getElementType(),
7182                               CK_IntegralComplexToReal);
7183       return CK_IntegralToFloating;
7184     case Type::STK_CPointer:
7185     case Type::STK_ObjCObjectPointer:
7186     case Type::STK_BlockPointer:
7187       llvm_unreachable("valid complex int->pointer cast?");
7188     case Type::STK_MemberPointer:
7189       llvm_unreachable("member pointer type in C");
7190     case Type::STK_FixedPoint:
7191       Diag(Src.get()->getExprLoc(),
7192            diag::err_unimplemented_conversion_with_fixed_point_type)
7193           << SrcTy;
7194       return CK_IntegralCast;
7195     }
7196     llvm_unreachable("Should have returned before this");
7197   }
7198 
7199   llvm_unreachable("Unhandled scalar cast");
7200 }
7201 
7202 static bool breakDownVectorType(QualType type, uint64_t &len,
7203                                 QualType &eltType) {
7204   // Vectors are simple.
7205   if (const VectorType *vecType = type->getAs<VectorType>()) {
7206     len = vecType->getNumElements();
7207     eltType = vecType->getElementType();
7208     assert(eltType->isScalarType());
7209     return true;
7210   }
7211 
7212   // We allow lax conversion to and from non-vector types, but only if
7213   // they're real types (i.e. non-complex, non-pointer scalar types).
7214   if (!type->isRealType()) return false;
7215 
7216   len = 1;
7217   eltType = type;
7218   return true;
7219 }
7220 
7221 /// Are the two types lax-compatible vector types?  That is, given
7222 /// that one of them is a vector, do they have equal storage sizes,
7223 /// where the storage size is the number of elements times the element
7224 /// size?
7225 ///
7226 /// This will also return false if either of the types is neither a
7227 /// vector nor a real type.
7228 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
7229   assert(destTy->isVectorType() || srcTy->isVectorType());
7230 
7231   // Disallow lax conversions between scalars and ExtVectors (these
7232   // conversions are allowed for other vector types because common headers
7233   // depend on them).  Most scalar OP ExtVector cases are handled by the
7234   // splat path anyway, which does what we want (convert, not bitcast).
7235   // What this rules out for ExtVectors is crazy things like char4*float.
7236   if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
7237   if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
7238 
7239   uint64_t srcLen, destLen;
7240   QualType srcEltTy, destEltTy;
7241   if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false;
7242   if (!breakDownVectorType(destTy, destLen, destEltTy)) return false;
7243 
7244   // ASTContext::getTypeSize will return the size rounded up to a
7245   // power of 2, so instead of using that, we need to use the raw
7246   // element size multiplied by the element count.
7247   uint64_t srcEltSize = Context.getTypeSize(srcEltTy);
7248   uint64_t destEltSize = Context.getTypeSize(destEltTy);
7249 
7250   return (srcLen * srcEltSize == destLen * destEltSize);
7251 }
7252 
7253 /// Is this a legal conversion between two types, one of which is
7254 /// known to be a vector type?
7255 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
7256   assert(destTy->isVectorType() || srcTy->isVectorType());
7257 
7258   switch (Context.getLangOpts().getLaxVectorConversions()) {
7259   case LangOptions::LaxVectorConversionKind::None:
7260     return false;
7261 
7262   case LangOptions::LaxVectorConversionKind::Integer:
7263     if (!srcTy->isIntegralOrEnumerationType()) {
7264       auto *Vec = srcTy->getAs<VectorType>();
7265       if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7266         return false;
7267     }
7268     if (!destTy->isIntegralOrEnumerationType()) {
7269       auto *Vec = destTy->getAs<VectorType>();
7270       if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7271         return false;
7272     }
7273     // OK, integer (vector) -> integer (vector) bitcast.
7274     break;
7275 
7276     case LangOptions::LaxVectorConversionKind::All:
7277     break;
7278   }
7279 
7280   return areLaxCompatibleVectorTypes(srcTy, destTy);
7281 }
7282 
7283 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
7284                            CastKind &Kind) {
7285   assert(VectorTy->isVectorType() && "Not a vector type!");
7286 
7287   if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
7288     if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
7289       return Diag(R.getBegin(),
7290                   Ty->isVectorType() ?
7291                   diag::err_invalid_conversion_between_vectors :
7292                   diag::err_invalid_conversion_between_vector_and_integer)
7293         << VectorTy << Ty << R;
7294   } else
7295     return Diag(R.getBegin(),
7296                 diag::err_invalid_conversion_between_vector_and_scalar)
7297       << VectorTy << Ty << R;
7298 
7299   Kind = CK_BitCast;
7300   return false;
7301 }
7302 
7303 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
7304   QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
7305 
7306   if (DestElemTy == SplattedExpr->getType())
7307     return SplattedExpr;
7308 
7309   assert(DestElemTy->isFloatingType() ||
7310          DestElemTy->isIntegralOrEnumerationType());
7311 
7312   CastKind CK;
7313   if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
7314     // OpenCL requires that we convert `true` boolean expressions to -1, but
7315     // only when splatting vectors.
7316     if (DestElemTy->isFloatingType()) {
7317       // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
7318       // in two steps: boolean to signed integral, then to floating.
7319       ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
7320                                                  CK_BooleanToSignedIntegral);
7321       SplattedExpr = CastExprRes.get();
7322       CK = CK_IntegralToFloating;
7323     } else {
7324       CK = CK_BooleanToSignedIntegral;
7325     }
7326   } else {
7327     ExprResult CastExprRes = SplattedExpr;
7328     CK = PrepareScalarCast(CastExprRes, DestElemTy);
7329     if (CastExprRes.isInvalid())
7330       return ExprError();
7331     SplattedExpr = CastExprRes.get();
7332   }
7333   return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
7334 }
7335 
7336 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
7337                                     Expr *CastExpr, CastKind &Kind) {
7338   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
7339 
7340   QualType SrcTy = CastExpr->getType();
7341 
7342   // If SrcTy is a VectorType, the total size must match to explicitly cast to
7343   // an ExtVectorType.
7344   // In OpenCL, casts between vectors of different types are not allowed.
7345   // (See OpenCL 6.2).
7346   if (SrcTy->isVectorType()) {
7347     if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
7348         (getLangOpts().OpenCL &&
7349          !Context.hasSameUnqualifiedType(DestTy, SrcTy))) {
7350       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
7351         << DestTy << SrcTy << R;
7352       return ExprError();
7353     }
7354     Kind = CK_BitCast;
7355     return CastExpr;
7356   }
7357 
7358   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
7359   // conversion will take place first from scalar to elt type, and then
7360   // splat from elt type to vector.
7361   if (SrcTy->isPointerType())
7362     return Diag(R.getBegin(),
7363                 diag::err_invalid_conversion_between_vector_and_scalar)
7364       << DestTy << SrcTy << R;
7365 
7366   Kind = CK_VectorSplat;
7367   return prepareVectorSplat(DestTy, CastExpr);
7368 }
7369 
7370 ExprResult
7371 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
7372                     Declarator &D, ParsedType &Ty,
7373                     SourceLocation RParenLoc, Expr *CastExpr) {
7374   assert(!D.isInvalidType() && (CastExpr != nullptr) &&
7375          "ActOnCastExpr(): missing type or expr");
7376 
7377   TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
7378   if (D.isInvalidType())
7379     return ExprError();
7380 
7381   if (getLangOpts().CPlusPlus) {
7382     // Check that there are no default arguments (C++ only).
7383     CheckExtraCXXDefaultArguments(D);
7384   } else {
7385     // Make sure any TypoExprs have been dealt with.
7386     ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
7387     if (!Res.isUsable())
7388       return ExprError();
7389     CastExpr = Res.get();
7390   }
7391 
7392   checkUnusedDeclAttributes(D);
7393 
7394   QualType castType = castTInfo->getType();
7395   Ty = CreateParsedType(castType, castTInfo);
7396 
7397   bool isVectorLiteral = false;
7398 
7399   // Check for an altivec or OpenCL literal,
7400   // i.e. all the elements are integer constants.
7401   ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
7402   ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
7403   if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
7404        && castType->isVectorType() && (PE || PLE)) {
7405     if (PLE && PLE->getNumExprs() == 0) {
7406       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
7407       return ExprError();
7408     }
7409     if (PE || PLE->getNumExprs() == 1) {
7410       Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
7411       if (!E->isTypeDependent() && !E->getType()->isVectorType())
7412         isVectorLiteral = true;
7413     }
7414     else
7415       isVectorLiteral = true;
7416   }
7417 
7418   // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
7419   // then handle it as such.
7420   if (isVectorLiteral)
7421     return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
7422 
7423   // If the Expr being casted is a ParenListExpr, handle it specially.
7424   // This is not an AltiVec-style cast, so turn the ParenListExpr into a
7425   // sequence of BinOp comma operators.
7426   if (isa<ParenListExpr>(CastExpr)) {
7427     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
7428     if (Result.isInvalid()) return ExprError();
7429     CastExpr = Result.get();
7430   }
7431 
7432   if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
7433       !getSourceManager().isInSystemMacro(LParenLoc))
7434     Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
7435 
7436   CheckTollFreeBridgeCast(castType, CastExpr);
7437 
7438   CheckObjCBridgeRelatedCast(castType, CastExpr);
7439 
7440   DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
7441 
7442   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
7443 }
7444 
7445 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
7446                                     SourceLocation RParenLoc, Expr *E,
7447                                     TypeSourceInfo *TInfo) {
7448   assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
7449          "Expected paren or paren list expression");
7450 
7451   Expr **exprs;
7452   unsigned numExprs;
7453   Expr *subExpr;
7454   SourceLocation LiteralLParenLoc, LiteralRParenLoc;
7455   if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
7456     LiteralLParenLoc = PE->getLParenLoc();
7457     LiteralRParenLoc = PE->getRParenLoc();
7458     exprs = PE->getExprs();
7459     numExprs = PE->getNumExprs();
7460   } else { // isa<ParenExpr> by assertion at function entrance
7461     LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
7462     LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
7463     subExpr = cast<ParenExpr>(E)->getSubExpr();
7464     exprs = &subExpr;
7465     numExprs = 1;
7466   }
7467 
7468   QualType Ty = TInfo->getType();
7469   assert(Ty->isVectorType() && "Expected vector type");
7470 
7471   SmallVector<Expr *, 8> initExprs;
7472   const VectorType *VTy = Ty->castAs<VectorType>();
7473   unsigned numElems = VTy->getNumElements();
7474 
7475   // '(...)' form of vector initialization in AltiVec: the number of
7476   // initializers must be one or must match the size of the vector.
7477   // If a single value is specified in the initializer then it will be
7478   // replicated to all the components of the vector
7479   if (VTy->getVectorKind() == VectorType::AltiVecVector) {
7480     // The number of initializers must be one or must match the size of the
7481     // vector. If a single value is specified in the initializer then it will
7482     // be replicated to all the components of the vector
7483     if (numExprs == 1) {
7484       QualType ElemTy = VTy->getElementType();
7485       ExprResult Literal = DefaultLvalueConversion(exprs[0]);
7486       if (Literal.isInvalid())
7487         return ExprError();
7488       Literal = ImpCastExprToType(Literal.get(), ElemTy,
7489                                   PrepareScalarCast(Literal, ElemTy));
7490       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
7491     }
7492     else if (numExprs < numElems) {
7493       Diag(E->getExprLoc(),
7494            diag::err_incorrect_number_of_vector_initializers);
7495       return ExprError();
7496     }
7497     else
7498       initExprs.append(exprs, exprs + numExprs);
7499   }
7500   else {
7501     // For OpenCL, when the number of initializers is a single value,
7502     // it will be replicated to all components of the vector.
7503     if (getLangOpts().OpenCL &&
7504         VTy->getVectorKind() == VectorType::GenericVector &&
7505         numExprs == 1) {
7506         QualType ElemTy = VTy->getElementType();
7507         ExprResult Literal = DefaultLvalueConversion(exprs[0]);
7508         if (Literal.isInvalid())
7509           return ExprError();
7510         Literal = ImpCastExprToType(Literal.get(), ElemTy,
7511                                     PrepareScalarCast(Literal, ElemTy));
7512         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
7513     }
7514 
7515     initExprs.append(exprs, exprs + numExprs);
7516   }
7517   // FIXME: This means that pretty-printing the final AST will produce curly
7518   // braces instead of the original commas.
7519   InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
7520                                                    initExprs, LiteralRParenLoc);
7521   initE->setType(Ty);
7522   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
7523 }
7524 
7525 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
7526 /// the ParenListExpr into a sequence of comma binary operators.
7527 ExprResult
7528 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
7529   ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
7530   if (!E)
7531     return OrigExpr;
7532 
7533   ExprResult Result(E->getExpr(0));
7534 
7535   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
7536     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
7537                         E->getExpr(i));
7538 
7539   if (Result.isInvalid()) return ExprError();
7540 
7541   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
7542 }
7543 
7544 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
7545                                     SourceLocation R,
7546                                     MultiExprArg Val) {
7547   return ParenListExpr::Create(Context, L, Val, R);
7548 }
7549 
7550 /// Emit a specialized diagnostic when one expression is a null pointer
7551 /// constant and the other is not a pointer.  Returns true if a diagnostic is
7552 /// emitted.
7553 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
7554                                       SourceLocation QuestionLoc) {
7555   Expr *NullExpr = LHSExpr;
7556   Expr *NonPointerExpr = RHSExpr;
7557   Expr::NullPointerConstantKind NullKind =
7558       NullExpr->isNullPointerConstant(Context,
7559                                       Expr::NPC_ValueDependentIsNotNull);
7560 
7561   if (NullKind == Expr::NPCK_NotNull) {
7562     NullExpr = RHSExpr;
7563     NonPointerExpr = LHSExpr;
7564     NullKind =
7565         NullExpr->isNullPointerConstant(Context,
7566                                         Expr::NPC_ValueDependentIsNotNull);
7567   }
7568 
7569   if (NullKind == Expr::NPCK_NotNull)
7570     return false;
7571 
7572   if (NullKind == Expr::NPCK_ZeroExpression)
7573     return false;
7574 
7575   if (NullKind == Expr::NPCK_ZeroLiteral) {
7576     // In this case, check to make sure that we got here from a "NULL"
7577     // string in the source code.
7578     NullExpr = NullExpr->IgnoreParenImpCasts();
7579     SourceLocation loc = NullExpr->getExprLoc();
7580     if (!findMacroSpelling(loc, "NULL"))
7581       return false;
7582   }
7583 
7584   int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
7585   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
7586       << NonPointerExpr->getType() << DiagType
7587       << NonPointerExpr->getSourceRange();
7588   return true;
7589 }
7590 
7591 /// Return false if the condition expression is valid, true otherwise.
7592 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
7593   QualType CondTy = Cond->getType();
7594 
7595   // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
7596   if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
7597     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
7598       << CondTy << Cond->getSourceRange();
7599     return true;
7600   }
7601 
7602   // C99 6.5.15p2
7603   if (CondTy->isScalarType()) return false;
7604 
7605   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
7606     << CondTy << Cond->getSourceRange();
7607   return true;
7608 }
7609 
7610 /// Handle when one or both operands are void type.
7611 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
7612                                          ExprResult &RHS) {
7613     Expr *LHSExpr = LHS.get();
7614     Expr *RHSExpr = RHS.get();
7615 
7616     if (!LHSExpr->getType()->isVoidType())
7617       S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
7618           << RHSExpr->getSourceRange();
7619     if (!RHSExpr->getType()->isVoidType())
7620       S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
7621           << LHSExpr->getSourceRange();
7622     LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
7623     RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
7624     return S.Context.VoidTy;
7625 }
7626 
7627 /// Return false if the NullExpr can be promoted to PointerTy,
7628 /// true otherwise.
7629 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
7630                                         QualType PointerTy) {
7631   if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
7632       !NullExpr.get()->isNullPointerConstant(S.Context,
7633                                             Expr::NPC_ValueDependentIsNull))
7634     return true;
7635 
7636   NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
7637   return false;
7638 }
7639 
7640 /// Checks compatibility between two pointers and return the resulting
7641 /// type.
7642 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
7643                                                      ExprResult &RHS,
7644                                                      SourceLocation Loc) {
7645   QualType LHSTy = LHS.get()->getType();
7646   QualType RHSTy = RHS.get()->getType();
7647 
7648   if (S.Context.hasSameType(LHSTy, RHSTy)) {
7649     // Two identical pointers types are always compatible.
7650     return LHSTy;
7651   }
7652 
7653   QualType lhptee, rhptee;
7654 
7655   // Get the pointee types.
7656   bool IsBlockPointer = false;
7657   if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
7658     lhptee = LHSBTy->getPointeeType();
7659     rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
7660     IsBlockPointer = true;
7661   } else {
7662     lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
7663     rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
7664   }
7665 
7666   // C99 6.5.15p6: If both operands are pointers to compatible types or to
7667   // differently qualified versions of compatible types, the result type is
7668   // a pointer to an appropriately qualified version of the composite
7669   // type.
7670 
7671   // Only CVR-qualifiers exist in the standard, and the differently-qualified
7672   // clause doesn't make sense for our extensions. E.g. address space 2 should
7673   // be incompatible with address space 3: they may live on different devices or
7674   // anything.
7675   Qualifiers lhQual = lhptee.getQualifiers();
7676   Qualifiers rhQual = rhptee.getQualifiers();
7677 
7678   LangAS ResultAddrSpace = LangAS::Default;
7679   LangAS LAddrSpace = lhQual.getAddressSpace();
7680   LangAS RAddrSpace = rhQual.getAddressSpace();
7681 
7682   // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
7683   // spaces is disallowed.
7684   if (lhQual.isAddressSpaceSupersetOf(rhQual))
7685     ResultAddrSpace = LAddrSpace;
7686   else if (rhQual.isAddressSpaceSupersetOf(lhQual))
7687     ResultAddrSpace = RAddrSpace;
7688   else {
7689     S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
7690         << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
7691         << RHS.get()->getSourceRange();
7692     return QualType();
7693   }
7694 
7695   unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
7696   auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
7697   lhQual.removeCVRQualifiers();
7698   rhQual.removeCVRQualifiers();
7699 
7700   // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
7701   // (C99 6.7.3) for address spaces. We assume that the check should behave in
7702   // the same manner as it's defined for CVR qualifiers, so for OpenCL two
7703   // qual types are compatible iff
7704   //  * corresponded types are compatible
7705   //  * CVR qualifiers are equal
7706   //  * address spaces are equal
7707   // Thus for conditional operator we merge CVR and address space unqualified
7708   // pointees and if there is a composite type we return a pointer to it with
7709   // merged qualifiers.
7710   LHSCastKind =
7711       LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
7712   RHSCastKind =
7713       RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
7714   lhQual.removeAddressSpace();
7715   rhQual.removeAddressSpace();
7716 
7717   lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
7718   rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
7719 
7720   QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
7721 
7722   if (CompositeTy.isNull()) {
7723     // In this situation, we assume void* type. No especially good
7724     // reason, but this is what gcc does, and we do have to pick
7725     // to get a consistent AST.
7726     QualType incompatTy;
7727     incompatTy = S.Context.getPointerType(
7728         S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
7729     LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
7730     RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
7731 
7732     // FIXME: For OpenCL the warning emission and cast to void* leaves a room
7733     // for casts between types with incompatible address space qualifiers.
7734     // For the following code the compiler produces casts between global and
7735     // local address spaces of the corresponded innermost pointees:
7736     // local int *global *a;
7737     // global int *global *b;
7738     // a = (0 ? a : b); // see C99 6.5.16.1.p1.
7739     S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
7740         << LHSTy << RHSTy << LHS.get()->getSourceRange()
7741         << RHS.get()->getSourceRange();
7742 
7743     return incompatTy;
7744   }
7745 
7746   // The pointer types are compatible.
7747   // In case of OpenCL ResultTy should have the address space qualifier
7748   // which is a superset of address spaces of both the 2nd and the 3rd
7749   // operands of the conditional operator.
7750   QualType ResultTy = [&, ResultAddrSpace]() {
7751     if (S.getLangOpts().OpenCL) {
7752       Qualifiers CompositeQuals = CompositeTy.getQualifiers();
7753       CompositeQuals.setAddressSpace(ResultAddrSpace);
7754       return S.Context
7755           .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
7756           .withCVRQualifiers(MergedCVRQual);
7757     }
7758     return CompositeTy.withCVRQualifiers(MergedCVRQual);
7759   }();
7760   if (IsBlockPointer)
7761     ResultTy = S.Context.getBlockPointerType(ResultTy);
7762   else
7763     ResultTy = S.Context.getPointerType(ResultTy);
7764 
7765   LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
7766   RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
7767   return ResultTy;
7768 }
7769 
7770 /// Return the resulting type when the operands are both block pointers.
7771 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
7772                                                           ExprResult &LHS,
7773                                                           ExprResult &RHS,
7774                                                           SourceLocation Loc) {
7775   QualType LHSTy = LHS.get()->getType();
7776   QualType RHSTy = RHS.get()->getType();
7777 
7778   if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
7779     if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
7780       QualType destType = S.Context.getPointerType(S.Context.VoidTy);
7781       LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
7782       RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
7783       return destType;
7784     }
7785     S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
7786       << LHSTy << RHSTy << LHS.get()->getSourceRange()
7787       << RHS.get()->getSourceRange();
7788     return QualType();
7789   }
7790 
7791   // We have 2 block pointer types.
7792   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
7793 }
7794 
7795 /// Return the resulting type when the operands are both pointers.
7796 static QualType
7797 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
7798                                             ExprResult &RHS,
7799                                             SourceLocation Loc) {
7800   // get the pointer types
7801   QualType LHSTy = LHS.get()->getType();
7802   QualType RHSTy = RHS.get()->getType();
7803 
7804   // get the "pointed to" types
7805   QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
7806   QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
7807 
7808   // ignore qualifiers on void (C99 6.5.15p3, clause 6)
7809   if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
7810     // Figure out necessary qualifiers (C99 6.5.15p6)
7811     QualType destPointee
7812       = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
7813     QualType destType = S.Context.getPointerType(destPointee);
7814     // Add qualifiers if necessary.
7815     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
7816     // Promote to void*.
7817     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
7818     return destType;
7819   }
7820   if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
7821     QualType destPointee
7822       = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
7823     QualType destType = S.Context.getPointerType(destPointee);
7824     // Add qualifiers if necessary.
7825     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
7826     // Promote to void*.
7827     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
7828     return destType;
7829   }
7830 
7831   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
7832 }
7833 
7834 /// Return false if the first expression is not an integer and the second
7835 /// expression is not a pointer, true otherwise.
7836 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
7837                                         Expr* PointerExpr, SourceLocation Loc,
7838                                         bool IsIntFirstExpr) {
7839   if (!PointerExpr->getType()->isPointerType() ||
7840       !Int.get()->getType()->isIntegerType())
7841     return false;
7842 
7843   Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
7844   Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
7845 
7846   S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
7847     << Expr1->getType() << Expr2->getType()
7848     << Expr1->getSourceRange() << Expr2->getSourceRange();
7849   Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
7850                             CK_IntegralToPointer);
7851   return true;
7852 }
7853 
7854 /// Simple conversion between integer and floating point types.
7855 ///
7856 /// Used when handling the OpenCL conditional operator where the
7857 /// condition is a vector while the other operands are scalar.
7858 ///
7859 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
7860 /// types are either integer or floating type. Between the two
7861 /// operands, the type with the higher rank is defined as the "result
7862 /// type". The other operand needs to be promoted to the same type. No
7863 /// other type promotion is allowed. We cannot use
7864 /// UsualArithmeticConversions() for this purpose, since it always
7865 /// promotes promotable types.
7866 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
7867                                             ExprResult &RHS,
7868                                             SourceLocation QuestionLoc) {
7869   LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
7870   if (LHS.isInvalid())
7871     return QualType();
7872   RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
7873   if (RHS.isInvalid())
7874     return QualType();
7875 
7876   // For conversion purposes, we ignore any qualifiers.
7877   // For example, "const float" and "float" are equivalent.
7878   QualType LHSType =
7879     S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
7880   QualType RHSType =
7881     S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
7882 
7883   if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
7884     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
7885       << LHSType << LHS.get()->getSourceRange();
7886     return QualType();
7887   }
7888 
7889   if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
7890     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
7891       << RHSType << RHS.get()->getSourceRange();
7892     return QualType();
7893   }
7894 
7895   // If both types are identical, no conversion is needed.
7896   if (LHSType == RHSType)
7897     return LHSType;
7898 
7899   // Now handle "real" floating types (i.e. float, double, long double).
7900   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
7901     return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
7902                                  /*IsCompAssign = */ false);
7903 
7904   // Finally, we have two differing integer types.
7905   return handleIntegerConversion<doIntegralCast, doIntegralCast>
7906   (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
7907 }
7908 
7909 /// Convert scalar operands to a vector that matches the
7910 ///        condition in length.
7911 ///
7912 /// Used when handling the OpenCL conditional operator where the
7913 /// condition is a vector while the other operands are scalar.
7914 ///
7915 /// We first compute the "result type" for the scalar operands
7916 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
7917 /// into a vector of that type where the length matches the condition
7918 /// vector type. s6.11.6 requires that the element types of the result
7919 /// and the condition must have the same number of bits.
7920 static QualType
7921 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
7922                               QualType CondTy, SourceLocation QuestionLoc) {
7923   QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
7924   if (ResTy.isNull()) return QualType();
7925 
7926   const VectorType *CV = CondTy->getAs<VectorType>();
7927   assert(CV);
7928 
7929   // Determine the vector result type
7930   unsigned NumElements = CV->getNumElements();
7931   QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
7932 
7933   // Ensure that all types have the same number of bits
7934   if (S.Context.getTypeSize(CV->getElementType())
7935       != S.Context.getTypeSize(ResTy)) {
7936     // Since VectorTy is created internally, it does not pretty print
7937     // with an OpenCL name. Instead, we just print a description.
7938     std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
7939     SmallString<64> Str;
7940     llvm::raw_svector_ostream OS(Str);
7941     OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
7942     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
7943       << CondTy << OS.str();
7944     return QualType();
7945   }
7946 
7947   // Convert operands to the vector result type
7948   LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
7949   RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
7950 
7951   return VectorTy;
7952 }
7953 
7954 /// Return false if this is a valid OpenCL condition vector
7955 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
7956                                        SourceLocation QuestionLoc) {
7957   // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
7958   // integral type.
7959   const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
7960   assert(CondTy);
7961   QualType EleTy = CondTy->getElementType();
7962   if (EleTy->isIntegerType()) return false;
7963 
7964   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
7965     << Cond->getType() << Cond->getSourceRange();
7966   return true;
7967 }
7968 
7969 /// Return false if the vector condition type and the vector
7970 ///        result type are compatible.
7971 ///
7972 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
7973 /// number of elements, and their element types have the same number
7974 /// of bits.
7975 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
7976                               SourceLocation QuestionLoc) {
7977   const VectorType *CV = CondTy->getAs<VectorType>();
7978   const VectorType *RV = VecResTy->getAs<VectorType>();
7979   assert(CV && RV);
7980 
7981   if (CV->getNumElements() != RV->getNumElements()) {
7982     S.Diag(QuestionLoc, diag::err_conditional_vector_size)
7983       << CondTy << VecResTy;
7984     return true;
7985   }
7986 
7987   QualType CVE = CV->getElementType();
7988   QualType RVE = RV->getElementType();
7989 
7990   if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
7991     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
7992       << CondTy << VecResTy;
7993     return true;
7994   }
7995 
7996   return false;
7997 }
7998 
7999 /// Return the resulting type for the conditional operator in
8000 ///        OpenCL (aka "ternary selection operator", OpenCL v1.1
8001 ///        s6.3.i) when the condition is a vector type.
8002 static QualType
8003 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
8004                              ExprResult &LHS, ExprResult &RHS,
8005                              SourceLocation QuestionLoc) {
8006   Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
8007   if (Cond.isInvalid())
8008     return QualType();
8009   QualType CondTy = Cond.get()->getType();
8010 
8011   if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
8012     return QualType();
8013 
8014   // If either operand is a vector then find the vector type of the
8015   // result as specified in OpenCL v1.1 s6.3.i.
8016   if (LHS.get()->getType()->isVectorType() ||
8017       RHS.get()->getType()->isVectorType()) {
8018     QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
8019                                               /*isCompAssign*/false,
8020                                               /*AllowBothBool*/true,
8021                                               /*AllowBoolConversions*/false);
8022     if (VecResTy.isNull()) return QualType();
8023     // The result type must match the condition type as specified in
8024     // OpenCL v1.1 s6.11.6.
8025     if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
8026       return QualType();
8027     return VecResTy;
8028   }
8029 
8030   // Both operands are scalar.
8031   return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
8032 }
8033 
8034 /// Return true if the Expr is block type
8035 static bool checkBlockType(Sema &S, const Expr *E) {
8036   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
8037     QualType Ty = CE->getCallee()->getType();
8038     if (Ty->isBlockPointerType()) {
8039       S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
8040       return true;
8041     }
8042   }
8043   return false;
8044 }
8045 
8046 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
8047 /// In that case, LHS = cond.
8048 /// C99 6.5.15
8049 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
8050                                         ExprResult &RHS, ExprValueKind &VK,
8051                                         ExprObjectKind &OK,
8052                                         SourceLocation QuestionLoc) {
8053 
8054   ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
8055   if (!LHSResult.isUsable()) return QualType();
8056   LHS = LHSResult;
8057 
8058   ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
8059   if (!RHSResult.isUsable()) return QualType();
8060   RHS = RHSResult;
8061 
8062   // C++ is sufficiently different to merit its own checker.
8063   if (getLangOpts().CPlusPlus)
8064     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
8065 
8066   VK = VK_RValue;
8067   OK = OK_Ordinary;
8068 
8069   // The OpenCL operator with a vector condition is sufficiently
8070   // different to merit its own checker.
8071   if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) ||
8072       Cond.get()->getType()->isExtVectorType())
8073     return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
8074 
8075   // First, check the condition.
8076   Cond = UsualUnaryConversions(Cond.get());
8077   if (Cond.isInvalid())
8078     return QualType();
8079   if (checkCondition(*this, Cond.get(), QuestionLoc))
8080     return QualType();
8081 
8082   // Now check the two expressions.
8083   if (LHS.get()->getType()->isVectorType() ||
8084       RHS.get()->getType()->isVectorType())
8085     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
8086                                /*AllowBothBool*/true,
8087                                /*AllowBoolConversions*/false);
8088 
8089   QualType ResTy =
8090       UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional);
8091   if (LHS.isInvalid() || RHS.isInvalid())
8092     return QualType();
8093 
8094   QualType LHSTy = LHS.get()->getType();
8095   QualType RHSTy = RHS.get()->getType();
8096 
8097   // Diagnose attempts to convert between __float128 and long double where
8098   // such conversions currently can't be handled.
8099   if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
8100     Diag(QuestionLoc,
8101          diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
8102       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8103     return QualType();
8104   }
8105 
8106   // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
8107   // selection operator (?:).
8108   if (getLangOpts().OpenCL &&
8109       (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) {
8110     return QualType();
8111   }
8112 
8113   // If both operands have arithmetic type, do the usual arithmetic conversions
8114   // to find a common type: C99 6.5.15p3,5.
8115   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
8116     // Disallow invalid arithmetic conversions, such as those between ExtInts of
8117     // different sizes, or between ExtInts and other types.
8118     if (ResTy.isNull() && (LHSTy->isExtIntType() || RHSTy->isExtIntType())) {
8119       Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
8120           << LHSTy << RHSTy << LHS.get()->getSourceRange()
8121           << RHS.get()->getSourceRange();
8122       return QualType();
8123     }
8124 
8125     LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
8126     RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
8127 
8128     return ResTy;
8129   }
8130 
8131   // And if they're both bfloat (which isn't arithmetic), that's fine too.
8132   if (LHSTy->isBFloat16Type() && RHSTy->isBFloat16Type()) {
8133     return LHSTy;
8134   }
8135 
8136   // If both operands are the same structure or union type, the result is that
8137   // type.
8138   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
8139     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
8140       if (LHSRT->getDecl() == RHSRT->getDecl())
8141         // "If both the operands have structure or union type, the result has
8142         // that type."  This implies that CV qualifiers are dropped.
8143         return LHSTy.getUnqualifiedType();
8144     // FIXME: Type of conditional expression must be complete in C mode.
8145   }
8146 
8147   // C99 6.5.15p5: "If both operands have void type, the result has void type."
8148   // The following || allows only one side to be void (a GCC-ism).
8149   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
8150     return checkConditionalVoidType(*this, LHS, RHS);
8151   }
8152 
8153   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
8154   // the type of the other operand."
8155   if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
8156   if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
8157 
8158   // All objective-c pointer type analysis is done here.
8159   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
8160                                                         QuestionLoc);
8161   if (LHS.isInvalid() || RHS.isInvalid())
8162     return QualType();
8163   if (!compositeType.isNull())
8164     return compositeType;
8165 
8166 
8167   // Handle block pointer types.
8168   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
8169     return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
8170                                                      QuestionLoc);
8171 
8172   // Check constraints for C object pointers types (C99 6.5.15p3,6).
8173   if (LHSTy->isPointerType() && RHSTy->isPointerType())
8174     return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
8175                                                        QuestionLoc);
8176 
8177   // GCC compatibility: soften pointer/integer mismatch.  Note that
8178   // null pointers have been filtered out by this point.
8179   if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
8180       /*IsIntFirstExpr=*/true))
8181     return RHSTy;
8182   if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
8183       /*IsIntFirstExpr=*/false))
8184     return LHSTy;
8185 
8186   // Allow ?: operations in which both operands have the same
8187   // built-in sizeless type.
8188   if (LHSTy->isSizelessBuiltinType() && LHSTy == RHSTy)
8189     return LHSTy;
8190 
8191   // Emit a better diagnostic if one of the expressions is a null pointer
8192   // constant and the other is not a pointer type. In this case, the user most
8193   // likely forgot to take the address of the other expression.
8194   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
8195     return QualType();
8196 
8197   // Otherwise, the operands are not compatible.
8198   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
8199     << LHSTy << RHSTy << LHS.get()->getSourceRange()
8200     << RHS.get()->getSourceRange();
8201   return QualType();
8202 }
8203 
8204 /// FindCompositeObjCPointerType - Helper method to find composite type of
8205 /// two objective-c pointer types of the two input expressions.
8206 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
8207                                             SourceLocation QuestionLoc) {
8208   QualType LHSTy = LHS.get()->getType();
8209   QualType RHSTy = RHS.get()->getType();
8210 
8211   // Handle things like Class and struct objc_class*.  Here we case the result
8212   // to the pseudo-builtin, because that will be implicitly cast back to the
8213   // redefinition type if an attempt is made to access its fields.
8214   if (LHSTy->isObjCClassType() &&
8215       (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
8216     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
8217     return LHSTy;
8218   }
8219   if (RHSTy->isObjCClassType() &&
8220       (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
8221     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
8222     return RHSTy;
8223   }
8224   // And the same for struct objc_object* / id
8225   if (LHSTy->isObjCIdType() &&
8226       (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
8227     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
8228     return LHSTy;
8229   }
8230   if (RHSTy->isObjCIdType() &&
8231       (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
8232     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
8233     return RHSTy;
8234   }
8235   // And the same for struct objc_selector* / SEL
8236   if (Context.isObjCSelType(LHSTy) &&
8237       (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
8238     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
8239     return LHSTy;
8240   }
8241   if (Context.isObjCSelType(RHSTy) &&
8242       (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
8243     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
8244     return RHSTy;
8245   }
8246   // Check constraints for Objective-C object pointers types.
8247   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
8248 
8249     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
8250       // Two identical object pointer types are always compatible.
8251       return LHSTy;
8252     }
8253     const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
8254     const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
8255     QualType compositeType = LHSTy;
8256 
8257     // If both operands are interfaces and either operand can be
8258     // assigned to the other, use that type as the composite
8259     // type. This allows
8260     //   xxx ? (A*) a : (B*) b
8261     // where B is a subclass of A.
8262     //
8263     // Additionally, as for assignment, if either type is 'id'
8264     // allow silent coercion. Finally, if the types are
8265     // incompatible then make sure to use 'id' as the composite
8266     // type so the result is acceptable for sending messages to.
8267 
8268     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
8269     // It could return the composite type.
8270     if (!(compositeType =
8271           Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
8272       // Nothing more to do.
8273     } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
8274       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
8275     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
8276       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
8277     } else if ((LHSOPT->isObjCQualifiedIdType() ||
8278                 RHSOPT->isObjCQualifiedIdType()) &&
8279                Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT,
8280                                                          true)) {
8281       // Need to handle "id<xx>" explicitly.
8282       // GCC allows qualified id and any Objective-C type to devolve to
8283       // id. Currently localizing to here until clear this should be
8284       // part of ObjCQualifiedIdTypesAreCompatible.
8285       compositeType = Context.getObjCIdType();
8286     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
8287       compositeType = Context.getObjCIdType();
8288     } else {
8289       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
8290       << LHSTy << RHSTy
8291       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8292       QualType incompatTy = Context.getObjCIdType();
8293       LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
8294       RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
8295       return incompatTy;
8296     }
8297     // The object pointer types are compatible.
8298     LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
8299     RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
8300     return compositeType;
8301   }
8302   // Check Objective-C object pointer types and 'void *'
8303   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
8304     if (getLangOpts().ObjCAutoRefCount) {
8305       // ARC forbids the implicit conversion of object pointers to 'void *',
8306       // so these types are not compatible.
8307       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
8308           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8309       LHS = RHS = true;
8310       return QualType();
8311     }
8312     QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8313     QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
8314     QualType destPointee
8315     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
8316     QualType destType = Context.getPointerType(destPointee);
8317     // Add qualifiers if necessary.
8318     LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
8319     // Promote to void*.
8320     RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8321     return destType;
8322   }
8323   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
8324     if (getLangOpts().ObjCAutoRefCount) {
8325       // ARC forbids the implicit conversion of object pointers to 'void *',
8326       // so these types are not compatible.
8327       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
8328           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8329       LHS = RHS = true;
8330       return QualType();
8331     }
8332     QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
8333     QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8334     QualType destPointee
8335     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
8336     QualType destType = Context.getPointerType(destPointee);
8337     // Add qualifiers if necessary.
8338     RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
8339     // Promote to void*.
8340     LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8341     return destType;
8342   }
8343   return QualType();
8344 }
8345 
8346 /// SuggestParentheses - Emit a note with a fixit hint that wraps
8347 /// ParenRange in parentheses.
8348 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
8349                                const PartialDiagnostic &Note,
8350                                SourceRange ParenRange) {
8351   SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
8352   if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
8353       EndLoc.isValid()) {
8354     Self.Diag(Loc, Note)
8355       << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
8356       << FixItHint::CreateInsertion(EndLoc, ")");
8357   } else {
8358     // We can't display the parentheses, so just show the bare note.
8359     Self.Diag(Loc, Note) << ParenRange;
8360   }
8361 }
8362 
8363 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
8364   return BinaryOperator::isAdditiveOp(Opc) ||
8365          BinaryOperator::isMultiplicativeOp(Opc) ||
8366          BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or;
8367   // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and
8368   // not any of the logical operators.  Bitwise-xor is commonly used as a
8369   // logical-xor because there is no logical-xor operator.  The logical
8370   // operators, including uses of xor, have a high false positive rate for
8371   // precedence warnings.
8372 }
8373 
8374 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
8375 /// expression, either using a built-in or overloaded operator,
8376 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
8377 /// expression.
8378 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
8379                                    Expr **RHSExprs) {
8380   // Don't strip parenthesis: we should not warn if E is in parenthesis.
8381   E = E->IgnoreImpCasts();
8382   E = E->IgnoreConversionOperatorSingleStep();
8383   E = E->IgnoreImpCasts();
8384   if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
8385     E = MTE->getSubExpr();
8386     E = E->IgnoreImpCasts();
8387   }
8388 
8389   // Built-in binary operator.
8390   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
8391     if (IsArithmeticOp(OP->getOpcode())) {
8392       *Opcode = OP->getOpcode();
8393       *RHSExprs = OP->getRHS();
8394       return true;
8395     }
8396   }
8397 
8398   // Overloaded operator.
8399   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
8400     if (Call->getNumArgs() != 2)
8401       return false;
8402 
8403     // Make sure this is really a binary operator that is safe to pass into
8404     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
8405     OverloadedOperatorKind OO = Call->getOperator();
8406     if (OO < OO_Plus || OO > OO_Arrow ||
8407         OO == OO_PlusPlus || OO == OO_MinusMinus)
8408       return false;
8409 
8410     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
8411     if (IsArithmeticOp(OpKind)) {
8412       *Opcode = OpKind;
8413       *RHSExprs = Call->getArg(1);
8414       return true;
8415     }
8416   }
8417 
8418   return false;
8419 }
8420 
8421 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
8422 /// or is a logical expression such as (x==y) which has int type, but is
8423 /// commonly interpreted as boolean.
8424 static bool ExprLooksBoolean(Expr *E) {
8425   E = E->IgnoreParenImpCasts();
8426 
8427   if (E->getType()->isBooleanType())
8428     return true;
8429   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
8430     return OP->isComparisonOp() || OP->isLogicalOp();
8431   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
8432     return OP->getOpcode() == UO_LNot;
8433   if (E->getType()->isPointerType())
8434     return true;
8435   // FIXME: What about overloaded operator calls returning "unspecified boolean
8436   // type"s (commonly pointer-to-members)?
8437 
8438   return false;
8439 }
8440 
8441 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
8442 /// and binary operator are mixed in a way that suggests the programmer assumed
8443 /// the conditional operator has higher precedence, for example:
8444 /// "int x = a + someBinaryCondition ? 1 : 2".
8445 static void DiagnoseConditionalPrecedence(Sema &Self,
8446                                           SourceLocation OpLoc,
8447                                           Expr *Condition,
8448                                           Expr *LHSExpr,
8449                                           Expr *RHSExpr) {
8450   BinaryOperatorKind CondOpcode;
8451   Expr *CondRHS;
8452 
8453   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
8454     return;
8455   if (!ExprLooksBoolean(CondRHS))
8456     return;
8457 
8458   // The condition is an arithmetic binary expression, with a right-
8459   // hand side that looks boolean, so warn.
8460 
8461   unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode)
8462                         ? diag::warn_precedence_bitwise_conditional
8463                         : diag::warn_precedence_conditional;
8464 
8465   Self.Diag(OpLoc, DiagID)
8466       << Condition->getSourceRange()
8467       << BinaryOperator::getOpcodeStr(CondOpcode);
8468 
8469   SuggestParentheses(
8470       Self, OpLoc,
8471       Self.PDiag(diag::note_precedence_silence)
8472           << BinaryOperator::getOpcodeStr(CondOpcode),
8473       SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
8474 
8475   SuggestParentheses(Self, OpLoc,
8476                      Self.PDiag(diag::note_precedence_conditional_first),
8477                      SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
8478 }
8479 
8480 /// Compute the nullability of a conditional expression.
8481 static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
8482                                               QualType LHSTy, QualType RHSTy,
8483                                               ASTContext &Ctx) {
8484   if (!ResTy->isAnyPointerType())
8485     return ResTy;
8486 
8487   auto GetNullability = [&Ctx](QualType Ty) {
8488     Optional<NullabilityKind> Kind = Ty->getNullability(Ctx);
8489     if (Kind)
8490       return *Kind;
8491     return NullabilityKind::Unspecified;
8492   };
8493 
8494   auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
8495   NullabilityKind MergedKind;
8496 
8497   // Compute nullability of a binary conditional expression.
8498   if (IsBin) {
8499     if (LHSKind == NullabilityKind::NonNull)
8500       MergedKind = NullabilityKind::NonNull;
8501     else
8502       MergedKind = RHSKind;
8503   // Compute nullability of a normal conditional expression.
8504   } else {
8505     if (LHSKind == NullabilityKind::Nullable ||
8506         RHSKind == NullabilityKind::Nullable)
8507       MergedKind = NullabilityKind::Nullable;
8508     else if (LHSKind == NullabilityKind::NonNull)
8509       MergedKind = RHSKind;
8510     else if (RHSKind == NullabilityKind::NonNull)
8511       MergedKind = LHSKind;
8512     else
8513       MergedKind = NullabilityKind::Unspecified;
8514   }
8515 
8516   // Return if ResTy already has the correct nullability.
8517   if (GetNullability(ResTy) == MergedKind)
8518     return ResTy;
8519 
8520   // Strip all nullability from ResTy.
8521   while (ResTy->getNullability(Ctx))
8522     ResTy = ResTy.getSingleStepDesugaredType(Ctx);
8523 
8524   // Create a new AttributedType with the new nullability kind.
8525   auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
8526   return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
8527 }
8528 
8529 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
8530 /// in the case of a the GNU conditional expr extension.
8531 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
8532                                     SourceLocation ColonLoc,
8533                                     Expr *CondExpr, Expr *LHSExpr,
8534                                     Expr *RHSExpr) {
8535   if (!getLangOpts().CPlusPlus) {
8536     // C cannot handle TypoExpr nodes in the condition because it
8537     // doesn't handle dependent types properly, so make sure any TypoExprs have
8538     // been dealt with before checking the operands.
8539     ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
8540     ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
8541     ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
8542 
8543     if (!CondResult.isUsable())
8544       return ExprError();
8545 
8546     if (LHSExpr) {
8547       if (!LHSResult.isUsable())
8548         return ExprError();
8549     }
8550 
8551     if (!RHSResult.isUsable())
8552       return ExprError();
8553 
8554     CondExpr = CondResult.get();
8555     LHSExpr = LHSResult.get();
8556     RHSExpr = RHSResult.get();
8557   }
8558 
8559   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
8560   // was the condition.
8561   OpaqueValueExpr *opaqueValue = nullptr;
8562   Expr *commonExpr = nullptr;
8563   if (!LHSExpr) {
8564     commonExpr = CondExpr;
8565     // Lower out placeholder types first.  This is important so that we don't
8566     // try to capture a placeholder. This happens in few cases in C++; such
8567     // as Objective-C++'s dictionary subscripting syntax.
8568     if (commonExpr->hasPlaceholderType()) {
8569       ExprResult result = CheckPlaceholderExpr(commonExpr);
8570       if (!result.isUsable()) return ExprError();
8571       commonExpr = result.get();
8572     }
8573     // We usually want to apply unary conversions *before* saving, except
8574     // in the special case of a C++ l-value conditional.
8575     if (!(getLangOpts().CPlusPlus
8576           && !commonExpr->isTypeDependent()
8577           && commonExpr->getValueKind() == RHSExpr->getValueKind()
8578           && commonExpr->isGLValue()
8579           && commonExpr->isOrdinaryOrBitFieldObject()
8580           && RHSExpr->isOrdinaryOrBitFieldObject()
8581           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
8582       ExprResult commonRes = UsualUnaryConversions(commonExpr);
8583       if (commonRes.isInvalid())
8584         return ExprError();
8585       commonExpr = commonRes.get();
8586     }
8587 
8588     // If the common expression is a class or array prvalue, materialize it
8589     // so that we can safely refer to it multiple times.
8590     if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() ||
8591                                    commonExpr->getType()->isArrayType())) {
8592       ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
8593       if (MatExpr.isInvalid())
8594         return ExprError();
8595       commonExpr = MatExpr.get();
8596     }
8597 
8598     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
8599                                                 commonExpr->getType(),
8600                                                 commonExpr->getValueKind(),
8601                                                 commonExpr->getObjectKind(),
8602                                                 commonExpr);
8603     LHSExpr = CondExpr = opaqueValue;
8604   }
8605 
8606   QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
8607   ExprValueKind VK = VK_RValue;
8608   ExprObjectKind OK = OK_Ordinary;
8609   ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
8610   QualType result = CheckConditionalOperands(Cond, LHS, RHS,
8611                                              VK, OK, QuestionLoc);
8612   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
8613       RHS.isInvalid())
8614     return ExprError();
8615 
8616   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
8617                                 RHS.get());
8618 
8619   CheckBoolLikeConversion(Cond.get(), QuestionLoc);
8620 
8621   result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
8622                                          Context);
8623 
8624   if (!commonExpr)
8625     return new (Context)
8626         ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
8627                             RHS.get(), result, VK, OK);
8628 
8629   return new (Context) BinaryConditionalOperator(
8630       commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
8631       ColonLoc, result, VK, OK);
8632 }
8633 
8634 // Check if we have a conversion between incompatible cmse function pointer
8635 // types, that is, a conversion between a function pointer with the
8636 // cmse_nonsecure_call attribute and one without.
8637 static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType,
8638                                           QualType ToType) {
8639   if (const auto *ToFn =
8640           dyn_cast<FunctionType>(S.Context.getCanonicalType(ToType))) {
8641     if (const auto *FromFn =
8642             dyn_cast<FunctionType>(S.Context.getCanonicalType(FromType))) {
8643       FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
8644       FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
8645 
8646       return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall();
8647     }
8648   }
8649   return false;
8650 }
8651 
8652 // checkPointerTypesForAssignment - This is a very tricky routine (despite
8653 // being closely modeled after the C99 spec:-). The odd characteristic of this
8654 // routine is it effectively iqnores the qualifiers on the top level pointee.
8655 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
8656 // FIXME: add a couple examples in this comment.
8657 static Sema::AssignConvertType
8658 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
8659   assert(LHSType.isCanonical() && "LHS not canonicalized!");
8660   assert(RHSType.isCanonical() && "RHS not canonicalized!");
8661 
8662   // get the "pointed to" type (ignoring qualifiers at the top level)
8663   const Type *lhptee, *rhptee;
8664   Qualifiers lhq, rhq;
8665   std::tie(lhptee, lhq) =
8666       cast<PointerType>(LHSType)->getPointeeType().split().asPair();
8667   std::tie(rhptee, rhq) =
8668       cast<PointerType>(RHSType)->getPointeeType().split().asPair();
8669 
8670   Sema::AssignConvertType ConvTy = Sema::Compatible;
8671 
8672   // C99 6.5.16.1p1: This following citation is common to constraints
8673   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
8674   // qualifiers of the type *pointed to* by the right;
8675 
8676   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
8677   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
8678       lhq.compatiblyIncludesObjCLifetime(rhq)) {
8679     // Ignore lifetime for further calculation.
8680     lhq.removeObjCLifetime();
8681     rhq.removeObjCLifetime();
8682   }
8683 
8684   if (!lhq.compatiblyIncludes(rhq)) {
8685     // Treat address-space mismatches as fatal.
8686     if (!lhq.isAddressSpaceSupersetOf(rhq))
8687       return Sema::IncompatiblePointerDiscardsQualifiers;
8688 
8689     // It's okay to add or remove GC or lifetime qualifiers when converting to
8690     // and from void*.
8691     else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
8692                         .compatiblyIncludes(
8693                                 rhq.withoutObjCGCAttr().withoutObjCLifetime())
8694              && (lhptee->isVoidType() || rhptee->isVoidType()))
8695       ; // keep old
8696 
8697     // Treat lifetime mismatches as fatal.
8698     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
8699       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
8700 
8701     // For GCC/MS compatibility, other qualifier mismatches are treated
8702     // as still compatible in C.
8703     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
8704   }
8705 
8706   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
8707   // incomplete type and the other is a pointer to a qualified or unqualified
8708   // version of void...
8709   if (lhptee->isVoidType()) {
8710     if (rhptee->isIncompleteOrObjectType())
8711       return ConvTy;
8712 
8713     // As an extension, we allow cast to/from void* to function pointer.
8714     assert(rhptee->isFunctionType());
8715     return Sema::FunctionVoidPointer;
8716   }
8717 
8718   if (rhptee->isVoidType()) {
8719     if (lhptee->isIncompleteOrObjectType())
8720       return ConvTy;
8721 
8722     // As an extension, we allow cast to/from void* to function pointer.
8723     assert(lhptee->isFunctionType());
8724     return Sema::FunctionVoidPointer;
8725   }
8726 
8727   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
8728   // unqualified versions of compatible types, ...
8729   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
8730   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
8731     // Check if the pointee types are compatible ignoring the sign.
8732     // We explicitly check for char so that we catch "char" vs
8733     // "unsigned char" on systems where "char" is unsigned.
8734     if (lhptee->isCharType())
8735       ltrans = S.Context.UnsignedCharTy;
8736     else if (lhptee->hasSignedIntegerRepresentation())
8737       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
8738 
8739     if (rhptee->isCharType())
8740       rtrans = S.Context.UnsignedCharTy;
8741     else if (rhptee->hasSignedIntegerRepresentation())
8742       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
8743 
8744     if (ltrans == rtrans) {
8745       // Types are compatible ignoring the sign. Qualifier incompatibility
8746       // takes priority over sign incompatibility because the sign
8747       // warning can be disabled.
8748       if (ConvTy != Sema::Compatible)
8749         return ConvTy;
8750 
8751       return Sema::IncompatiblePointerSign;
8752     }
8753 
8754     // If we are a multi-level pointer, it's possible that our issue is simply
8755     // one of qualification - e.g. char ** -> const char ** is not allowed. If
8756     // the eventual target type is the same and the pointers have the same
8757     // level of indirection, this must be the issue.
8758     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
8759       do {
8760         std::tie(lhptee, lhq) =
8761           cast<PointerType>(lhptee)->getPointeeType().split().asPair();
8762         std::tie(rhptee, rhq) =
8763           cast<PointerType>(rhptee)->getPointeeType().split().asPair();
8764 
8765         // Inconsistent address spaces at this point is invalid, even if the
8766         // address spaces would be compatible.
8767         // FIXME: This doesn't catch address space mismatches for pointers of
8768         // different nesting levels, like:
8769         //   __local int *** a;
8770         //   int ** b = a;
8771         // It's not clear how to actually determine when such pointers are
8772         // invalidly incompatible.
8773         if (lhq.getAddressSpace() != rhq.getAddressSpace())
8774           return Sema::IncompatibleNestedPointerAddressSpaceMismatch;
8775 
8776       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
8777 
8778       if (lhptee == rhptee)
8779         return Sema::IncompatibleNestedPointerQualifiers;
8780     }
8781 
8782     // General pointer incompatibility takes priority over qualifiers.
8783     if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType())
8784       return Sema::IncompatibleFunctionPointer;
8785     return Sema::IncompatiblePointer;
8786   }
8787   if (!S.getLangOpts().CPlusPlus &&
8788       S.IsFunctionConversion(ltrans, rtrans, ltrans))
8789     return Sema::IncompatibleFunctionPointer;
8790   if (IsInvalidCmseNSCallConversion(S, ltrans, rtrans))
8791     return Sema::IncompatibleFunctionPointer;
8792   return ConvTy;
8793 }
8794 
8795 /// checkBlockPointerTypesForAssignment - This routine determines whether two
8796 /// block pointer types are compatible or whether a block and normal pointer
8797 /// are compatible. It is more restrict than comparing two function pointer
8798 // types.
8799 static Sema::AssignConvertType
8800 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
8801                                     QualType RHSType) {
8802   assert(LHSType.isCanonical() && "LHS not canonicalized!");
8803   assert(RHSType.isCanonical() && "RHS not canonicalized!");
8804 
8805   QualType lhptee, rhptee;
8806 
8807   // get the "pointed to" type (ignoring qualifiers at the top level)
8808   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
8809   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
8810 
8811   // In C++, the types have to match exactly.
8812   if (S.getLangOpts().CPlusPlus)
8813     return Sema::IncompatibleBlockPointer;
8814 
8815   Sema::AssignConvertType ConvTy = Sema::Compatible;
8816 
8817   // For blocks we enforce that qualifiers are identical.
8818   Qualifiers LQuals = lhptee.getLocalQualifiers();
8819   Qualifiers RQuals = rhptee.getLocalQualifiers();
8820   if (S.getLangOpts().OpenCL) {
8821     LQuals.removeAddressSpace();
8822     RQuals.removeAddressSpace();
8823   }
8824   if (LQuals != RQuals)
8825     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
8826 
8827   // FIXME: OpenCL doesn't define the exact compile time semantics for a block
8828   // assignment.
8829   // The current behavior is similar to C++ lambdas. A block might be
8830   // assigned to a variable iff its return type and parameters are compatible
8831   // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
8832   // an assignment. Presumably it should behave in way that a function pointer
8833   // assignment does in C, so for each parameter and return type:
8834   //  * CVR and address space of LHS should be a superset of CVR and address
8835   //  space of RHS.
8836   //  * unqualified types should be compatible.
8837   if (S.getLangOpts().OpenCL) {
8838     if (!S.Context.typesAreBlockPointerCompatible(
8839             S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
8840             S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
8841       return Sema::IncompatibleBlockPointer;
8842   } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
8843     return Sema::IncompatibleBlockPointer;
8844 
8845   return ConvTy;
8846 }
8847 
8848 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
8849 /// for assignment compatibility.
8850 static Sema::AssignConvertType
8851 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
8852                                    QualType RHSType) {
8853   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
8854   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
8855 
8856   if (LHSType->isObjCBuiltinType()) {
8857     // Class is not compatible with ObjC object pointers.
8858     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
8859         !RHSType->isObjCQualifiedClassType())
8860       return Sema::IncompatiblePointer;
8861     return Sema::Compatible;
8862   }
8863   if (RHSType->isObjCBuiltinType()) {
8864     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
8865         !LHSType->isObjCQualifiedClassType())
8866       return Sema::IncompatiblePointer;
8867     return Sema::Compatible;
8868   }
8869   QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
8870   QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
8871 
8872   if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
8873       // make an exception for id<P>
8874       !LHSType->isObjCQualifiedIdType())
8875     return Sema::CompatiblePointerDiscardsQualifiers;
8876 
8877   if (S.Context.typesAreCompatible(LHSType, RHSType))
8878     return Sema::Compatible;
8879   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
8880     return Sema::IncompatibleObjCQualifiedId;
8881   return Sema::IncompatiblePointer;
8882 }
8883 
8884 Sema::AssignConvertType
8885 Sema::CheckAssignmentConstraints(SourceLocation Loc,
8886                                  QualType LHSType, QualType RHSType) {
8887   // Fake up an opaque expression.  We don't actually care about what
8888   // cast operations are required, so if CheckAssignmentConstraints
8889   // adds casts to this they'll be wasted, but fortunately that doesn't
8890   // usually happen on valid code.
8891   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
8892   ExprResult RHSPtr = &RHSExpr;
8893   CastKind K;
8894 
8895   return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
8896 }
8897 
8898 /// This helper function returns true if QT is a vector type that has element
8899 /// type ElementType.
8900 static bool isVector(QualType QT, QualType ElementType) {
8901   if (const VectorType *VT = QT->getAs<VectorType>())
8902     return VT->getElementType().getCanonicalType() == ElementType;
8903   return false;
8904 }
8905 
8906 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
8907 /// has code to accommodate several GCC extensions when type checking
8908 /// pointers. Here are some objectionable examples that GCC considers warnings:
8909 ///
8910 ///  int a, *pint;
8911 ///  short *pshort;
8912 ///  struct foo *pfoo;
8913 ///
8914 ///  pint = pshort; // warning: assignment from incompatible pointer type
8915 ///  a = pint; // warning: assignment makes integer from pointer without a cast
8916 ///  pint = a; // warning: assignment makes pointer from integer without a cast
8917 ///  pint = pfoo; // warning: assignment from incompatible pointer type
8918 ///
8919 /// As a result, the code for dealing with pointers is more complex than the
8920 /// C99 spec dictates.
8921 ///
8922 /// Sets 'Kind' for any result kind except Incompatible.
8923 Sema::AssignConvertType
8924 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
8925                                  CastKind &Kind, bool ConvertRHS) {
8926   QualType RHSType = RHS.get()->getType();
8927   QualType OrigLHSType = LHSType;
8928 
8929   // Get canonical types.  We're not formatting these types, just comparing
8930   // them.
8931   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
8932   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
8933 
8934   // Common case: no conversion required.
8935   if (LHSType == RHSType) {
8936     Kind = CK_NoOp;
8937     return Compatible;
8938   }
8939 
8940   // If we have an atomic type, try a non-atomic assignment, then just add an
8941   // atomic qualification step.
8942   if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
8943     Sema::AssignConvertType result =
8944       CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
8945     if (result != Compatible)
8946       return result;
8947     if (Kind != CK_NoOp && ConvertRHS)
8948       RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
8949     Kind = CK_NonAtomicToAtomic;
8950     return Compatible;
8951   }
8952 
8953   // If the left-hand side is a reference type, then we are in a
8954   // (rare!) case where we've allowed the use of references in C,
8955   // e.g., as a parameter type in a built-in function. In this case,
8956   // just make sure that the type referenced is compatible with the
8957   // right-hand side type. The caller is responsible for adjusting
8958   // LHSType so that the resulting expression does not have reference
8959   // type.
8960   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
8961     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
8962       Kind = CK_LValueBitCast;
8963       return Compatible;
8964     }
8965     return Incompatible;
8966   }
8967 
8968   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
8969   // to the same ExtVector type.
8970   if (LHSType->isExtVectorType()) {
8971     if (RHSType->isExtVectorType())
8972       return Incompatible;
8973     if (RHSType->isArithmeticType()) {
8974       // CK_VectorSplat does T -> vector T, so first cast to the element type.
8975       if (ConvertRHS)
8976         RHS = prepareVectorSplat(LHSType, RHS.get());
8977       Kind = CK_VectorSplat;
8978       return Compatible;
8979     }
8980   }
8981 
8982   // Conversions to or from vector type.
8983   if (LHSType->isVectorType() || RHSType->isVectorType()) {
8984     if (LHSType->isVectorType() && RHSType->isVectorType()) {
8985       // Allow assignments of an AltiVec vector type to an equivalent GCC
8986       // vector type and vice versa
8987       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
8988         Kind = CK_BitCast;
8989         return Compatible;
8990       }
8991 
8992       // If we are allowing lax vector conversions, and LHS and RHS are both
8993       // vectors, the total size only needs to be the same. This is a bitcast;
8994       // no bits are changed but the result type is different.
8995       if (isLaxVectorConversion(RHSType, LHSType)) {
8996         Kind = CK_BitCast;
8997         return IncompatibleVectors;
8998       }
8999     }
9000 
9001     // When the RHS comes from another lax conversion (e.g. binops between
9002     // scalars and vectors) the result is canonicalized as a vector. When the
9003     // LHS is also a vector, the lax is allowed by the condition above. Handle
9004     // the case where LHS is a scalar.
9005     if (LHSType->isScalarType()) {
9006       const VectorType *VecType = RHSType->getAs<VectorType>();
9007       if (VecType && VecType->getNumElements() == 1 &&
9008           isLaxVectorConversion(RHSType, LHSType)) {
9009         ExprResult *VecExpr = &RHS;
9010         *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
9011         Kind = CK_BitCast;
9012         return Compatible;
9013       }
9014     }
9015 
9016     // Allow assignments between fixed-length and sizeless SVE vectors.
9017     if (((LHSType->isSizelessBuiltinType() && RHSType->isVectorType()) ||
9018          (LHSType->isVectorType() && RHSType->isSizelessBuiltinType())) &&
9019         Context.areCompatibleSveTypes(LHSType, RHSType)) {
9020       Kind = CK_BitCast;
9021       return Compatible;
9022     }
9023 
9024     return Incompatible;
9025   }
9026 
9027   // Diagnose attempts to convert between __float128 and long double where
9028   // such conversions currently can't be handled.
9029   if (unsupportedTypeConversion(*this, LHSType, RHSType))
9030     return Incompatible;
9031 
9032   // Disallow assigning a _Complex to a real type in C++ mode since it simply
9033   // discards the imaginary part.
9034   if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
9035       !LHSType->getAs<ComplexType>())
9036     return Incompatible;
9037 
9038   // Arithmetic conversions.
9039   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
9040       !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
9041     if (ConvertRHS)
9042       Kind = PrepareScalarCast(RHS, LHSType);
9043     return Compatible;
9044   }
9045 
9046   // Conversions to normal pointers.
9047   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
9048     // U* -> T*
9049     if (isa<PointerType>(RHSType)) {
9050       LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9051       LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
9052       if (AddrSpaceL != AddrSpaceR)
9053         Kind = CK_AddressSpaceConversion;
9054       else if (Context.hasCvrSimilarType(RHSType, LHSType))
9055         Kind = CK_NoOp;
9056       else
9057         Kind = CK_BitCast;
9058       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
9059     }
9060 
9061     // int -> T*
9062     if (RHSType->isIntegerType()) {
9063       Kind = CK_IntegralToPointer; // FIXME: null?
9064       return IntToPointer;
9065     }
9066 
9067     // C pointers are not compatible with ObjC object pointers,
9068     // with two exceptions:
9069     if (isa<ObjCObjectPointerType>(RHSType)) {
9070       //  - conversions to void*
9071       if (LHSPointer->getPointeeType()->isVoidType()) {
9072         Kind = CK_BitCast;
9073         return Compatible;
9074       }
9075 
9076       //  - conversions from 'Class' to the redefinition type
9077       if (RHSType->isObjCClassType() &&
9078           Context.hasSameType(LHSType,
9079                               Context.getObjCClassRedefinitionType())) {
9080         Kind = CK_BitCast;
9081         return Compatible;
9082       }
9083 
9084       Kind = CK_BitCast;
9085       return IncompatiblePointer;
9086     }
9087 
9088     // U^ -> void*
9089     if (RHSType->getAs<BlockPointerType>()) {
9090       if (LHSPointer->getPointeeType()->isVoidType()) {
9091         LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9092         LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9093                                 ->getPointeeType()
9094                                 .getAddressSpace();
9095         Kind =
9096             AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9097         return Compatible;
9098       }
9099     }
9100 
9101     return Incompatible;
9102   }
9103 
9104   // Conversions to block pointers.
9105   if (isa<BlockPointerType>(LHSType)) {
9106     // U^ -> T^
9107     if (RHSType->isBlockPointerType()) {
9108       LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
9109                               ->getPointeeType()
9110                               .getAddressSpace();
9111       LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9112                               ->getPointeeType()
9113                               .getAddressSpace();
9114       Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9115       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
9116     }
9117 
9118     // int or null -> T^
9119     if (RHSType->isIntegerType()) {
9120       Kind = CK_IntegralToPointer; // FIXME: null
9121       return IntToBlockPointer;
9122     }
9123 
9124     // id -> T^
9125     if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
9126       Kind = CK_AnyPointerToBlockPointerCast;
9127       return Compatible;
9128     }
9129 
9130     // void* -> T^
9131     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
9132       if (RHSPT->getPointeeType()->isVoidType()) {
9133         Kind = CK_AnyPointerToBlockPointerCast;
9134         return Compatible;
9135       }
9136 
9137     return Incompatible;
9138   }
9139 
9140   // Conversions to Objective-C pointers.
9141   if (isa<ObjCObjectPointerType>(LHSType)) {
9142     // A* -> B*
9143     if (RHSType->isObjCObjectPointerType()) {
9144       Kind = CK_BitCast;
9145       Sema::AssignConvertType result =
9146         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
9147       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9148           result == Compatible &&
9149           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
9150         result = IncompatibleObjCWeakRef;
9151       return result;
9152     }
9153 
9154     // int or null -> A*
9155     if (RHSType->isIntegerType()) {
9156       Kind = CK_IntegralToPointer; // FIXME: null
9157       return IntToPointer;
9158     }
9159 
9160     // In general, C pointers are not compatible with ObjC object pointers,
9161     // with two exceptions:
9162     if (isa<PointerType>(RHSType)) {
9163       Kind = CK_CPointerToObjCPointerCast;
9164 
9165       //  - conversions from 'void*'
9166       if (RHSType->isVoidPointerType()) {
9167         return Compatible;
9168       }
9169 
9170       //  - conversions to 'Class' from its redefinition type
9171       if (LHSType->isObjCClassType() &&
9172           Context.hasSameType(RHSType,
9173                               Context.getObjCClassRedefinitionType())) {
9174         return Compatible;
9175       }
9176 
9177       return IncompatiblePointer;
9178     }
9179 
9180     // Only under strict condition T^ is compatible with an Objective-C pointer.
9181     if (RHSType->isBlockPointerType() &&
9182         LHSType->isBlockCompatibleObjCPointerType(Context)) {
9183       if (ConvertRHS)
9184         maybeExtendBlockObject(RHS);
9185       Kind = CK_BlockPointerToObjCPointerCast;
9186       return Compatible;
9187     }
9188 
9189     return Incompatible;
9190   }
9191 
9192   // Conversions from pointers that are not covered by the above.
9193   if (isa<PointerType>(RHSType)) {
9194     // T* -> _Bool
9195     if (LHSType == Context.BoolTy) {
9196       Kind = CK_PointerToBoolean;
9197       return Compatible;
9198     }
9199 
9200     // T* -> int
9201     if (LHSType->isIntegerType()) {
9202       Kind = CK_PointerToIntegral;
9203       return PointerToInt;
9204     }
9205 
9206     return Incompatible;
9207   }
9208 
9209   // Conversions from Objective-C pointers that are not covered by the above.
9210   if (isa<ObjCObjectPointerType>(RHSType)) {
9211     // T* -> _Bool
9212     if (LHSType == Context.BoolTy) {
9213       Kind = CK_PointerToBoolean;
9214       return Compatible;
9215     }
9216 
9217     // T* -> int
9218     if (LHSType->isIntegerType()) {
9219       Kind = CK_PointerToIntegral;
9220       return PointerToInt;
9221     }
9222 
9223     return Incompatible;
9224   }
9225 
9226   // struct A -> struct B
9227   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
9228     if (Context.typesAreCompatible(LHSType, RHSType)) {
9229       Kind = CK_NoOp;
9230       return Compatible;
9231     }
9232   }
9233 
9234   if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
9235     Kind = CK_IntToOCLSampler;
9236     return Compatible;
9237   }
9238 
9239   return Incompatible;
9240 }
9241 
9242 /// Constructs a transparent union from an expression that is
9243 /// used to initialize the transparent union.
9244 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
9245                                       ExprResult &EResult, QualType UnionType,
9246                                       FieldDecl *Field) {
9247   // Build an initializer list that designates the appropriate member
9248   // of the transparent union.
9249   Expr *E = EResult.get();
9250   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
9251                                                    E, SourceLocation());
9252   Initializer->setType(UnionType);
9253   Initializer->setInitializedFieldInUnion(Field);
9254 
9255   // Build a compound literal constructing a value of the transparent
9256   // union type from this initializer list.
9257   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
9258   EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
9259                                         VK_RValue, Initializer, false);
9260 }
9261 
9262 Sema::AssignConvertType
9263 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
9264                                                ExprResult &RHS) {
9265   QualType RHSType = RHS.get()->getType();
9266 
9267   // If the ArgType is a Union type, we want to handle a potential
9268   // transparent_union GCC extension.
9269   const RecordType *UT = ArgType->getAsUnionType();
9270   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
9271     return Incompatible;
9272 
9273   // The field to initialize within the transparent union.
9274   RecordDecl *UD = UT->getDecl();
9275   FieldDecl *InitField = nullptr;
9276   // It's compatible if the expression matches any of the fields.
9277   for (auto *it : UD->fields()) {
9278     if (it->getType()->isPointerType()) {
9279       // If the transparent union contains a pointer type, we allow:
9280       // 1) void pointer
9281       // 2) null pointer constant
9282       if (RHSType->isPointerType())
9283         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
9284           RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
9285           InitField = it;
9286           break;
9287         }
9288 
9289       if (RHS.get()->isNullPointerConstant(Context,
9290                                            Expr::NPC_ValueDependentIsNull)) {
9291         RHS = ImpCastExprToType(RHS.get(), it->getType(),
9292                                 CK_NullToPointer);
9293         InitField = it;
9294         break;
9295       }
9296     }
9297 
9298     CastKind Kind;
9299     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
9300           == Compatible) {
9301       RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
9302       InitField = it;
9303       break;
9304     }
9305   }
9306 
9307   if (!InitField)
9308     return Incompatible;
9309 
9310   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
9311   return Compatible;
9312 }
9313 
9314 Sema::AssignConvertType
9315 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
9316                                        bool Diagnose,
9317                                        bool DiagnoseCFAudited,
9318                                        bool ConvertRHS) {
9319   // We need to be able to tell the caller whether we diagnosed a problem, if
9320   // they ask us to issue diagnostics.
9321   assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
9322 
9323   // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
9324   // we can't avoid *all* modifications at the moment, so we need some somewhere
9325   // to put the updated value.
9326   ExprResult LocalRHS = CallerRHS;
9327   ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
9328 
9329   if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
9330     if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
9331       if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
9332           !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
9333         Diag(RHS.get()->getExprLoc(),
9334              diag::warn_noderef_to_dereferenceable_pointer)
9335             << RHS.get()->getSourceRange();
9336       }
9337     }
9338   }
9339 
9340   if (getLangOpts().CPlusPlus) {
9341     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
9342       // C++ 5.17p3: If the left operand is not of class type, the
9343       // expression is implicitly converted (C++ 4) to the
9344       // cv-unqualified type of the left operand.
9345       QualType RHSType = RHS.get()->getType();
9346       if (Diagnose) {
9347         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9348                                         AA_Assigning);
9349       } else {
9350         ImplicitConversionSequence ICS =
9351             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9352                                   /*SuppressUserConversions=*/false,
9353                                   AllowedExplicit::None,
9354                                   /*InOverloadResolution=*/false,
9355                                   /*CStyle=*/false,
9356                                   /*AllowObjCWritebackConversion=*/false);
9357         if (ICS.isFailure())
9358           return Incompatible;
9359         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9360                                         ICS, AA_Assigning);
9361       }
9362       if (RHS.isInvalid())
9363         return Incompatible;
9364       Sema::AssignConvertType result = Compatible;
9365       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9366           !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
9367         result = IncompatibleObjCWeakRef;
9368       return result;
9369     }
9370 
9371     // FIXME: Currently, we fall through and treat C++ classes like C
9372     // structures.
9373     // FIXME: We also fall through for atomics; not sure what should
9374     // happen there, though.
9375   } else if (RHS.get()->getType() == Context.OverloadTy) {
9376     // As a set of extensions to C, we support overloading on functions. These
9377     // functions need to be resolved here.
9378     DeclAccessPair DAP;
9379     if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
9380             RHS.get(), LHSType, /*Complain=*/false, DAP))
9381       RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
9382     else
9383       return Incompatible;
9384   }
9385 
9386   // C99 6.5.16.1p1: the left operand is a pointer and the right is
9387   // a null pointer constant.
9388   if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
9389        LHSType->isBlockPointerType()) &&
9390       RHS.get()->isNullPointerConstant(Context,
9391                                        Expr::NPC_ValueDependentIsNull)) {
9392     if (Diagnose || ConvertRHS) {
9393       CastKind Kind;
9394       CXXCastPath Path;
9395       CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
9396                              /*IgnoreBaseAccess=*/false, Diagnose);
9397       if (ConvertRHS)
9398         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
9399     }
9400     return Compatible;
9401   }
9402 
9403   // OpenCL queue_t type assignment.
9404   if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
9405                                  Context, Expr::NPC_ValueDependentIsNull)) {
9406     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9407     return Compatible;
9408   }
9409 
9410   // This check seems unnatural, however it is necessary to ensure the proper
9411   // conversion of functions/arrays. If the conversion were done for all
9412   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
9413   // expressions that suppress this implicit conversion (&, sizeof).
9414   //
9415   // Suppress this for references: C++ 8.5.3p5.
9416   if (!LHSType->isReferenceType()) {
9417     // FIXME: We potentially allocate here even if ConvertRHS is false.
9418     RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
9419     if (RHS.isInvalid())
9420       return Incompatible;
9421   }
9422   CastKind Kind;
9423   Sema::AssignConvertType result =
9424     CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
9425 
9426   // C99 6.5.16.1p2: The value of the right operand is converted to the
9427   // type of the assignment expression.
9428   // CheckAssignmentConstraints allows the left-hand side to be a reference,
9429   // so that we can use references in built-in functions even in C.
9430   // The getNonReferenceType() call makes sure that the resulting expression
9431   // does not have reference type.
9432   if (result != Incompatible && RHS.get()->getType() != LHSType) {
9433     QualType Ty = LHSType.getNonLValueExprType(Context);
9434     Expr *E = RHS.get();
9435 
9436     // Check for various Objective-C errors. If we are not reporting
9437     // diagnostics and just checking for errors, e.g., during overload
9438     // resolution, return Incompatible to indicate the failure.
9439     if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9440         CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
9441                             Diagnose, DiagnoseCFAudited) != ACR_okay) {
9442       if (!Diagnose)
9443         return Incompatible;
9444     }
9445     if (getLangOpts().ObjC &&
9446         (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType,
9447                                            E->getType(), E, Diagnose) ||
9448          CheckConversionToObjCLiteral(LHSType, E, Diagnose))) {
9449       if (!Diagnose)
9450         return Incompatible;
9451       // Replace the expression with a corrected version and continue so we
9452       // can find further errors.
9453       RHS = E;
9454       return Compatible;
9455     }
9456 
9457     if (ConvertRHS)
9458       RHS = ImpCastExprToType(E, Ty, Kind);
9459   }
9460 
9461   return result;
9462 }
9463 
9464 namespace {
9465 /// The original operand to an operator, prior to the application of the usual
9466 /// arithmetic conversions and converting the arguments of a builtin operator
9467 /// candidate.
9468 struct OriginalOperand {
9469   explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
9470     if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op))
9471       Op = MTE->getSubExpr();
9472     if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op))
9473       Op = BTE->getSubExpr();
9474     if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) {
9475       Orig = ICE->getSubExprAsWritten();
9476       Conversion = ICE->getConversionFunction();
9477     }
9478   }
9479 
9480   QualType getType() const { return Orig->getType(); }
9481 
9482   Expr *Orig;
9483   NamedDecl *Conversion;
9484 };
9485 }
9486 
9487 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
9488                                ExprResult &RHS) {
9489   OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
9490 
9491   Diag(Loc, diag::err_typecheck_invalid_operands)
9492     << OrigLHS.getType() << OrigRHS.getType()
9493     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9494 
9495   // If a user-defined conversion was applied to either of the operands prior
9496   // to applying the built-in operator rules, tell the user about it.
9497   if (OrigLHS.Conversion) {
9498     Diag(OrigLHS.Conversion->getLocation(),
9499          diag::note_typecheck_invalid_operands_converted)
9500       << 0 << LHS.get()->getType();
9501   }
9502   if (OrigRHS.Conversion) {
9503     Diag(OrigRHS.Conversion->getLocation(),
9504          diag::note_typecheck_invalid_operands_converted)
9505       << 1 << RHS.get()->getType();
9506   }
9507 
9508   return QualType();
9509 }
9510 
9511 // Diagnose cases where a scalar was implicitly converted to a vector and
9512 // diagnose the underlying types. Otherwise, diagnose the error
9513 // as invalid vector logical operands for non-C++ cases.
9514 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
9515                                             ExprResult &RHS) {
9516   QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
9517   QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
9518 
9519   bool LHSNatVec = LHSType->isVectorType();
9520   bool RHSNatVec = RHSType->isVectorType();
9521 
9522   if (!(LHSNatVec && RHSNatVec)) {
9523     Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
9524     Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
9525     Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
9526         << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
9527         << Vector->getSourceRange();
9528     return QualType();
9529   }
9530 
9531   Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
9532       << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
9533       << RHS.get()->getSourceRange();
9534 
9535   return QualType();
9536 }
9537 
9538 /// Try to convert a value of non-vector type to a vector type by converting
9539 /// the type to the element type of the vector and then performing a splat.
9540 /// If the language is OpenCL, we only use conversions that promote scalar
9541 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
9542 /// for float->int.
9543 ///
9544 /// OpenCL V2.0 6.2.6.p2:
9545 /// An error shall occur if any scalar operand type has greater rank
9546 /// than the type of the vector element.
9547 ///
9548 /// \param scalar - if non-null, actually perform the conversions
9549 /// \return true if the operation fails (but without diagnosing the failure)
9550 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
9551                                      QualType scalarTy,
9552                                      QualType vectorEltTy,
9553                                      QualType vectorTy,
9554                                      unsigned &DiagID) {
9555   // The conversion to apply to the scalar before splatting it,
9556   // if necessary.
9557   CastKind scalarCast = CK_NoOp;
9558 
9559   if (vectorEltTy->isIntegralType(S.Context)) {
9560     if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
9561         (scalarTy->isIntegerType() &&
9562          S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
9563       DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
9564       return true;
9565     }
9566     if (!scalarTy->isIntegralType(S.Context))
9567       return true;
9568     scalarCast = CK_IntegralCast;
9569   } else if (vectorEltTy->isRealFloatingType()) {
9570     if (scalarTy->isRealFloatingType()) {
9571       if (S.getLangOpts().OpenCL &&
9572           S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
9573         DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
9574         return true;
9575       }
9576       scalarCast = CK_FloatingCast;
9577     }
9578     else if (scalarTy->isIntegralType(S.Context))
9579       scalarCast = CK_IntegralToFloating;
9580     else
9581       return true;
9582   } else {
9583     return true;
9584   }
9585 
9586   // Adjust scalar if desired.
9587   if (scalar) {
9588     if (scalarCast != CK_NoOp)
9589       *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
9590     *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
9591   }
9592   return false;
9593 }
9594 
9595 /// Convert vector E to a vector with the same number of elements but different
9596 /// element type.
9597 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
9598   const auto *VecTy = E->getType()->getAs<VectorType>();
9599   assert(VecTy && "Expression E must be a vector");
9600   QualType NewVecTy = S.Context.getVectorType(ElementType,
9601                                               VecTy->getNumElements(),
9602                                               VecTy->getVectorKind());
9603 
9604   // Look through the implicit cast. Return the subexpression if its type is
9605   // NewVecTy.
9606   if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
9607     if (ICE->getSubExpr()->getType() == NewVecTy)
9608       return ICE->getSubExpr();
9609 
9610   auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
9611   return S.ImpCastExprToType(E, NewVecTy, Cast);
9612 }
9613 
9614 /// Test if a (constant) integer Int can be casted to another integer type
9615 /// IntTy without losing precision.
9616 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int,
9617                                       QualType OtherIntTy) {
9618   QualType IntTy = Int->get()->getType().getUnqualifiedType();
9619 
9620   // Reject cases where the value of the Int is unknown as that would
9621   // possibly cause truncation, but accept cases where the scalar can be
9622   // demoted without loss of precision.
9623   Expr::EvalResult EVResult;
9624   bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
9625   int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
9626   bool IntSigned = IntTy->hasSignedIntegerRepresentation();
9627   bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
9628 
9629   if (CstInt) {
9630     // If the scalar is constant and is of a higher order and has more active
9631     // bits that the vector element type, reject it.
9632     llvm::APSInt Result = EVResult.Val.getInt();
9633     unsigned NumBits = IntSigned
9634                            ? (Result.isNegative() ? Result.getMinSignedBits()
9635                                                   : Result.getActiveBits())
9636                            : Result.getActiveBits();
9637     if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
9638       return true;
9639 
9640     // If the signedness of the scalar type and the vector element type
9641     // differs and the number of bits is greater than that of the vector
9642     // element reject it.
9643     return (IntSigned != OtherIntSigned &&
9644             NumBits > S.Context.getIntWidth(OtherIntTy));
9645   }
9646 
9647   // Reject cases where the value of the scalar is not constant and it's
9648   // order is greater than that of the vector element type.
9649   return (Order < 0);
9650 }
9651 
9652 /// Test if a (constant) integer Int can be casted to floating point type
9653 /// FloatTy without losing precision.
9654 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int,
9655                                      QualType FloatTy) {
9656   QualType IntTy = Int->get()->getType().getUnqualifiedType();
9657 
9658   // Determine if the integer constant can be expressed as a floating point
9659   // number of the appropriate type.
9660   Expr::EvalResult EVResult;
9661   bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
9662 
9663   uint64_t Bits = 0;
9664   if (CstInt) {
9665     // Reject constants that would be truncated if they were converted to
9666     // the floating point type. Test by simple to/from conversion.
9667     // FIXME: Ideally the conversion to an APFloat and from an APFloat
9668     //        could be avoided if there was a convertFromAPInt method
9669     //        which could signal back if implicit truncation occurred.
9670     llvm::APSInt Result = EVResult.Val.getInt();
9671     llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
9672     Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
9673                            llvm::APFloat::rmTowardZero);
9674     llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
9675                              !IntTy->hasSignedIntegerRepresentation());
9676     bool Ignored = false;
9677     Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
9678                            &Ignored);
9679     if (Result != ConvertBack)
9680       return true;
9681   } else {
9682     // Reject types that cannot be fully encoded into the mantissa of
9683     // the float.
9684     Bits = S.Context.getTypeSize(IntTy);
9685     unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
9686         S.Context.getFloatTypeSemantics(FloatTy));
9687     if (Bits > FloatPrec)
9688       return true;
9689   }
9690 
9691   return false;
9692 }
9693 
9694 /// Attempt to convert and splat Scalar into a vector whose types matches
9695 /// Vector following GCC conversion rules. The rule is that implicit
9696 /// conversion can occur when Scalar can be casted to match Vector's element
9697 /// type without causing truncation of Scalar.
9698 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar,
9699                                         ExprResult *Vector) {
9700   QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
9701   QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
9702   const VectorType *VT = VectorTy->getAs<VectorType>();
9703 
9704   assert(!isa<ExtVectorType>(VT) &&
9705          "ExtVectorTypes should not be handled here!");
9706 
9707   QualType VectorEltTy = VT->getElementType();
9708 
9709   // Reject cases where the vector element type or the scalar element type are
9710   // not integral or floating point types.
9711   if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
9712     return true;
9713 
9714   // The conversion to apply to the scalar before splatting it,
9715   // if necessary.
9716   CastKind ScalarCast = CK_NoOp;
9717 
9718   // Accept cases where the vector elements are integers and the scalar is
9719   // an integer.
9720   // FIXME: Notionally if the scalar was a floating point value with a precise
9721   //        integral representation, we could cast it to an appropriate integer
9722   //        type and then perform the rest of the checks here. GCC will perform
9723   //        this conversion in some cases as determined by the input language.
9724   //        We should accept it on a language independent basis.
9725   if (VectorEltTy->isIntegralType(S.Context) &&
9726       ScalarTy->isIntegralType(S.Context) &&
9727       S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
9728 
9729     if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
9730       return true;
9731 
9732     ScalarCast = CK_IntegralCast;
9733   } else if (VectorEltTy->isIntegralType(S.Context) &&
9734              ScalarTy->isRealFloatingType()) {
9735     if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy))
9736       ScalarCast = CK_FloatingToIntegral;
9737     else
9738       return true;
9739   } else if (VectorEltTy->isRealFloatingType()) {
9740     if (ScalarTy->isRealFloatingType()) {
9741 
9742       // Reject cases where the scalar type is not a constant and has a higher
9743       // Order than the vector element type.
9744       llvm::APFloat Result(0.0);
9745 
9746       // Determine whether this is a constant scalar. In the event that the
9747       // value is dependent (and thus cannot be evaluated by the constant
9748       // evaluator), skip the evaluation. This will then diagnose once the
9749       // expression is instantiated.
9750       bool CstScalar = Scalar->get()->isValueDependent() ||
9751                        Scalar->get()->EvaluateAsFloat(Result, S.Context);
9752       int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
9753       if (!CstScalar && Order < 0)
9754         return true;
9755 
9756       // If the scalar cannot be safely casted to the vector element type,
9757       // reject it.
9758       if (CstScalar) {
9759         bool Truncated = false;
9760         Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
9761                        llvm::APFloat::rmNearestTiesToEven, &Truncated);
9762         if (Truncated)
9763           return true;
9764       }
9765 
9766       ScalarCast = CK_FloatingCast;
9767     } else if (ScalarTy->isIntegralType(S.Context)) {
9768       if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
9769         return true;
9770 
9771       ScalarCast = CK_IntegralToFloating;
9772     } else
9773       return true;
9774   } else if (ScalarTy->isEnumeralType())
9775     return true;
9776 
9777   // Adjust scalar if desired.
9778   if (Scalar) {
9779     if (ScalarCast != CK_NoOp)
9780       *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
9781     *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
9782   }
9783   return false;
9784 }
9785 
9786 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
9787                                    SourceLocation Loc, bool IsCompAssign,
9788                                    bool AllowBothBool,
9789                                    bool AllowBoolConversions) {
9790   if (!IsCompAssign) {
9791     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
9792     if (LHS.isInvalid())
9793       return QualType();
9794   }
9795   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
9796   if (RHS.isInvalid())
9797     return QualType();
9798 
9799   // For conversion purposes, we ignore any qualifiers.
9800   // For example, "const float" and "float" are equivalent.
9801   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
9802   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
9803 
9804   const VectorType *LHSVecType = LHSType->getAs<VectorType>();
9805   const VectorType *RHSVecType = RHSType->getAs<VectorType>();
9806   assert(LHSVecType || RHSVecType);
9807 
9808   if ((LHSVecType && LHSVecType->getElementType()->isBFloat16Type()) ||
9809       (RHSVecType && RHSVecType->getElementType()->isBFloat16Type()))
9810     return InvalidOperands(Loc, LHS, RHS);
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   // Returns true if the operands are SVE VLA and VLS types.
9915   auto IsSveConversion = [](QualType FirstType, QualType SecondType) {
9916     const VectorType *VecType = SecondType->getAs<VectorType>();
9917     return FirstType->isSizelessBuiltinType() && VecType &&
9918            (VecType->getVectorKind() == VectorType::SveFixedLengthDataVector ||
9919             VecType->getVectorKind() ==
9920                 VectorType::SveFixedLengthPredicateVector);
9921   };
9922 
9923   // If there's a sizeless and fixed-length operand, diagnose that.
9924   if (IsSveConversion(LHSType, RHSType) || IsSveConversion(RHSType, LHSType)) {
9925     Diag(Loc, diag::err_typecheck_vector_not_convertable_sizeless)
9926         << LHSType << RHSType;
9927     return QualType();
9928   }
9929 
9930   // If there's a non-vector, non-real operand, diagnose that.
9931   if ((!RHSVecType && !RHSType->isRealType()) ||
9932       (!LHSVecType && !LHSType->isRealType())) {
9933     Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
9934       << LHSType << RHSType
9935       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9936     return QualType();
9937   }
9938 
9939   // OpenCL V1.1 6.2.6.p1:
9940   // If the operands are of more than one vector type, then an error shall
9941   // occur. Implicit conversions between vector types are not permitted, per
9942   // section 6.2.1.
9943   if (getLangOpts().OpenCL &&
9944       RHSVecType && isa<ExtVectorType>(RHSVecType) &&
9945       LHSVecType && isa<ExtVectorType>(LHSVecType)) {
9946     Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
9947                                                            << RHSType;
9948     return QualType();
9949   }
9950 
9951 
9952   // If there is a vector type that is not a ExtVector and a scalar, we reach
9953   // this point if scalar could not be converted to the vector's element type
9954   // without truncation.
9955   if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
9956       (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
9957     QualType Scalar = LHSVecType ? RHSType : LHSType;
9958     QualType Vector = LHSVecType ? LHSType : RHSType;
9959     unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
9960     Diag(Loc,
9961          diag::err_typecheck_vector_not_convertable_implict_truncation)
9962         << ScalarOrVector << Scalar << Vector;
9963 
9964     return QualType();
9965   }
9966 
9967   // Otherwise, use the generic diagnostic.
9968   Diag(Loc, DiagID)
9969     << LHSType << RHSType
9970     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9971   return QualType();
9972 }
9973 
9974 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
9975 // expression.  These are mainly cases where the null pointer is used as an
9976 // integer instead of a pointer.
9977 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
9978                                 SourceLocation Loc, bool IsCompare) {
9979   // The canonical way to check for a GNU null is with isNullPointerConstant,
9980   // but we use a bit of a hack here for speed; this is a relatively
9981   // hot path, and isNullPointerConstant is slow.
9982   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
9983   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
9984 
9985   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
9986 
9987   // Avoid analyzing cases where the result will either be invalid (and
9988   // diagnosed as such) or entirely valid and not something to warn about.
9989   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
9990       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
9991     return;
9992 
9993   // Comparison operations would not make sense with a null pointer no matter
9994   // what the other expression is.
9995   if (!IsCompare) {
9996     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
9997         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
9998         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
9999     return;
10000   }
10001 
10002   // The rest of the operations only make sense with a null pointer
10003   // if the other expression is a pointer.
10004   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
10005       NonNullType->canDecayToPointerType())
10006     return;
10007 
10008   S.Diag(Loc, diag::warn_null_in_comparison_operation)
10009       << LHSNull /* LHS is NULL */ << NonNullType
10010       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10011 }
10012 
10013 static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS,
10014                                           SourceLocation Loc) {
10015   const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS);
10016   const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS);
10017   if (!LUE || !RUE)
10018     return;
10019   if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
10020       RUE->getKind() != UETT_SizeOf)
10021     return;
10022 
10023   const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens();
10024   QualType LHSTy = LHSArg->getType();
10025   QualType RHSTy;
10026 
10027   if (RUE->isArgumentType())
10028     RHSTy = RUE->getArgumentType();
10029   else
10030     RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
10031 
10032   if (LHSTy->isPointerType() && !RHSTy->isPointerType()) {
10033     if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy))
10034       return;
10035 
10036     S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
10037     if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
10038       if (const ValueDecl *LHSArgDecl = DRE->getDecl())
10039         S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here)
10040             << LHSArgDecl;
10041     }
10042   } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) {
10043     QualType ArrayElemTy = ArrayTy->getElementType();
10044     if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) ||
10045         ArrayElemTy->isDependentType() || RHSTy->isDependentType() ||
10046         RHSTy->isReferenceType() || ArrayElemTy->isCharType() ||
10047         S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy))
10048       return;
10049     S.Diag(Loc, diag::warn_division_sizeof_array)
10050         << LHSArg->getSourceRange() << ArrayElemTy << RHSTy;
10051     if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
10052       if (const ValueDecl *LHSArgDecl = DRE->getDecl())
10053         S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here)
10054             << LHSArgDecl;
10055     }
10056 
10057     S.Diag(Loc, diag::note_precedence_silence) << RHS;
10058   }
10059 }
10060 
10061 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
10062                                                ExprResult &RHS,
10063                                                SourceLocation Loc, bool IsDiv) {
10064   // Check for division/remainder by zero.
10065   Expr::EvalResult RHSValue;
10066   if (!RHS.get()->isValueDependent() &&
10067       RHS.get()->EvaluateAsInt(RHSValue, S.Context) &&
10068       RHSValue.Val.getInt() == 0)
10069     S.DiagRuntimeBehavior(Loc, RHS.get(),
10070                           S.PDiag(diag::warn_remainder_division_by_zero)
10071                             << IsDiv << RHS.get()->getSourceRange());
10072 }
10073 
10074 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
10075                                            SourceLocation Loc,
10076                                            bool IsCompAssign, bool IsDiv) {
10077   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10078 
10079   if (LHS.get()->getType()->isVectorType() ||
10080       RHS.get()->getType()->isVectorType())
10081     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10082                                /*AllowBothBool*/getLangOpts().AltiVec,
10083                                /*AllowBoolConversions*/false);
10084   if (!IsDiv && (LHS.get()->getType()->isConstantMatrixType() ||
10085                  RHS.get()->getType()->isConstantMatrixType()))
10086     return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign);
10087 
10088   QualType compType = UsualArithmeticConversions(
10089       LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
10090   if (LHS.isInvalid() || RHS.isInvalid())
10091     return QualType();
10092 
10093 
10094   if (compType.isNull() || !compType->isArithmeticType())
10095     return InvalidOperands(Loc, LHS, RHS);
10096   if (IsDiv) {
10097     DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
10098     DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc);
10099   }
10100   return compType;
10101 }
10102 
10103 QualType Sema::CheckRemainderOperands(
10104   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
10105   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10106 
10107   if (LHS.get()->getType()->isVectorType() ||
10108       RHS.get()->getType()->isVectorType()) {
10109     if (LHS.get()->getType()->hasIntegerRepresentation() &&
10110         RHS.get()->getType()->hasIntegerRepresentation())
10111       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10112                                  /*AllowBothBool*/getLangOpts().AltiVec,
10113                                  /*AllowBoolConversions*/false);
10114     return InvalidOperands(Loc, LHS, RHS);
10115   }
10116 
10117   QualType compType = UsualArithmeticConversions(
10118       LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
10119   if (LHS.isInvalid() || RHS.isInvalid())
10120     return QualType();
10121 
10122   if (compType.isNull() || !compType->isIntegerType())
10123     return InvalidOperands(Loc, LHS, RHS);
10124   DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
10125   return compType;
10126 }
10127 
10128 /// Diagnose invalid arithmetic on two void pointers.
10129 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
10130                                                 Expr *LHSExpr, Expr *RHSExpr) {
10131   S.Diag(Loc, S.getLangOpts().CPlusPlus
10132                 ? diag::err_typecheck_pointer_arith_void_type
10133                 : diag::ext_gnu_void_ptr)
10134     << 1 /* two pointers */ << LHSExpr->getSourceRange()
10135                             << RHSExpr->getSourceRange();
10136 }
10137 
10138 /// Diagnose invalid arithmetic on a void pointer.
10139 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
10140                                             Expr *Pointer) {
10141   S.Diag(Loc, S.getLangOpts().CPlusPlus
10142                 ? diag::err_typecheck_pointer_arith_void_type
10143                 : diag::ext_gnu_void_ptr)
10144     << 0 /* one pointer */ << Pointer->getSourceRange();
10145 }
10146 
10147 /// Diagnose invalid arithmetic on a null pointer.
10148 ///
10149 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
10150 /// idiom, which we recognize as a GNU extension.
10151 ///
10152 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc,
10153                                             Expr *Pointer, bool IsGNUIdiom) {
10154   if (IsGNUIdiom)
10155     S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
10156       << Pointer->getSourceRange();
10157   else
10158     S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
10159       << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
10160 }
10161 
10162 /// Diagnose invalid arithmetic on two function pointers.
10163 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
10164                                                     Expr *LHS, Expr *RHS) {
10165   assert(LHS->getType()->isAnyPointerType());
10166   assert(RHS->getType()->isAnyPointerType());
10167   S.Diag(Loc, S.getLangOpts().CPlusPlus
10168                 ? diag::err_typecheck_pointer_arith_function_type
10169                 : diag::ext_gnu_ptr_func_arith)
10170     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
10171     // We only show the second type if it differs from the first.
10172     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
10173                                                    RHS->getType())
10174     << RHS->getType()->getPointeeType()
10175     << LHS->getSourceRange() << RHS->getSourceRange();
10176 }
10177 
10178 /// Diagnose invalid arithmetic on a function pointer.
10179 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
10180                                                 Expr *Pointer) {
10181   assert(Pointer->getType()->isAnyPointerType());
10182   S.Diag(Loc, S.getLangOpts().CPlusPlus
10183                 ? diag::err_typecheck_pointer_arith_function_type
10184                 : diag::ext_gnu_ptr_func_arith)
10185     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
10186     << 0 /* one pointer, so only one type */
10187     << Pointer->getSourceRange();
10188 }
10189 
10190 /// Emit error if Operand is incomplete pointer type
10191 ///
10192 /// \returns True if pointer has incomplete type
10193 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
10194                                                  Expr *Operand) {
10195   QualType ResType = Operand->getType();
10196   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10197     ResType = ResAtomicType->getValueType();
10198 
10199   assert(ResType->isAnyPointerType() && !ResType->isDependentType());
10200   QualType PointeeTy = ResType->getPointeeType();
10201   return S.RequireCompleteSizedType(
10202       Loc, PointeeTy,
10203       diag::err_typecheck_arithmetic_incomplete_or_sizeless_type,
10204       Operand->getSourceRange());
10205 }
10206 
10207 /// Check the validity of an arithmetic pointer operand.
10208 ///
10209 /// If the operand has pointer type, this code will check for pointer types
10210 /// which are invalid in arithmetic operations. These will be diagnosed
10211 /// appropriately, including whether or not the use is supported as an
10212 /// extension.
10213 ///
10214 /// \returns True when the operand is valid to use (even if as an extension).
10215 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
10216                                             Expr *Operand) {
10217   QualType ResType = Operand->getType();
10218   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10219     ResType = ResAtomicType->getValueType();
10220 
10221   if (!ResType->isAnyPointerType()) return true;
10222 
10223   QualType PointeeTy = ResType->getPointeeType();
10224   if (PointeeTy->isVoidType()) {
10225     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
10226     return !S.getLangOpts().CPlusPlus;
10227   }
10228   if (PointeeTy->isFunctionType()) {
10229     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
10230     return !S.getLangOpts().CPlusPlus;
10231   }
10232 
10233   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
10234 
10235   return true;
10236 }
10237 
10238 /// Check the validity of a binary arithmetic operation w.r.t. pointer
10239 /// operands.
10240 ///
10241 /// This routine will diagnose any invalid arithmetic on pointer operands much
10242 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
10243 /// for emitting a single diagnostic even for operations where both LHS and RHS
10244 /// are (potentially problematic) pointers.
10245 ///
10246 /// \returns True when the operand is valid to use (even if as an extension).
10247 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
10248                                                 Expr *LHSExpr, Expr *RHSExpr) {
10249   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
10250   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
10251   if (!isLHSPointer && !isRHSPointer) return true;
10252 
10253   QualType LHSPointeeTy, RHSPointeeTy;
10254   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
10255   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
10256 
10257   // if both are pointers check if operation is valid wrt address spaces
10258   if (isLHSPointer && isRHSPointer) {
10259     if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy)) {
10260       S.Diag(Loc,
10261              diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
10262           << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
10263           << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
10264       return false;
10265     }
10266   }
10267 
10268   // Check for arithmetic on pointers to incomplete types.
10269   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
10270   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
10271   if (isLHSVoidPtr || isRHSVoidPtr) {
10272     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
10273     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
10274     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
10275 
10276     return !S.getLangOpts().CPlusPlus;
10277   }
10278 
10279   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
10280   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
10281   if (isLHSFuncPtr || isRHSFuncPtr) {
10282     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
10283     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
10284                                                                 RHSExpr);
10285     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
10286 
10287     return !S.getLangOpts().CPlusPlus;
10288   }
10289 
10290   if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
10291     return false;
10292   if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
10293     return false;
10294 
10295   return true;
10296 }
10297 
10298 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
10299 /// literal.
10300 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
10301                                   Expr *LHSExpr, Expr *RHSExpr) {
10302   StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
10303   Expr* IndexExpr = RHSExpr;
10304   if (!StrExpr) {
10305     StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
10306     IndexExpr = LHSExpr;
10307   }
10308 
10309   bool IsStringPlusInt = StrExpr &&
10310       IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
10311   if (!IsStringPlusInt || IndexExpr->isValueDependent())
10312     return;
10313 
10314   SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
10315   Self.Diag(OpLoc, diag::warn_string_plus_int)
10316       << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
10317 
10318   // Only print a fixit for "str" + int, not for int + "str".
10319   if (IndexExpr == RHSExpr) {
10320     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
10321     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
10322         << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
10323         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
10324         << FixItHint::CreateInsertion(EndLoc, "]");
10325   } else
10326     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
10327 }
10328 
10329 /// Emit a warning when adding a char literal to a string.
10330 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
10331                                    Expr *LHSExpr, Expr *RHSExpr) {
10332   const Expr *StringRefExpr = LHSExpr;
10333   const CharacterLiteral *CharExpr =
10334       dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
10335 
10336   if (!CharExpr) {
10337     CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
10338     StringRefExpr = RHSExpr;
10339   }
10340 
10341   if (!CharExpr || !StringRefExpr)
10342     return;
10343 
10344   const QualType StringType = StringRefExpr->getType();
10345 
10346   // Return if not a PointerType.
10347   if (!StringType->isAnyPointerType())
10348     return;
10349 
10350   // Return if not a CharacterType.
10351   if (!StringType->getPointeeType()->isAnyCharacterType())
10352     return;
10353 
10354   ASTContext &Ctx = Self.getASTContext();
10355   SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
10356 
10357   const QualType CharType = CharExpr->getType();
10358   if (!CharType->isAnyCharacterType() &&
10359       CharType->isIntegerType() &&
10360       llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
10361     Self.Diag(OpLoc, diag::warn_string_plus_char)
10362         << DiagRange << Ctx.CharTy;
10363   } else {
10364     Self.Diag(OpLoc, diag::warn_string_plus_char)
10365         << DiagRange << CharExpr->getType();
10366   }
10367 
10368   // Only print a fixit for str + char, not for char + str.
10369   if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
10370     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
10371     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
10372         << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
10373         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
10374         << FixItHint::CreateInsertion(EndLoc, "]");
10375   } else {
10376     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
10377   }
10378 }
10379 
10380 /// Emit error when two pointers are incompatible.
10381 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
10382                                            Expr *LHSExpr, Expr *RHSExpr) {
10383   assert(LHSExpr->getType()->isAnyPointerType());
10384   assert(RHSExpr->getType()->isAnyPointerType());
10385   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
10386     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
10387     << RHSExpr->getSourceRange();
10388 }
10389 
10390 // C99 6.5.6
10391 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
10392                                      SourceLocation Loc, BinaryOperatorKind Opc,
10393                                      QualType* CompLHSTy) {
10394   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10395 
10396   if (LHS.get()->getType()->isVectorType() ||
10397       RHS.get()->getType()->isVectorType()) {
10398     QualType compType = CheckVectorOperands(
10399         LHS, RHS, Loc, CompLHSTy,
10400         /*AllowBothBool*/getLangOpts().AltiVec,
10401         /*AllowBoolConversions*/getLangOpts().ZVector);
10402     if (CompLHSTy) *CompLHSTy = compType;
10403     return compType;
10404   }
10405 
10406   if (LHS.get()->getType()->isConstantMatrixType() ||
10407       RHS.get()->getType()->isConstantMatrixType()) {
10408     return CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
10409   }
10410 
10411   QualType compType = UsualArithmeticConversions(
10412       LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
10413   if (LHS.isInvalid() || RHS.isInvalid())
10414     return QualType();
10415 
10416   // Diagnose "string literal" '+' int and string '+' "char literal".
10417   if (Opc == BO_Add) {
10418     diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
10419     diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
10420   }
10421 
10422   // handle the common case first (both operands are arithmetic).
10423   if (!compType.isNull() && compType->isArithmeticType()) {
10424     if (CompLHSTy) *CompLHSTy = compType;
10425     return compType;
10426   }
10427 
10428   // Type-checking.  Ultimately the pointer's going to be in PExp;
10429   // note that we bias towards the LHS being the pointer.
10430   Expr *PExp = LHS.get(), *IExp = RHS.get();
10431 
10432   bool isObjCPointer;
10433   if (PExp->getType()->isPointerType()) {
10434     isObjCPointer = false;
10435   } else if (PExp->getType()->isObjCObjectPointerType()) {
10436     isObjCPointer = true;
10437   } else {
10438     std::swap(PExp, IExp);
10439     if (PExp->getType()->isPointerType()) {
10440       isObjCPointer = false;
10441     } else if (PExp->getType()->isObjCObjectPointerType()) {
10442       isObjCPointer = true;
10443     } else {
10444       return InvalidOperands(Loc, LHS, RHS);
10445     }
10446   }
10447   assert(PExp->getType()->isAnyPointerType());
10448 
10449   if (!IExp->getType()->isIntegerType())
10450     return InvalidOperands(Loc, LHS, RHS);
10451 
10452   // Adding to a null pointer results in undefined behavior.
10453   if (PExp->IgnoreParenCasts()->isNullPointerConstant(
10454           Context, Expr::NPC_ValueDependentIsNotNull)) {
10455     // In C++ adding zero to a null pointer is defined.
10456     Expr::EvalResult KnownVal;
10457     if (!getLangOpts().CPlusPlus ||
10458         (!IExp->isValueDependent() &&
10459          (!IExp->EvaluateAsInt(KnownVal, Context) ||
10460           KnownVal.Val.getInt() != 0))) {
10461       // Check the conditions to see if this is the 'p = nullptr + n' idiom.
10462       bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension(
10463           Context, BO_Add, PExp, IExp);
10464       diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
10465     }
10466   }
10467 
10468   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
10469     return QualType();
10470 
10471   if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
10472     return QualType();
10473 
10474   // Check array bounds for pointer arithemtic
10475   CheckArrayAccess(PExp, IExp);
10476 
10477   if (CompLHSTy) {
10478     QualType LHSTy = Context.isPromotableBitField(LHS.get());
10479     if (LHSTy.isNull()) {
10480       LHSTy = LHS.get()->getType();
10481       if (LHSTy->isPromotableIntegerType())
10482         LHSTy = Context.getPromotedIntegerType(LHSTy);
10483     }
10484     *CompLHSTy = LHSTy;
10485   }
10486 
10487   return PExp->getType();
10488 }
10489 
10490 // C99 6.5.6
10491 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
10492                                         SourceLocation Loc,
10493                                         QualType* CompLHSTy) {
10494   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10495 
10496   if (LHS.get()->getType()->isVectorType() ||
10497       RHS.get()->getType()->isVectorType()) {
10498     QualType compType = CheckVectorOperands(
10499         LHS, RHS, Loc, CompLHSTy,
10500         /*AllowBothBool*/getLangOpts().AltiVec,
10501         /*AllowBoolConversions*/getLangOpts().ZVector);
10502     if (CompLHSTy) *CompLHSTy = compType;
10503     return compType;
10504   }
10505 
10506   if (LHS.get()->getType()->isConstantMatrixType() ||
10507       RHS.get()->getType()->isConstantMatrixType()) {
10508     return CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
10509   }
10510 
10511   QualType compType = UsualArithmeticConversions(
10512       LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
10513   if (LHS.isInvalid() || RHS.isInvalid())
10514     return QualType();
10515 
10516   // Enforce type constraints: C99 6.5.6p3.
10517 
10518   // Handle the common case first (both operands are arithmetic).
10519   if (!compType.isNull() && compType->isArithmeticType()) {
10520     if (CompLHSTy) *CompLHSTy = compType;
10521     return compType;
10522   }
10523 
10524   // Either ptr - int   or   ptr - ptr.
10525   if (LHS.get()->getType()->isAnyPointerType()) {
10526     QualType lpointee = LHS.get()->getType()->getPointeeType();
10527 
10528     // Diagnose bad cases where we step over interface counts.
10529     if (LHS.get()->getType()->isObjCObjectPointerType() &&
10530         checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
10531       return QualType();
10532 
10533     // The result type of a pointer-int computation is the pointer type.
10534     if (RHS.get()->getType()->isIntegerType()) {
10535       // Subtracting from a null pointer should produce a warning.
10536       // The last argument to the diagnose call says this doesn't match the
10537       // GNU int-to-pointer idiom.
10538       if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context,
10539                                            Expr::NPC_ValueDependentIsNotNull)) {
10540         // In C++ adding zero to a null pointer is defined.
10541         Expr::EvalResult KnownVal;
10542         if (!getLangOpts().CPlusPlus ||
10543             (!RHS.get()->isValueDependent() &&
10544              (!RHS.get()->EvaluateAsInt(KnownVal, Context) ||
10545               KnownVal.Val.getInt() != 0))) {
10546           diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
10547         }
10548       }
10549 
10550       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
10551         return QualType();
10552 
10553       // Check array bounds for pointer arithemtic
10554       CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
10555                        /*AllowOnePastEnd*/true, /*IndexNegated*/true);
10556 
10557       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
10558       return LHS.get()->getType();
10559     }
10560 
10561     // Handle pointer-pointer subtractions.
10562     if (const PointerType *RHSPTy
10563           = RHS.get()->getType()->getAs<PointerType>()) {
10564       QualType rpointee = RHSPTy->getPointeeType();
10565 
10566       if (getLangOpts().CPlusPlus) {
10567         // Pointee types must be the same: C++ [expr.add]
10568         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
10569           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
10570         }
10571       } else {
10572         // Pointee types must be compatible C99 6.5.6p3
10573         if (!Context.typesAreCompatible(
10574                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
10575                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
10576           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
10577           return QualType();
10578         }
10579       }
10580 
10581       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
10582                                                LHS.get(), RHS.get()))
10583         return QualType();
10584 
10585       // FIXME: Add warnings for nullptr - ptr.
10586 
10587       // The pointee type may have zero size.  As an extension, a structure or
10588       // union may have zero size or an array may have zero length.  In this
10589       // case subtraction does not make sense.
10590       if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
10591         CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
10592         if (ElementSize.isZero()) {
10593           Diag(Loc,diag::warn_sub_ptr_zero_size_types)
10594             << rpointee.getUnqualifiedType()
10595             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10596         }
10597       }
10598 
10599       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
10600       return Context.getPointerDiffType();
10601     }
10602   }
10603 
10604   return InvalidOperands(Loc, LHS, RHS);
10605 }
10606 
10607 static bool isScopedEnumerationType(QualType T) {
10608   if (const EnumType *ET = T->getAs<EnumType>())
10609     return ET->getDecl()->isScoped();
10610   return false;
10611 }
10612 
10613 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
10614                                    SourceLocation Loc, BinaryOperatorKind Opc,
10615                                    QualType LHSType) {
10616   // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
10617   // so skip remaining warnings as we don't want to modify values within Sema.
10618   if (S.getLangOpts().OpenCL)
10619     return;
10620 
10621   // Check right/shifter operand
10622   Expr::EvalResult RHSResult;
10623   if (RHS.get()->isValueDependent() ||
10624       !RHS.get()->EvaluateAsInt(RHSResult, S.Context))
10625     return;
10626   llvm::APSInt Right = RHSResult.Val.getInt();
10627 
10628   if (Right.isNegative()) {
10629     S.DiagRuntimeBehavior(Loc, RHS.get(),
10630                           S.PDiag(diag::warn_shift_negative)
10631                             << RHS.get()->getSourceRange());
10632     return;
10633   }
10634 
10635   QualType LHSExprType = LHS.get()->getType();
10636   uint64_t LeftSize = S.Context.getTypeSize(LHSExprType);
10637   if (LHSExprType->isExtIntType())
10638     LeftSize = S.Context.getIntWidth(LHSExprType);
10639   else if (LHSExprType->isFixedPointType()) {
10640     auto FXSema = S.Context.getFixedPointSemantics(LHSExprType);
10641     LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding();
10642   }
10643   llvm::APInt LeftBits(Right.getBitWidth(), LeftSize);
10644   if (Right.uge(LeftBits)) {
10645     S.DiagRuntimeBehavior(Loc, RHS.get(),
10646                           S.PDiag(diag::warn_shift_gt_typewidth)
10647                             << RHS.get()->getSourceRange());
10648     return;
10649   }
10650 
10651   // FIXME: We probably need to handle fixed point types specially here.
10652   if (Opc != BO_Shl || LHSExprType->isFixedPointType())
10653     return;
10654 
10655   // When left shifting an ICE which is signed, we can check for overflow which
10656   // according to C++ standards prior to C++2a has undefined behavior
10657   // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one
10658   // more than the maximum value representable in the result type, so never
10659   // warn for those. (FIXME: Unsigned left-shift overflow in a constant
10660   // expression is still probably a bug.)
10661   Expr::EvalResult LHSResult;
10662   if (LHS.get()->isValueDependent() ||
10663       LHSType->hasUnsignedIntegerRepresentation() ||
10664       !LHS.get()->EvaluateAsInt(LHSResult, S.Context))
10665     return;
10666   llvm::APSInt Left = LHSResult.Val.getInt();
10667 
10668   // If LHS does not have a signed type and non-negative value
10669   // then, the behavior is undefined before C++2a. Warn about it.
10670   if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined() &&
10671       !S.getLangOpts().CPlusPlus20) {
10672     S.DiagRuntimeBehavior(Loc, LHS.get(),
10673                           S.PDiag(diag::warn_shift_lhs_negative)
10674                             << LHS.get()->getSourceRange());
10675     return;
10676   }
10677 
10678   llvm::APInt ResultBits =
10679       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
10680   if (LeftBits.uge(ResultBits))
10681     return;
10682   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
10683   Result = Result.shl(Right);
10684 
10685   // Print the bit representation of the signed integer as an unsigned
10686   // hexadecimal number.
10687   SmallString<40> HexResult;
10688   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
10689 
10690   // If we are only missing a sign bit, this is less likely to result in actual
10691   // bugs -- if the result is cast back to an unsigned type, it will have the
10692   // expected value. Thus we place this behind a different warning that can be
10693   // turned off separately if needed.
10694   if (LeftBits == ResultBits - 1) {
10695     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
10696         << HexResult << LHSType
10697         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10698     return;
10699   }
10700 
10701   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
10702     << HexResult.str() << Result.getMinSignedBits() << LHSType
10703     << Left.getBitWidth() << LHS.get()->getSourceRange()
10704     << RHS.get()->getSourceRange();
10705 }
10706 
10707 /// Return the resulting type when a vector is shifted
10708 ///        by a scalar or vector shift amount.
10709 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
10710                                  SourceLocation Loc, bool IsCompAssign) {
10711   // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
10712   if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
10713       !LHS.get()->getType()->isVectorType()) {
10714     S.Diag(Loc, diag::err_shift_rhs_only_vector)
10715       << RHS.get()->getType() << LHS.get()->getType()
10716       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10717     return QualType();
10718   }
10719 
10720   if (!IsCompAssign) {
10721     LHS = S.UsualUnaryConversions(LHS.get());
10722     if (LHS.isInvalid()) return QualType();
10723   }
10724 
10725   RHS = S.UsualUnaryConversions(RHS.get());
10726   if (RHS.isInvalid()) return QualType();
10727 
10728   QualType LHSType = LHS.get()->getType();
10729   // Note that LHS might be a scalar because the routine calls not only in
10730   // OpenCL case.
10731   const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
10732   QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
10733 
10734   // Note that RHS might not be a vector.
10735   QualType RHSType = RHS.get()->getType();
10736   const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
10737   QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
10738 
10739   // The operands need to be integers.
10740   if (!LHSEleType->isIntegerType()) {
10741     S.Diag(Loc, diag::err_typecheck_expect_int)
10742       << LHS.get()->getType() << LHS.get()->getSourceRange();
10743     return QualType();
10744   }
10745 
10746   if (!RHSEleType->isIntegerType()) {
10747     S.Diag(Loc, diag::err_typecheck_expect_int)
10748       << RHS.get()->getType() << RHS.get()->getSourceRange();
10749     return QualType();
10750   }
10751 
10752   if (!LHSVecTy) {
10753     assert(RHSVecTy);
10754     if (IsCompAssign)
10755       return RHSType;
10756     if (LHSEleType != RHSEleType) {
10757       LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
10758       LHSEleType = RHSEleType;
10759     }
10760     QualType VecTy =
10761         S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
10762     LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
10763     LHSType = VecTy;
10764   } else if (RHSVecTy) {
10765     // OpenCL v1.1 s6.3.j says that for vector types, the operators
10766     // are applied component-wise. So if RHS is a vector, then ensure
10767     // that the number of elements is the same as LHS...
10768     if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
10769       S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
10770         << LHS.get()->getType() << RHS.get()->getType()
10771         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10772       return QualType();
10773     }
10774     if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
10775       const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
10776       const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
10777       if (LHSBT != RHSBT &&
10778           S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
10779         S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
10780             << LHS.get()->getType() << RHS.get()->getType()
10781             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10782       }
10783     }
10784   } else {
10785     // ...else expand RHS to match the number of elements in LHS.
10786     QualType VecTy =
10787       S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
10788     RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
10789   }
10790 
10791   return LHSType;
10792 }
10793 
10794 // C99 6.5.7
10795 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
10796                                   SourceLocation Loc, BinaryOperatorKind Opc,
10797                                   bool IsCompAssign) {
10798   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10799 
10800   // Vector shifts promote their scalar inputs to vector type.
10801   if (LHS.get()->getType()->isVectorType() ||
10802       RHS.get()->getType()->isVectorType()) {
10803     if (LangOpts.ZVector) {
10804       // The shift operators for the z vector extensions work basically
10805       // like general shifts, except that neither the LHS nor the RHS is
10806       // allowed to be a "vector bool".
10807       if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
10808         if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
10809           return InvalidOperands(Loc, LHS, RHS);
10810       if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
10811         if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
10812           return InvalidOperands(Loc, LHS, RHS);
10813     }
10814     return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
10815   }
10816 
10817   // Shifts don't perform usual arithmetic conversions, they just do integer
10818   // promotions on each operand. C99 6.5.7p3
10819 
10820   // For the LHS, do usual unary conversions, but then reset them away
10821   // if this is a compound assignment.
10822   ExprResult OldLHS = LHS;
10823   LHS = UsualUnaryConversions(LHS.get());
10824   if (LHS.isInvalid())
10825     return QualType();
10826   QualType LHSType = LHS.get()->getType();
10827   if (IsCompAssign) LHS = OldLHS;
10828 
10829   // The RHS is simpler.
10830   RHS = UsualUnaryConversions(RHS.get());
10831   if (RHS.isInvalid())
10832     return QualType();
10833   QualType RHSType = RHS.get()->getType();
10834 
10835   // C99 6.5.7p2: Each of the operands shall have integer type.
10836   // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point.
10837   if ((!LHSType->isFixedPointOrIntegerType() &&
10838        !LHSType->hasIntegerRepresentation()) ||
10839       !RHSType->hasIntegerRepresentation())
10840     return InvalidOperands(Loc, LHS, RHS);
10841 
10842   // C++0x: Don't allow scoped enums. FIXME: Use something better than
10843   // hasIntegerRepresentation() above instead of this.
10844   if (isScopedEnumerationType(LHSType) ||
10845       isScopedEnumerationType(RHSType)) {
10846     return InvalidOperands(Loc, LHS, RHS);
10847   }
10848   // Sanity-check shift operands
10849   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
10850 
10851   // "The type of the result is that of the promoted left operand."
10852   return LHSType;
10853 }
10854 
10855 /// Diagnose bad pointer comparisons.
10856 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
10857                                               ExprResult &LHS, ExprResult &RHS,
10858                                               bool IsError) {
10859   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
10860                       : diag::ext_typecheck_comparison_of_distinct_pointers)
10861     << LHS.get()->getType() << RHS.get()->getType()
10862     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10863 }
10864 
10865 /// Returns false if the pointers are converted to a composite type,
10866 /// true otherwise.
10867 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
10868                                            ExprResult &LHS, ExprResult &RHS) {
10869   // C++ [expr.rel]p2:
10870   //   [...] Pointer conversions (4.10) and qualification
10871   //   conversions (4.4) are performed on pointer operands (or on
10872   //   a pointer operand and a null pointer constant) to bring
10873   //   them to their composite pointer type. [...]
10874   //
10875   // C++ [expr.eq]p1 uses the same notion for (in)equality
10876   // comparisons of pointers.
10877 
10878   QualType LHSType = LHS.get()->getType();
10879   QualType RHSType = RHS.get()->getType();
10880   assert(LHSType->isPointerType() || RHSType->isPointerType() ||
10881          LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
10882 
10883   QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
10884   if (T.isNull()) {
10885     if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) &&
10886         (RHSType->isAnyPointerType() || RHSType->isMemberPointerType()))
10887       diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
10888     else
10889       S.InvalidOperands(Loc, LHS, RHS);
10890     return true;
10891   }
10892 
10893   return false;
10894 }
10895 
10896 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
10897                                                     ExprResult &LHS,
10898                                                     ExprResult &RHS,
10899                                                     bool IsError) {
10900   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
10901                       : diag::ext_typecheck_comparison_of_fptr_to_void)
10902     << LHS.get()->getType() << RHS.get()->getType()
10903     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10904 }
10905 
10906 static bool isObjCObjectLiteral(ExprResult &E) {
10907   switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
10908   case Stmt::ObjCArrayLiteralClass:
10909   case Stmt::ObjCDictionaryLiteralClass:
10910   case Stmt::ObjCStringLiteralClass:
10911   case Stmt::ObjCBoxedExprClass:
10912     return true;
10913   default:
10914     // Note that ObjCBoolLiteral is NOT an object literal!
10915     return false;
10916   }
10917 }
10918 
10919 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
10920   const ObjCObjectPointerType *Type =
10921     LHS->getType()->getAs<ObjCObjectPointerType>();
10922 
10923   // If this is not actually an Objective-C object, bail out.
10924   if (!Type)
10925     return false;
10926 
10927   // Get the LHS object's interface type.
10928   QualType InterfaceType = Type->getPointeeType();
10929 
10930   // If the RHS isn't an Objective-C object, bail out.
10931   if (!RHS->getType()->isObjCObjectPointerType())
10932     return false;
10933 
10934   // Try to find the -isEqual: method.
10935   Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
10936   ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
10937                                                       InterfaceType,
10938                                                       /*IsInstance=*/true);
10939   if (!Method) {
10940     if (Type->isObjCIdType()) {
10941       // For 'id', just check the global pool.
10942       Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
10943                                                   /*receiverId=*/true);
10944     } else {
10945       // Check protocols.
10946       Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
10947                                              /*IsInstance=*/true);
10948     }
10949   }
10950 
10951   if (!Method)
10952     return false;
10953 
10954   QualType T = Method->parameters()[0]->getType();
10955   if (!T->isObjCObjectPointerType())
10956     return false;
10957 
10958   QualType R = Method->getReturnType();
10959   if (!R->isScalarType())
10960     return false;
10961 
10962   return true;
10963 }
10964 
10965 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
10966   FromE = FromE->IgnoreParenImpCasts();
10967   switch (FromE->getStmtClass()) {
10968     default:
10969       break;
10970     case Stmt::ObjCStringLiteralClass:
10971       // "string literal"
10972       return LK_String;
10973     case Stmt::ObjCArrayLiteralClass:
10974       // "array literal"
10975       return LK_Array;
10976     case Stmt::ObjCDictionaryLiteralClass:
10977       // "dictionary literal"
10978       return LK_Dictionary;
10979     case Stmt::BlockExprClass:
10980       return LK_Block;
10981     case Stmt::ObjCBoxedExprClass: {
10982       Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
10983       switch (Inner->getStmtClass()) {
10984         case Stmt::IntegerLiteralClass:
10985         case Stmt::FloatingLiteralClass:
10986         case Stmt::CharacterLiteralClass:
10987         case Stmt::ObjCBoolLiteralExprClass:
10988         case Stmt::CXXBoolLiteralExprClass:
10989           // "numeric literal"
10990           return LK_Numeric;
10991         case Stmt::ImplicitCastExprClass: {
10992           CastKind CK = cast<CastExpr>(Inner)->getCastKind();
10993           // Boolean literals can be represented by implicit casts.
10994           if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
10995             return LK_Numeric;
10996           break;
10997         }
10998         default:
10999           break;
11000       }
11001       return LK_Boxed;
11002     }
11003   }
11004   return LK_None;
11005 }
11006 
11007 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
11008                                           ExprResult &LHS, ExprResult &RHS,
11009                                           BinaryOperator::Opcode Opc){
11010   Expr *Literal;
11011   Expr *Other;
11012   if (isObjCObjectLiteral(LHS)) {
11013     Literal = LHS.get();
11014     Other = RHS.get();
11015   } else {
11016     Literal = RHS.get();
11017     Other = LHS.get();
11018   }
11019 
11020   // Don't warn on comparisons against nil.
11021   Other = Other->IgnoreParenCasts();
11022   if (Other->isNullPointerConstant(S.getASTContext(),
11023                                    Expr::NPC_ValueDependentIsNotNull))
11024     return;
11025 
11026   // This should be kept in sync with warn_objc_literal_comparison.
11027   // LK_String should always be after the other literals, since it has its own
11028   // warning flag.
11029   Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
11030   assert(LiteralKind != Sema::LK_Block);
11031   if (LiteralKind == Sema::LK_None) {
11032     llvm_unreachable("Unknown Objective-C object literal kind");
11033   }
11034 
11035   if (LiteralKind == Sema::LK_String)
11036     S.Diag(Loc, diag::warn_objc_string_literal_comparison)
11037       << Literal->getSourceRange();
11038   else
11039     S.Diag(Loc, diag::warn_objc_literal_comparison)
11040       << LiteralKind << Literal->getSourceRange();
11041 
11042   if (BinaryOperator::isEqualityOp(Opc) &&
11043       hasIsEqualMethod(S, LHS.get(), RHS.get())) {
11044     SourceLocation Start = LHS.get()->getBeginLoc();
11045     SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc());
11046     CharSourceRange OpRange =
11047       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
11048 
11049     S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
11050       << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
11051       << FixItHint::CreateReplacement(OpRange, " isEqual:")
11052       << FixItHint::CreateInsertion(End, "]");
11053   }
11054 }
11055 
11056 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
11057 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
11058                                            ExprResult &RHS, SourceLocation Loc,
11059                                            BinaryOperatorKind Opc) {
11060   // Check that left hand side is !something.
11061   UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
11062   if (!UO || UO->getOpcode() != UO_LNot) return;
11063 
11064   // Only check if the right hand side is non-bool arithmetic type.
11065   if (RHS.get()->isKnownToHaveBooleanValue()) return;
11066 
11067   // Make sure that the something in !something is not bool.
11068   Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
11069   if (SubExpr->isKnownToHaveBooleanValue()) return;
11070 
11071   // Emit warning.
11072   bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
11073   S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
11074       << Loc << IsBitwiseOp;
11075 
11076   // First note suggest !(x < y)
11077   SourceLocation FirstOpen = SubExpr->getBeginLoc();
11078   SourceLocation FirstClose = RHS.get()->getEndLoc();
11079   FirstClose = S.getLocForEndOfToken(FirstClose);
11080   if (FirstClose.isInvalid())
11081     FirstOpen = SourceLocation();
11082   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
11083       << IsBitwiseOp
11084       << FixItHint::CreateInsertion(FirstOpen, "(")
11085       << FixItHint::CreateInsertion(FirstClose, ")");
11086 
11087   // Second note suggests (!x) < y
11088   SourceLocation SecondOpen = LHS.get()->getBeginLoc();
11089   SourceLocation SecondClose = LHS.get()->getEndLoc();
11090   SecondClose = S.getLocForEndOfToken(SecondClose);
11091   if (SecondClose.isInvalid())
11092     SecondOpen = SourceLocation();
11093   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
11094       << FixItHint::CreateInsertion(SecondOpen, "(")
11095       << FixItHint::CreateInsertion(SecondClose, ")");
11096 }
11097 
11098 // Returns true if E refers to a non-weak array.
11099 static bool checkForArray(const Expr *E) {
11100   const ValueDecl *D = nullptr;
11101   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
11102     D = DR->getDecl();
11103   } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
11104     if (Mem->isImplicitAccess())
11105       D = Mem->getMemberDecl();
11106   }
11107   if (!D)
11108     return false;
11109   return D->getType()->isArrayType() && !D->isWeak();
11110 }
11111 
11112 /// Diagnose some forms of syntactically-obvious tautological comparison.
11113 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc,
11114                                            Expr *LHS, Expr *RHS,
11115                                            BinaryOperatorKind Opc) {
11116   Expr *LHSStripped = LHS->IgnoreParenImpCasts();
11117   Expr *RHSStripped = RHS->IgnoreParenImpCasts();
11118 
11119   QualType LHSType = LHS->getType();
11120   QualType RHSType = RHS->getType();
11121   if (LHSType->hasFloatingRepresentation() ||
11122       (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
11123       S.inTemplateInstantiation())
11124     return;
11125 
11126   // Comparisons between two array types are ill-formed for operator<=>, so
11127   // we shouldn't emit any additional warnings about it.
11128   if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
11129     return;
11130 
11131   // For non-floating point types, check for self-comparisons of the form
11132   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
11133   // often indicate logic errors in the program.
11134   //
11135   // NOTE: Don't warn about comparison expressions resulting from macro
11136   // expansion. Also don't warn about comparisons which are only self
11137   // comparisons within a template instantiation. The warnings should catch
11138   // obvious cases in the definition of the template anyways. The idea is to
11139   // warn when the typed comparison operator will always evaluate to the same
11140   // result.
11141 
11142   // Used for indexing into %select in warn_comparison_always
11143   enum {
11144     AlwaysConstant,
11145     AlwaysTrue,
11146     AlwaysFalse,
11147     AlwaysEqual, // std::strong_ordering::equal from operator<=>
11148   };
11149 
11150   // C++2a [depr.array.comp]:
11151   //   Equality and relational comparisons ([expr.eq], [expr.rel]) between two
11152   //   operands of array type are deprecated.
11153   if (S.getLangOpts().CPlusPlus20 && LHSStripped->getType()->isArrayType() &&
11154       RHSStripped->getType()->isArrayType()) {
11155     S.Diag(Loc, diag::warn_depr_array_comparison)
11156         << LHS->getSourceRange() << RHS->getSourceRange()
11157         << LHSStripped->getType() << RHSStripped->getType();
11158     // Carry on to produce the tautological comparison warning, if this
11159     // expression is potentially-evaluated, we can resolve the array to a
11160     // non-weak declaration, and so on.
11161   }
11162 
11163   if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) {
11164     if (Expr::isSameComparisonOperand(LHS, RHS)) {
11165       unsigned Result;
11166       switch (Opc) {
11167       case BO_EQ:
11168       case BO_LE:
11169       case BO_GE:
11170         Result = AlwaysTrue;
11171         break;
11172       case BO_NE:
11173       case BO_LT:
11174       case BO_GT:
11175         Result = AlwaysFalse;
11176         break;
11177       case BO_Cmp:
11178         Result = AlwaysEqual;
11179         break;
11180       default:
11181         Result = AlwaysConstant;
11182         break;
11183       }
11184       S.DiagRuntimeBehavior(Loc, nullptr,
11185                             S.PDiag(diag::warn_comparison_always)
11186                                 << 0 /*self-comparison*/
11187                                 << Result);
11188     } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) {
11189       // What is it always going to evaluate to?
11190       unsigned Result;
11191       switch (Opc) {
11192       case BO_EQ: // e.g. array1 == array2
11193         Result = AlwaysFalse;
11194         break;
11195       case BO_NE: // e.g. array1 != array2
11196         Result = AlwaysTrue;
11197         break;
11198       default: // e.g. array1 <= array2
11199         // The best we can say is 'a constant'
11200         Result = AlwaysConstant;
11201         break;
11202       }
11203       S.DiagRuntimeBehavior(Loc, nullptr,
11204                             S.PDiag(diag::warn_comparison_always)
11205                                 << 1 /*array comparison*/
11206                                 << Result);
11207     }
11208   }
11209 
11210   if (isa<CastExpr>(LHSStripped))
11211     LHSStripped = LHSStripped->IgnoreParenCasts();
11212   if (isa<CastExpr>(RHSStripped))
11213     RHSStripped = RHSStripped->IgnoreParenCasts();
11214 
11215   // Warn about comparisons against a string constant (unless the other
11216   // operand is null); the user probably wants string comparison function.
11217   Expr *LiteralString = nullptr;
11218   Expr *LiteralStringStripped = nullptr;
11219   if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
11220       !RHSStripped->isNullPointerConstant(S.Context,
11221                                           Expr::NPC_ValueDependentIsNull)) {
11222     LiteralString = LHS;
11223     LiteralStringStripped = LHSStripped;
11224   } else if ((isa<StringLiteral>(RHSStripped) ||
11225               isa<ObjCEncodeExpr>(RHSStripped)) &&
11226              !LHSStripped->isNullPointerConstant(S.Context,
11227                                           Expr::NPC_ValueDependentIsNull)) {
11228     LiteralString = RHS;
11229     LiteralStringStripped = RHSStripped;
11230   }
11231 
11232   if (LiteralString) {
11233     S.DiagRuntimeBehavior(Loc, nullptr,
11234                           S.PDiag(diag::warn_stringcompare)
11235                               << isa<ObjCEncodeExpr>(LiteralStringStripped)
11236                               << LiteralString->getSourceRange());
11237   }
11238 }
11239 
11240 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) {
11241   switch (CK) {
11242   default: {
11243 #ifndef NDEBUG
11244     llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
11245                  << "\n";
11246 #endif
11247     llvm_unreachable("unhandled cast kind");
11248   }
11249   case CK_UserDefinedConversion:
11250     return ICK_Identity;
11251   case CK_LValueToRValue:
11252     return ICK_Lvalue_To_Rvalue;
11253   case CK_ArrayToPointerDecay:
11254     return ICK_Array_To_Pointer;
11255   case CK_FunctionToPointerDecay:
11256     return ICK_Function_To_Pointer;
11257   case CK_IntegralCast:
11258     return ICK_Integral_Conversion;
11259   case CK_FloatingCast:
11260     return ICK_Floating_Conversion;
11261   case CK_IntegralToFloating:
11262   case CK_FloatingToIntegral:
11263     return ICK_Floating_Integral;
11264   case CK_IntegralComplexCast:
11265   case CK_FloatingComplexCast:
11266   case CK_FloatingComplexToIntegralComplex:
11267   case CK_IntegralComplexToFloatingComplex:
11268     return ICK_Complex_Conversion;
11269   case CK_FloatingComplexToReal:
11270   case CK_FloatingRealToComplex:
11271   case CK_IntegralComplexToReal:
11272   case CK_IntegralRealToComplex:
11273     return ICK_Complex_Real;
11274   }
11275 }
11276 
11277 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E,
11278                                              QualType FromType,
11279                                              SourceLocation Loc) {
11280   // Check for a narrowing implicit conversion.
11281   StandardConversionSequence SCS;
11282   SCS.setAsIdentityConversion();
11283   SCS.setToType(0, FromType);
11284   SCS.setToType(1, ToType);
11285   if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
11286     SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
11287 
11288   APValue PreNarrowingValue;
11289   QualType PreNarrowingType;
11290   switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
11291                                PreNarrowingType,
11292                                /*IgnoreFloatToIntegralConversion*/ true)) {
11293   case NK_Dependent_Narrowing:
11294     // Implicit conversion to a narrower type, but the expression is
11295     // value-dependent so we can't tell whether it's actually narrowing.
11296   case NK_Not_Narrowing:
11297     return false;
11298 
11299   case NK_Constant_Narrowing:
11300     // Implicit conversion to a narrower type, and the value is not a constant
11301     // expression.
11302     S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
11303         << /*Constant*/ 1
11304         << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
11305     return true;
11306 
11307   case NK_Variable_Narrowing:
11308     // Implicit conversion to a narrower type, and the value is not a constant
11309     // expression.
11310   case NK_Type_Narrowing:
11311     S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
11312         << /*Constant*/ 0 << FromType << ToType;
11313     // TODO: It's not a constant expression, but what if the user intended it
11314     // to be? Can we produce notes to help them figure out why it isn't?
11315     return true;
11316   }
11317   llvm_unreachable("unhandled case in switch");
11318 }
11319 
11320 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S,
11321                                                          ExprResult &LHS,
11322                                                          ExprResult &RHS,
11323                                                          SourceLocation Loc) {
11324   QualType LHSType = LHS.get()->getType();
11325   QualType RHSType = RHS.get()->getType();
11326   // Dig out the original argument type and expression before implicit casts
11327   // were applied. These are the types/expressions we need to check the
11328   // [expr.spaceship] requirements against.
11329   ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
11330   ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
11331   QualType LHSStrippedType = LHSStripped.get()->getType();
11332   QualType RHSStrippedType = RHSStripped.get()->getType();
11333 
11334   // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
11335   // other is not, the program is ill-formed.
11336   if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
11337     S.InvalidOperands(Loc, LHSStripped, RHSStripped);
11338     return QualType();
11339   }
11340 
11341   // FIXME: Consider combining this with checkEnumArithmeticConversions.
11342   int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
11343                     RHSStrippedType->isEnumeralType();
11344   if (NumEnumArgs == 1) {
11345     bool LHSIsEnum = LHSStrippedType->isEnumeralType();
11346     QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
11347     if (OtherTy->hasFloatingRepresentation()) {
11348       S.InvalidOperands(Loc, LHSStripped, RHSStripped);
11349       return QualType();
11350     }
11351   }
11352   if (NumEnumArgs == 2) {
11353     // C++2a [expr.spaceship]p5: If both operands have the same enumeration
11354     // type E, the operator yields the result of converting the operands
11355     // to the underlying type of E and applying <=> to the converted operands.
11356     if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
11357       S.InvalidOperands(Loc, LHS, RHS);
11358       return QualType();
11359     }
11360     QualType IntType =
11361         LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType();
11362     assert(IntType->isArithmeticType());
11363 
11364     // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
11365     // promote the boolean type, and all other promotable integer types, to
11366     // avoid this.
11367     if (IntType->isPromotableIntegerType())
11368       IntType = S.Context.getPromotedIntegerType(IntType);
11369 
11370     LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
11371     RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
11372     LHSType = RHSType = IntType;
11373   }
11374 
11375   // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
11376   // usual arithmetic conversions are applied to the operands.
11377   QualType Type =
11378       S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison);
11379   if (LHS.isInvalid() || RHS.isInvalid())
11380     return QualType();
11381   if (Type.isNull())
11382     return S.InvalidOperands(Loc, LHS, RHS);
11383 
11384   Optional<ComparisonCategoryType> CCT =
11385       getComparisonCategoryForBuiltinCmp(Type);
11386   if (!CCT)
11387     return S.InvalidOperands(Loc, LHS, RHS);
11388 
11389   bool HasNarrowing = checkThreeWayNarrowingConversion(
11390       S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc());
11391   HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType,
11392                                                    RHS.get()->getBeginLoc());
11393   if (HasNarrowing)
11394     return QualType();
11395 
11396   assert(!Type.isNull() && "composite type for <=> has not been set");
11397 
11398   return S.CheckComparisonCategoryType(
11399       *CCT, Loc, Sema::ComparisonCategoryUsage::OperatorInExpression);
11400 }
11401 
11402 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS,
11403                                                  ExprResult &RHS,
11404                                                  SourceLocation Loc,
11405                                                  BinaryOperatorKind Opc) {
11406   if (Opc == BO_Cmp)
11407     return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
11408 
11409   // C99 6.5.8p3 / C99 6.5.9p4
11410   QualType Type =
11411       S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison);
11412   if (LHS.isInvalid() || RHS.isInvalid())
11413     return QualType();
11414   if (Type.isNull())
11415     return S.InvalidOperands(Loc, LHS, RHS);
11416   assert(Type->isArithmeticType() || Type->isEnumeralType());
11417 
11418   if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc))
11419     return S.InvalidOperands(Loc, LHS, RHS);
11420 
11421   // Check for comparisons of floating point operands using != and ==.
11422   if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc))
11423     S.CheckFloatComparison(Loc, LHS.get(), RHS.get());
11424 
11425   // The result of comparisons is 'bool' in C++, 'int' in C.
11426   return S.Context.getLogicalOperationType();
11427 }
11428 
11429 void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) {
11430   if (!NullE.get()->getType()->isAnyPointerType())
11431     return;
11432   int NullValue = PP.isMacroDefined("NULL") ? 0 : 1;
11433   if (!E.get()->getType()->isAnyPointerType() &&
11434       E.get()->isNullPointerConstant(Context,
11435                                      Expr::NPC_ValueDependentIsNotNull) ==
11436         Expr::NPCK_ZeroExpression) {
11437     if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) {
11438       if (CL->getValue() == 0)
11439         Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
11440             << NullValue
11441             << FixItHint::CreateReplacement(E.get()->getExprLoc(),
11442                                             NullValue ? "NULL" : "(void *)0");
11443     } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) {
11444         TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
11445         QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType();
11446         if (T == Context.CharTy)
11447           Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
11448               << NullValue
11449               << FixItHint::CreateReplacement(E.get()->getExprLoc(),
11450                                               NullValue ? "NULL" : "(void *)0");
11451       }
11452   }
11453 }
11454 
11455 // C99 6.5.8, C++ [expr.rel]
11456 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
11457                                     SourceLocation Loc,
11458                                     BinaryOperatorKind Opc) {
11459   bool IsRelational = BinaryOperator::isRelationalOp(Opc);
11460   bool IsThreeWay = Opc == BO_Cmp;
11461   bool IsOrdered = IsRelational || IsThreeWay;
11462   auto IsAnyPointerType = [](ExprResult E) {
11463     QualType Ty = E.get()->getType();
11464     return Ty->isPointerType() || Ty->isMemberPointerType();
11465   };
11466 
11467   // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
11468   // type, array-to-pointer, ..., conversions are performed on both operands to
11469   // bring them to their composite type.
11470   // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
11471   // any type-related checks.
11472   if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
11473     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
11474     if (LHS.isInvalid())
11475       return QualType();
11476     RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
11477     if (RHS.isInvalid())
11478       return QualType();
11479   } else {
11480     LHS = DefaultLvalueConversion(LHS.get());
11481     if (LHS.isInvalid())
11482       return QualType();
11483     RHS = DefaultLvalueConversion(RHS.get());
11484     if (RHS.isInvalid())
11485       return QualType();
11486   }
11487 
11488   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true);
11489   if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) {
11490     CheckPtrComparisonWithNullChar(LHS, RHS);
11491     CheckPtrComparisonWithNullChar(RHS, LHS);
11492   }
11493 
11494   // Handle vector comparisons separately.
11495   if (LHS.get()->getType()->isVectorType() ||
11496       RHS.get()->getType()->isVectorType())
11497     return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
11498 
11499   diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
11500   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
11501 
11502   QualType LHSType = LHS.get()->getType();
11503   QualType RHSType = RHS.get()->getType();
11504   if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
11505       (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
11506     return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
11507 
11508   const Expr::NullPointerConstantKind LHSNullKind =
11509       LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
11510   const Expr::NullPointerConstantKind RHSNullKind =
11511       RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
11512   bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
11513   bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
11514 
11515   auto computeResultTy = [&]() {
11516     if (Opc != BO_Cmp)
11517       return Context.getLogicalOperationType();
11518     assert(getLangOpts().CPlusPlus);
11519     assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
11520 
11521     QualType CompositeTy = LHS.get()->getType();
11522     assert(!CompositeTy->isReferenceType());
11523 
11524     Optional<ComparisonCategoryType> CCT =
11525         getComparisonCategoryForBuiltinCmp(CompositeTy);
11526     if (!CCT)
11527       return InvalidOperands(Loc, LHS, RHS);
11528 
11529     if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) {
11530       // P0946R0: Comparisons between a null pointer constant and an object
11531       // pointer result in std::strong_equality, which is ill-formed under
11532       // P1959R0.
11533       Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero)
11534           << (LHSIsNull ? LHS.get()->getSourceRange()
11535                         : RHS.get()->getSourceRange());
11536       return QualType();
11537     }
11538 
11539     return CheckComparisonCategoryType(
11540         *CCT, Loc, ComparisonCategoryUsage::OperatorInExpression);
11541   };
11542 
11543   if (!IsOrdered && LHSIsNull != RHSIsNull) {
11544     bool IsEquality = Opc == BO_EQ;
11545     if (RHSIsNull)
11546       DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
11547                                    RHS.get()->getSourceRange());
11548     else
11549       DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
11550                                    LHS.get()->getSourceRange());
11551   }
11552 
11553   if ((LHSType->isIntegerType() && !LHSIsNull) ||
11554       (RHSType->isIntegerType() && !RHSIsNull)) {
11555     // Skip normal pointer conversion checks in this case; we have better
11556     // diagnostics for this below.
11557   } else if (getLangOpts().CPlusPlus) {
11558     // Equality comparison of a function pointer to a void pointer is invalid,
11559     // but we allow it as an extension.
11560     // FIXME: If we really want to allow this, should it be part of composite
11561     // pointer type computation so it works in conditionals too?
11562     if (!IsOrdered &&
11563         ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
11564          (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
11565       // This is a gcc extension compatibility comparison.
11566       // In a SFINAE context, we treat this as a hard error to maintain
11567       // conformance with the C++ standard.
11568       diagnoseFunctionPointerToVoidComparison(
11569           *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
11570 
11571       if (isSFINAEContext())
11572         return QualType();
11573 
11574       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
11575       return computeResultTy();
11576     }
11577 
11578     // C++ [expr.eq]p2:
11579     //   If at least one operand is a pointer [...] bring them to their
11580     //   composite pointer type.
11581     // C++ [expr.spaceship]p6
11582     //  If at least one of the operands is of pointer type, [...] bring them
11583     //  to their composite pointer type.
11584     // C++ [expr.rel]p2:
11585     //   If both operands are pointers, [...] bring them to their composite
11586     //   pointer type.
11587     // For <=>, the only valid non-pointer types are arrays and functions, and
11588     // we already decayed those, so this is really the same as the relational
11589     // comparison rule.
11590     if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
11591             (IsOrdered ? 2 : 1) &&
11592         (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
11593                                          RHSType->isObjCObjectPointerType()))) {
11594       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
11595         return QualType();
11596       return computeResultTy();
11597     }
11598   } else if (LHSType->isPointerType() &&
11599              RHSType->isPointerType()) { // C99 6.5.8p2
11600     // All of the following pointer-related warnings are GCC extensions, except
11601     // when handling null pointer constants.
11602     QualType LCanPointeeTy =
11603       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
11604     QualType RCanPointeeTy =
11605       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
11606 
11607     // C99 6.5.9p2 and C99 6.5.8p2
11608     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
11609                                    RCanPointeeTy.getUnqualifiedType())) {
11610       if (IsRelational) {
11611         // Pointers both need to point to complete or incomplete types
11612         if ((LCanPointeeTy->isIncompleteType() !=
11613              RCanPointeeTy->isIncompleteType()) &&
11614             !getLangOpts().C11) {
11615           Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers)
11616               << LHS.get()->getSourceRange() << RHS.get()->getSourceRange()
11617               << LHSType << RHSType << LCanPointeeTy->isIncompleteType()
11618               << RCanPointeeTy->isIncompleteType();
11619         }
11620         if (LCanPointeeTy->isFunctionType()) {
11621           // Valid unless a relational comparison of function pointers
11622           Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
11623               << LHSType << RHSType << LHS.get()->getSourceRange()
11624               << RHS.get()->getSourceRange();
11625         }
11626       }
11627     } else if (!IsRelational &&
11628                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
11629       // Valid unless comparison between non-null pointer and function pointer
11630       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
11631           && !LHSIsNull && !RHSIsNull)
11632         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
11633                                                 /*isError*/false);
11634     } else {
11635       // Invalid
11636       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
11637     }
11638     if (LCanPointeeTy != RCanPointeeTy) {
11639       // Treat NULL constant as a special case in OpenCL.
11640       if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
11641         if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy)) {
11642           Diag(Loc,
11643                diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
11644               << LHSType << RHSType << 0 /* comparison */
11645               << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11646         }
11647       }
11648       LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
11649       LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
11650       CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
11651                                                : CK_BitCast;
11652       if (LHSIsNull && !RHSIsNull)
11653         LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
11654       else
11655         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
11656     }
11657     return computeResultTy();
11658   }
11659 
11660   if (getLangOpts().CPlusPlus) {
11661     // C++ [expr.eq]p4:
11662     //   Two operands of type std::nullptr_t or one operand of type
11663     //   std::nullptr_t and the other a null pointer constant compare equal.
11664     if (!IsOrdered && LHSIsNull && RHSIsNull) {
11665       if (LHSType->isNullPtrType()) {
11666         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11667         return computeResultTy();
11668       }
11669       if (RHSType->isNullPtrType()) {
11670         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11671         return computeResultTy();
11672       }
11673     }
11674 
11675     // Comparison of Objective-C pointers and block pointers against nullptr_t.
11676     // These aren't covered by the composite pointer type rules.
11677     if (!IsOrdered && RHSType->isNullPtrType() &&
11678         (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
11679       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11680       return computeResultTy();
11681     }
11682     if (!IsOrdered && LHSType->isNullPtrType() &&
11683         (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
11684       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11685       return computeResultTy();
11686     }
11687 
11688     if (IsRelational &&
11689         ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
11690          (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
11691       // HACK: Relational comparison of nullptr_t against a pointer type is
11692       // invalid per DR583, but we allow it within std::less<> and friends,
11693       // since otherwise common uses of it break.
11694       // FIXME: Consider removing this hack once LWG fixes std::less<> and
11695       // friends to have std::nullptr_t overload candidates.
11696       DeclContext *DC = CurContext;
11697       if (isa<FunctionDecl>(DC))
11698         DC = DC->getParent();
11699       if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
11700         if (CTSD->isInStdNamespace() &&
11701             llvm::StringSwitch<bool>(CTSD->getName())
11702                 .Cases("less", "less_equal", "greater", "greater_equal", true)
11703                 .Default(false)) {
11704           if (RHSType->isNullPtrType())
11705             RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11706           else
11707             LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11708           return computeResultTy();
11709         }
11710       }
11711     }
11712 
11713     // C++ [expr.eq]p2:
11714     //   If at least one operand is a pointer to member, [...] bring them to
11715     //   their composite pointer type.
11716     if (!IsOrdered &&
11717         (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
11718       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
11719         return QualType();
11720       else
11721         return computeResultTy();
11722     }
11723   }
11724 
11725   // Handle block pointer types.
11726   if (!IsOrdered && LHSType->isBlockPointerType() &&
11727       RHSType->isBlockPointerType()) {
11728     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
11729     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
11730 
11731     if (!LHSIsNull && !RHSIsNull &&
11732         !Context.typesAreCompatible(lpointee, rpointee)) {
11733       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
11734         << LHSType << RHSType << LHS.get()->getSourceRange()
11735         << RHS.get()->getSourceRange();
11736     }
11737     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
11738     return computeResultTy();
11739   }
11740 
11741   // Allow block pointers to be compared with null pointer constants.
11742   if (!IsOrdered
11743       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
11744           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
11745     if (!LHSIsNull && !RHSIsNull) {
11746       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
11747              ->getPointeeType()->isVoidType())
11748             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
11749                 ->getPointeeType()->isVoidType())))
11750         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
11751           << LHSType << RHSType << LHS.get()->getSourceRange()
11752           << RHS.get()->getSourceRange();
11753     }
11754     if (LHSIsNull && !RHSIsNull)
11755       LHS = ImpCastExprToType(LHS.get(), RHSType,
11756                               RHSType->isPointerType() ? CK_BitCast
11757                                 : CK_AnyPointerToBlockPointerCast);
11758     else
11759       RHS = ImpCastExprToType(RHS.get(), LHSType,
11760                               LHSType->isPointerType() ? CK_BitCast
11761                                 : CK_AnyPointerToBlockPointerCast);
11762     return computeResultTy();
11763   }
11764 
11765   if (LHSType->isObjCObjectPointerType() ||
11766       RHSType->isObjCObjectPointerType()) {
11767     const PointerType *LPT = LHSType->getAs<PointerType>();
11768     const PointerType *RPT = RHSType->getAs<PointerType>();
11769     if (LPT || RPT) {
11770       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
11771       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
11772 
11773       if (!LPtrToVoid && !RPtrToVoid &&
11774           !Context.typesAreCompatible(LHSType, RHSType)) {
11775         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
11776                                           /*isError*/false);
11777       }
11778       // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than
11779       // the RHS, but we have test coverage for this behavior.
11780       // FIXME: Consider using convertPointersToCompositeType in C++.
11781       if (LHSIsNull && !RHSIsNull) {
11782         Expr *E = LHS.get();
11783         if (getLangOpts().ObjCAutoRefCount)
11784           CheckObjCConversion(SourceRange(), RHSType, E,
11785                               CCK_ImplicitConversion);
11786         LHS = ImpCastExprToType(E, RHSType,
11787                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
11788       }
11789       else {
11790         Expr *E = RHS.get();
11791         if (getLangOpts().ObjCAutoRefCount)
11792           CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion,
11793                               /*Diagnose=*/true,
11794                               /*DiagnoseCFAudited=*/false, Opc);
11795         RHS = ImpCastExprToType(E, LHSType,
11796                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
11797       }
11798       return computeResultTy();
11799     }
11800     if (LHSType->isObjCObjectPointerType() &&
11801         RHSType->isObjCObjectPointerType()) {
11802       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
11803         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
11804                                           /*isError*/false);
11805       if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
11806         diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
11807 
11808       if (LHSIsNull && !RHSIsNull)
11809         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
11810       else
11811         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
11812       return computeResultTy();
11813     }
11814 
11815     if (!IsOrdered && LHSType->isBlockPointerType() &&
11816         RHSType->isBlockCompatibleObjCPointerType(Context)) {
11817       LHS = ImpCastExprToType(LHS.get(), RHSType,
11818                               CK_BlockPointerToObjCPointerCast);
11819       return computeResultTy();
11820     } else if (!IsOrdered &&
11821                LHSType->isBlockCompatibleObjCPointerType(Context) &&
11822                RHSType->isBlockPointerType()) {
11823       RHS = ImpCastExprToType(RHS.get(), LHSType,
11824                               CK_BlockPointerToObjCPointerCast);
11825       return computeResultTy();
11826     }
11827   }
11828   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
11829       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
11830     unsigned DiagID = 0;
11831     bool isError = false;
11832     if (LangOpts.DebuggerSupport) {
11833       // Under a debugger, allow the comparison of pointers to integers,
11834       // since users tend to want to compare addresses.
11835     } else if ((LHSIsNull && LHSType->isIntegerType()) ||
11836                (RHSIsNull && RHSType->isIntegerType())) {
11837       if (IsOrdered) {
11838         isError = getLangOpts().CPlusPlus;
11839         DiagID =
11840           isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
11841                   : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
11842       }
11843     } else if (getLangOpts().CPlusPlus) {
11844       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
11845       isError = true;
11846     } else if (IsOrdered)
11847       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
11848     else
11849       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
11850 
11851     if (DiagID) {
11852       Diag(Loc, DiagID)
11853         << LHSType << RHSType << LHS.get()->getSourceRange()
11854         << RHS.get()->getSourceRange();
11855       if (isError)
11856         return QualType();
11857     }
11858 
11859     if (LHSType->isIntegerType())
11860       LHS = ImpCastExprToType(LHS.get(), RHSType,
11861                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
11862     else
11863       RHS = ImpCastExprToType(RHS.get(), LHSType,
11864                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
11865     return computeResultTy();
11866   }
11867 
11868   // Handle block pointers.
11869   if (!IsOrdered && RHSIsNull
11870       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
11871     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11872     return computeResultTy();
11873   }
11874   if (!IsOrdered && LHSIsNull
11875       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
11876     LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11877     return computeResultTy();
11878   }
11879 
11880   if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) {
11881     if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
11882       return computeResultTy();
11883     }
11884 
11885     if (LHSType->isQueueT() && RHSType->isQueueT()) {
11886       return computeResultTy();
11887     }
11888 
11889     if (LHSIsNull && RHSType->isQueueT()) {
11890       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11891       return computeResultTy();
11892     }
11893 
11894     if (LHSType->isQueueT() && RHSIsNull) {
11895       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11896       return computeResultTy();
11897     }
11898   }
11899 
11900   return InvalidOperands(Loc, LHS, RHS);
11901 }
11902 
11903 // Return a signed ext_vector_type that is of identical size and number of
11904 // elements. For floating point vectors, return an integer type of identical
11905 // size and number of elements. In the non ext_vector_type case, search from
11906 // the largest type to the smallest type to avoid cases where long long == long,
11907 // where long gets picked over long long.
11908 QualType Sema::GetSignedVectorType(QualType V) {
11909   const VectorType *VTy = V->castAs<VectorType>();
11910   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
11911 
11912   if (isa<ExtVectorType>(VTy)) {
11913     if (TypeSize == Context.getTypeSize(Context.CharTy))
11914       return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
11915     else if (TypeSize == Context.getTypeSize(Context.ShortTy))
11916       return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
11917     else if (TypeSize == Context.getTypeSize(Context.IntTy))
11918       return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
11919     else if (TypeSize == Context.getTypeSize(Context.LongTy))
11920       return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
11921     assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
11922            "Unhandled vector element size in vector compare");
11923     return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
11924   }
11925 
11926   if (TypeSize == Context.getTypeSize(Context.LongLongTy))
11927     return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
11928                                  VectorType::GenericVector);
11929   else if (TypeSize == Context.getTypeSize(Context.LongTy))
11930     return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
11931                                  VectorType::GenericVector);
11932   else if (TypeSize == Context.getTypeSize(Context.IntTy))
11933     return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
11934                                  VectorType::GenericVector);
11935   else if (TypeSize == Context.getTypeSize(Context.ShortTy))
11936     return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
11937                                  VectorType::GenericVector);
11938   assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
11939          "Unhandled vector element size in vector compare");
11940   return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
11941                                VectorType::GenericVector);
11942 }
11943 
11944 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
11945 /// operates on extended vector types.  Instead of producing an IntTy result,
11946 /// like a scalar comparison, a vector comparison produces a vector of integer
11947 /// types.
11948 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
11949                                           SourceLocation Loc,
11950                                           BinaryOperatorKind Opc) {
11951   if (Opc == BO_Cmp) {
11952     Diag(Loc, diag::err_three_way_vector_comparison);
11953     return QualType();
11954   }
11955 
11956   // Check to make sure we're operating on vectors of the same type and width,
11957   // Allowing one side to be a scalar of element type.
11958   QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
11959                               /*AllowBothBool*/true,
11960                               /*AllowBoolConversions*/getLangOpts().ZVector);
11961   if (vType.isNull())
11962     return vType;
11963 
11964   QualType LHSType = LHS.get()->getType();
11965 
11966   // If AltiVec, the comparison results in a numeric type, i.e.
11967   // bool for C++, int for C
11968   if (getLangOpts().AltiVec &&
11969       vType->castAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
11970     return Context.getLogicalOperationType();
11971 
11972   // For non-floating point types, check for self-comparisons of the form
11973   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
11974   // often indicate logic errors in the program.
11975   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
11976 
11977   // Check for comparisons of floating point operands using != and ==.
11978   if (BinaryOperator::isEqualityOp(Opc) &&
11979       LHSType->hasFloatingRepresentation()) {
11980     assert(RHS.get()->getType()->hasFloatingRepresentation());
11981     CheckFloatComparison(Loc, LHS.get(), RHS.get());
11982   }
11983 
11984   // Return a signed type for the vector.
11985   return GetSignedVectorType(vType);
11986 }
11987 
11988 static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS,
11989                                     const ExprResult &XorRHS,
11990                                     const SourceLocation Loc) {
11991   // Do not diagnose macros.
11992   if (Loc.isMacroID())
11993     return;
11994 
11995   bool Negative = false;
11996   bool ExplicitPlus = false;
11997   const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get());
11998   const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get());
11999 
12000   if (!LHSInt)
12001     return;
12002   if (!RHSInt) {
12003     // Check negative literals.
12004     if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) {
12005       UnaryOperatorKind Opc = UO->getOpcode();
12006       if (Opc != UO_Minus && Opc != UO_Plus)
12007         return;
12008       RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr());
12009       if (!RHSInt)
12010         return;
12011       Negative = (Opc == UO_Minus);
12012       ExplicitPlus = !Negative;
12013     } else {
12014       return;
12015     }
12016   }
12017 
12018   const llvm::APInt &LeftSideValue = LHSInt->getValue();
12019   llvm::APInt RightSideValue = RHSInt->getValue();
12020   if (LeftSideValue != 2 && LeftSideValue != 10)
12021     return;
12022 
12023   if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth())
12024     return;
12025 
12026   CharSourceRange ExprRange = CharSourceRange::getCharRange(
12027       LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation()));
12028   llvm::StringRef ExprStr =
12029       Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts());
12030 
12031   CharSourceRange XorRange =
12032       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
12033   llvm::StringRef XorStr =
12034       Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts());
12035   // Do not diagnose if xor keyword/macro is used.
12036   if (XorStr == "xor")
12037     return;
12038 
12039   std::string LHSStr = std::string(Lexer::getSourceText(
12040       CharSourceRange::getTokenRange(LHSInt->getSourceRange()),
12041       S.getSourceManager(), S.getLangOpts()));
12042   std::string RHSStr = std::string(Lexer::getSourceText(
12043       CharSourceRange::getTokenRange(RHSInt->getSourceRange()),
12044       S.getSourceManager(), S.getLangOpts()));
12045 
12046   if (Negative) {
12047     RightSideValue = -RightSideValue;
12048     RHSStr = "-" + RHSStr;
12049   } else if (ExplicitPlus) {
12050     RHSStr = "+" + RHSStr;
12051   }
12052 
12053   StringRef LHSStrRef = LHSStr;
12054   StringRef RHSStrRef = RHSStr;
12055   // Do not diagnose literals with digit separators, binary, hexadecimal, octal
12056   // literals.
12057   if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") ||
12058       RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") ||
12059       LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") ||
12060       RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") ||
12061       (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) ||
12062       (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) ||
12063       LHSStrRef.find('\'') != StringRef::npos ||
12064       RHSStrRef.find('\'') != StringRef::npos)
12065     return;
12066 
12067   bool SuggestXor = S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor");
12068   const llvm::APInt XorValue = LeftSideValue ^ RightSideValue;
12069   int64_t RightSideIntValue = RightSideValue.getSExtValue();
12070   if (LeftSideValue == 2 && RightSideIntValue >= 0) {
12071     std::string SuggestedExpr = "1 << " + RHSStr;
12072     bool Overflow = false;
12073     llvm::APInt One = (LeftSideValue - 1);
12074     llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow);
12075     if (Overflow) {
12076       if (RightSideIntValue < 64)
12077         S.Diag(Loc, diag::warn_xor_used_as_pow_base)
12078             << ExprStr << XorValue.toString(10, true) << ("1LL << " + RHSStr)
12079             << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr);
12080       else if (RightSideIntValue == 64)
12081         S.Diag(Loc, diag::warn_xor_used_as_pow) << ExprStr << XorValue.toString(10, true);
12082       else
12083         return;
12084     } else {
12085       S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra)
12086           << ExprStr << XorValue.toString(10, true) << SuggestedExpr
12087           << PowValue.toString(10, true)
12088           << FixItHint::CreateReplacement(
12089                  ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr);
12090     }
12091 
12092     S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0x2 ^ " + RHSStr) << SuggestXor;
12093   } else if (LeftSideValue == 10) {
12094     std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue);
12095     S.Diag(Loc, diag::warn_xor_used_as_pow_base)
12096         << ExprStr << XorValue.toString(10, true) << SuggestedValue
12097         << FixItHint::CreateReplacement(ExprRange, SuggestedValue);
12098     S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0xA ^ " + RHSStr) << SuggestXor;
12099   }
12100 }
12101 
12102 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
12103                                           SourceLocation Loc) {
12104   // Ensure that either both operands are of the same vector type, or
12105   // one operand is of a vector type and the other is of its element type.
12106   QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
12107                                        /*AllowBothBool*/true,
12108                                        /*AllowBoolConversions*/false);
12109   if (vType.isNull())
12110     return InvalidOperands(Loc, LHS, RHS);
12111   if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
12112       !getLangOpts().OpenCLCPlusPlus && vType->hasFloatingRepresentation())
12113     return InvalidOperands(Loc, LHS, RHS);
12114   // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
12115   //        usage of the logical operators && and || with vectors in C. This
12116   //        check could be notionally dropped.
12117   if (!getLangOpts().CPlusPlus &&
12118       !(isa<ExtVectorType>(vType->getAs<VectorType>())))
12119     return InvalidLogicalVectorOperands(Loc, LHS, RHS);
12120 
12121   return GetSignedVectorType(LHS.get()->getType());
12122 }
12123 
12124 QualType Sema::CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS,
12125                                               SourceLocation Loc,
12126                                               bool IsCompAssign) {
12127   if (!IsCompAssign) {
12128     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
12129     if (LHS.isInvalid())
12130       return QualType();
12131   }
12132   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
12133   if (RHS.isInvalid())
12134     return QualType();
12135 
12136   // For conversion purposes, we ignore any qualifiers.
12137   // For example, "const float" and "float" are equivalent.
12138   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
12139   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
12140 
12141   const MatrixType *LHSMatType = LHSType->getAs<MatrixType>();
12142   const MatrixType *RHSMatType = RHSType->getAs<MatrixType>();
12143   assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
12144 
12145   if (Context.hasSameType(LHSType, RHSType))
12146     return LHSType;
12147 
12148   // Type conversion may change LHS/RHS. Keep copies to the original results, in
12149   // case we have to return InvalidOperands.
12150   ExprResult OriginalLHS = LHS;
12151   ExprResult OriginalRHS = RHS;
12152   if (LHSMatType && !RHSMatType) {
12153     RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType());
12154     if (!RHS.isInvalid())
12155       return LHSType;
12156 
12157     return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
12158   }
12159 
12160   if (!LHSMatType && RHSMatType) {
12161     LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType());
12162     if (!LHS.isInvalid())
12163       return RHSType;
12164     return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
12165   }
12166 
12167   return InvalidOperands(Loc, LHS, RHS);
12168 }
12169 
12170 QualType Sema::CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS,
12171                                            SourceLocation Loc,
12172                                            bool IsCompAssign) {
12173   if (!IsCompAssign) {
12174     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
12175     if (LHS.isInvalid())
12176       return QualType();
12177   }
12178   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
12179   if (RHS.isInvalid())
12180     return QualType();
12181 
12182   auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>();
12183   auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>();
12184   assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
12185 
12186   if (LHSMatType && RHSMatType) {
12187     if (LHSMatType->getNumColumns() != RHSMatType->getNumRows())
12188       return InvalidOperands(Loc, LHS, RHS);
12189 
12190     if (!Context.hasSameType(LHSMatType->getElementType(),
12191                              RHSMatType->getElementType()))
12192       return InvalidOperands(Loc, LHS, RHS);
12193 
12194     return Context.getConstantMatrixType(LHSMatType->getElementType(),
12195                                          LHSMatType->getNumRows(),
12196                                          RHSMatType->getNumColumns());
12197   }
12198   return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
12199 }
12200 
12201 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
12202                                            SourceLocation Loc,
12203                                            BinaryOperatorKind Opc) {
12204   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
12205 
12206   bool IsCompAssign =
12207       Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
12208 
12209   if (LHS.get()->getType()->isVectorType() ||
12210       RHS.get()->getType()->isVectorType()) {
12211     if (LHS.get()->getType()->hasIntegerRepresentation() &&
12212         RHS.get()->getType()->hasIntegerRepresentation())
12213       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
12214                         /*AllowBothBool*/true,
12215                         /*AllowBoolConversions*/getLangOpts().ZVector);
12216     return InvalidOperands(Loc, LHS, RHS);
12217   }
12218 
12219   if (Opc == BO_And)
12220     diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
12221 
12222   if (LHS.get()->getType()->hasFloatingRepresentation() ||
12223       RHS.get()->getType()->hasFloatingRepresentation())
12224     return InvalidOperands(Loc, LHS, RHS);
12225 
12226   ExprResult LHSResult = LHS, RHSResult = RHS;
12227   QualType compType = UsualArithmeticConversions(
12228       LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp);
12229   if (LHSResult.isInvalid() || RHSResult.isInvalid())
12230     return QualType();
12231   LHS = LHSResult.get();
12232   RHS = RHSResult.get();
12233 
12234   if (Opc == BO_Xor)
12235     diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc);
12236 
12237   if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
12238     return compType;
12239   return InvalidOperands(Loc, LHS, RHS);
12240 }
12241 
12242 // C99 6.5.[13,14]
12243 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
12244                                            SourceLocation Loc,
12245                                            BinaryOperatorKind Opc) {
12246   // Check vector operands differently.
12247   if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
12248     return CheckVectorLogicalOperands(LHS, RHS, Loc);
12249 
12250   bool EnumConstantInBoolContext = false;
12251   for (const ExprResult &HS : {LHS, RHS}) {
12252     if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) {
12253       const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl());
12254       if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1)
12255         EnumConstantInBoolContext = true;
12256     }
12257   }
12258 
12259   if (EnumConstantInBoolContext)
12260     Diag(Loc, diag::warn_enum_constant_in_bool_context);
12261 
12262   // Diagnose cases where the user write a logical and/or but probably meant a
12263   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
12264   // is a constant.
12265   if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() &&
12266       !LHS.get()->getType()->isBooleanType() &&
12267       RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
12268       // Don't warn in macros or template instantiations.
12269       !Loc.isMacroID() && !inTemplateInstantiation()) {
12270     // If the RHS can be constant folded, and if it constant folds to something
12271     // that isn't 0 or 1 (which indicate a potential logical operation that
12272     // happened to fold to true/false) then warn.
12273     // Parens on the RHS are ignored.
12274     Expr::EvalResult EVResult;
12275     if (RHS.get()->EvaluateAsInt(EVResult, Context)) {
12276       llvm::APSInt Result = EVResult.Val.getInt();
12277       if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
12278            !RHS.get()->getExprLoc().isMacroID()) ||
12279           (Result != 0 && Result != 1)) {
12280         Diag(Loc, diag::warn_logical_instead_of_bitwise)
12281           << RHS.get()->getSourceRange()
12282           << (Opc == BO_LAnd ? "&&" : "||");
12283         // Suggest replacing the logical operator with the bitwise version
12284         Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
12285             << (Opc == BO_LAnd ? "&" : "|")
12286             << FixItHint::CreateReplacement(SourceRange(
12287                                                  Loc, getLocForEndOfToken(Loc)),
12288                                             Opc == BO_LAnd ? "&" : "|");
12289         if (Opc == BO_LAnd)
12290           // Suggest replacing "Foo() && kNonZero" with "Foo()"
12291           Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
12292               << FixItHint::CreateRemoval(
12293                      SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()),
12294                                  RHS.get()->getEndLoc()));
12295       }
12296     }
12297   }
12298 
12299   if (!Context.getLangOpts().CPlusPlus) {
12300     // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
12301     // not operate on the built-in scalar and vector float types.
12302     if (Context.getLangOpts().OpenCL &&
12303         Context.getLangOpts().OpenCLVersion < 120) {
12304       if (LHS.get()->getType()->isFloatingType() ||
12305           RHS.get()->getType()->isFloatingType())
12306         return InvalidOperands(Loc, LHS, RHS);
12307     }
12308 
12309     LHS = UsualUnaryConversions(LHS.get());
12310     if (LHS.isInvalid())
12311       return QualType();
12312 
12313     RHS = UsualUnaryConversions(RHS.get());
12314     if (RHS.isInvalid())
12315       return QualType();
12316 
12317     if (!LHS.get()->getType()->isScalarType() ||
12318         !RHS.get()->getType()->isScalarType())
12319       return InvalidOperands(Loc, LHS, RHS);
12320 
12321     return Context.IntTy;
12322   }
12323 
12324   // The following is safe because we only use this method for
12325   // non-overloadable operands.
12326 
12327   // C++ [expr.log.and]p1
12328   // C++ [expr.log.or]p1
12329   // The operands are both contextually converted to type bool.
12330   ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
12331   if (LHSRes.isInvalid())
12332     return InvalidOperands(Loc, LHS, RHS);
12333   LHS = LHSRes;
12334 
12335   ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
12336   if (RHSRes.isInvalid())
12337     return InvalidOperands(Loc, LHS, RHS);
12338   RHS = RHSRes;
12339 
12340   // C++ [expr.log.and]p2
12341   // C++ [expr.log.or]p2
12342   // The result is a bool.
12343   return Context.BoolTy;
12344 }
12345 
12346 static bool IsReadonlyMessage(Expr *E, Sema &S) {
12347   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
12348   if (!ME) return false;
12349   if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
12350   ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
12351       ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
12352   if (!Base) return false;
12353   return Base->getMethodDecl() != nullptr;
12354 }
12355 
12356 /// Is the given expression (which must be 'const') a reference to a
12357 /// variable which was originally non-const, but which has become
12358 /// 'const' due to being captured within a block?
12359 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
12360 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
12361   assert(E->isLValue() && E->getType().isConstQualified());
12362   E = E->IgnoreParens();
12363 
12364   // Must be a reference to a declaration from an enclosing scope.
12365   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
12366   if (!DRE) return NCCK_None;
12367   if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
12368 
12369   // The declaration must be a variable which is not declared 'const'.
12370   VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
12371   if (!var) return NCCK_None;
12372   if (var->getType().isConstQualified()) return NCCK_None;
12373   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
12374 
12375   // Decide whether the first capture was for a block or a lambda.
12376   DeclContext *DC = S.CurContext, *Prev = nullptr;
12377   // Decide whether the first capture was for a block or a lambda.
12378   while (DC) {
12379     // For init-capture, it is possible that the variable belongs to the
12380     // template pattern of the current context.
12381     if (auto *FD = dyn_cast<FunctionDecl>(DC))
12382       if (var->isInitCapture() &&
12383           FD->getTemplateInstantiationPattern() == var->getDeclContext())
12384         break;
12385     if (DC == var->getDeclContext())
12386       break;
12387     Prev = DC;
12388     DC = DC->getParent();
12389   }
12390   // Unless we have an init-capture, we've gone one step too far.
12391   if (!var->isInitCapture())
12392     DC = Prev;
12393   return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
12394 }
12395 
12396 static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
12397   Ty = Ty.getNonReferenceType();
12398   if (IsDereference && Ty->isPointerType())
12399     Ty = Ty->getPointeeType();
12400   return !Ty.isConstQualified();
12401 }
12402 
12403 // Update err_typecheck_assign_const and note_typecheck_assign_const
12404 // when this enum is changed.
12405 enum {
12406   ConstFunction,
12407   ConstVariable,
12408   ConstMember,
12409   ConstMethod,
12410   NestedConstMember,
12411   ConstUnknown,  // Keep as last element
12412 };
12413 
12414 /// Emit the "read-only variable not assignable" error and print notes to give
12415 /// more information about why the variable is not assignable, such as pointing
12416 /// to the declaration of a const variable, showing that a method is const, or
12417 /// that the function is returning a const reference.
12418 static void DiagnoseConstAssignment(Sema &S, const Expr *E,
12419                                     SourceLocation Loc) {
12420   SourceRange ExprRange = E->getSourceRange();
12421 
12422   // Only emit one error on the first const found.  All other consts will emit
12423   // a note to the error.
12424   bool DiagnosticEmitted = false;
12425 
12426   // Track if the current expression is the result of a dereference, and if the
12427   // next checked expression is the result of a dereference.
12428   bool IsDereference = false;
12429   bool NextIsDereference = false;
12430 
12431   // Loop to process MemberExpr chains.
12432   while (true) {
12433     IsDereference = NextIsDereference;
12434 
12435     E = E->IgnoreImplicit()->IgnoreParenImpCasts();
12436     if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
12437       NextIsDereference = ME->isArrow();
12438       const ValueDecl *VD = ME->getMemberDecl();
12439       if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
12440         // Mutable fields can be modified even if the class is const.
12441         if (Field->isMutable()) {
12442           assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
12443           break;
12444         }
12445 
12446         if (!IsTypeModifiable(Field->getType(), IsDereference)) {
12447           if (!DiagnosticEmitted) {
12448             S.Diag(Loc, diag::err_typecheck_assign_const)
12449                 << ExprRange << ConstMember << false /*static*/ << Field
12450                 << Field->getType();
12451             DiagnosticEmitted = true;
12452           }
12453           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
12454               << ConstMember << false /*static*/ << Field << Field->getType()
12455               << Field->getSourceRange();
12456         }
12457         E = ME->getBase();
12458         continue;
12459       } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
12460         if (VDecl->getType().isConstQualified()) {
12461           if (!DiagnosticEmitted) {
12462             S.Diag(Loc, diag::err_typecheck_assign_const)
12463                 << ExprRange << ConstMember << true /*static*/ << VDecl
12464                 << VDecl->getType();
12465             DiagnosticEmitted = true;
12466           }
12467           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
12468               << ConstMember << true /*static*/ << VDecl << VDecl->getType()
12469               << VDecl->getSourceRange();
12470         }
12471         // Static fields do not inherit constness from parents.
12472         break;
12473       }
12474       break; // End MemberExpr
12475     } else if (const ArraySubscriptExpr *ASE =
12476                    dyn_cast<ArraySubscriptExpr>(E)) {
12477       E = ASE->getBase()->IgnoreParenImpCasts();
12478       continue;
12479     } else if (const ExtVectorElementExpr *EVE =
12480                    dyn_cast<ExtVectorElementExpr>(E)) {
12481       E = EVE->getBase()->IgnoreParenImpCasts();
12482       continue;
12483     }
12484     break;
12485   }
12486 
12487   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
12488     // Function calls
12489     const FunctionDecl *FD = CE->getDirectCallee();
12490     if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
12491       if (!DiagnosticEmitted) {
12492         S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
12493                                                       << ConstFunction << FD;
12494         DiagnosticEmitted = true;
12495       }
12496       S.Diag(FD->getReturnTypeSourceRange().getBegin(),
12497              diag::note_typecheck_assign_const)
12498           << ConstFunction << FD << FD->getReturnType()
12499           << FD->getReturnTypeSourceRange();
12500     }
12501   } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
12502     // Point to variable declaration.
12503     if (const ValueDecl *VD = DRE->getDecl()) {
12504       if (!IsTypeModifiable(VD->getType(), IsDereference)) {
12505         if (!DiagnosticEmitted) {
12506           S.Diag(Loc, diag::err_typecheck_assign_const)
12507               << ExprRange << ConstVariable << VD << VD->getType();
12508           DiagnosticEmitted = true;
12509         }
12510         S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
12511             << ConstVariable << VD << VD->getType() << VD->getSourceRange();
12512       }
12513     }
12514   } else if (isa<CXXThisExpr>(E)) {
12515     if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
12516       if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
12517         if (MD->isConst()) {
12518           if (!DiagnosticEmitted) {
12519             S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
12520                                                           << ConstMethod << MD;
12521             DiagnosticEmitted = true;
12522           }
12523           S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
12524               << ConstMethod << MD << MD->getSourceRange();
12525         }
12526       }
12527     }
12528   }
12529 
12530   if (DiagnosticEmitted)
12531     return;
12532 
12533   // Can't determine a more specific message, so display the generic error.
12534   S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
12535 }
12536 
12537 enum OriginalExprKind {
12538   OEK_Variable,
12539   OEK_Member,
12540   OEK_LValue
12541 };
12542 
12543 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD,
12544                                          const RecordType *Ty,
12545                                          SourceLocation Loc, SourceRange Range,
12546                                          OriginalExprKind OEK,
12547                                          bool &DiagnosticEmitted) {
12548   std::vector<const RecordType *> RecordTypeList;
12549   RecordTypeList.push_back(Ty);
12550   unsigned NextToCheckIndex = 0;
12551   // We walk the record hierarchy breadth-first to ensure that we print
12552   // diagnostics in field nesting order.
12553   while (RecordTypeList.size() > NextToCheckIndex) {
12554     bool IsNested = NextToCheckIndex > 0;
12555     for (const FieldDecl *Field :
12556          RecordTypeList[NextToCheckIndex]->getDecl()->fields()) {
12557       // First, check every field for constness.
12558       QualType FieldTy = Field->getType();
12559       if (FieldTy.isConstQualified()) {
12560         if (!DiagnosticEmitted) {
12561           S.Diag(Loc, diag::err_typecheck_assign_const)
12562               << Range << NestedConstMember << OEK << VD
12563               << IsNested << Field;
12564           DiagnosticEmitted = true;
12565         }
12566         S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
12567             << NestedConstMember << IsNested << Field
12568             << FieldTy << Field->getSourceRange();
12569       }
12570 
12571       // Then we append it to the list to check next in order.
12572       FieldTy = FieldTy.getCanonicalType();
12573       if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) {
12574         if (llvm::find(RecordTypeList, FieldRecTy) == RecordTypeList.end())
12575           RecordTypeList.push_back(FieldRecTy);
12576       }
12577     }
12578     ++NextToCheckIndex;
12579   }
12580 }
12581 
12582 /// Emit an error for the case where a record we are trying to assign to has a
12583 /// const-qualified field somewhere in its hierarchy.
12584 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
12585                                          SourceLocation Loc) {
12586   QualType Ty = E->getType();
12587   assert(Ty->isRecordType() && "lvalue was not record?");
12588   SourceRange Range = E->getSourceRange();
12589   const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>();
12590   bool DiagEmitted = false;
12591 
12592   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
12593     DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
12594             Range, OEK_Member, DiagEmitted);
12595   else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
12596     DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
12597             Range, OEK_Variable, DiagEmitted);
12598   else
12599     DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
12600             Range, OEK_LValue, DiagEmitted);
12601   if (!DiagEmitted)
12602     DiagnoseConstAssignment(S, E, Loc);
12603 }
12604 
12605 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
12606 /// emit an error and return true.  If so, return false.
12607 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
12608   assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
12609 
12610   S.CheckShadowingDeclModification(E, Loc);
12611 
12612   SourceLocation OrigLoc = Loc;
12613   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
12614                                                               &Loc);
12615   if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
12616     IsLV = Expr::MLV_InvalidMessageExpression;
12617   if (IsLV == Expr::MLV_Valid)
12618     return false;
12619 
12620   unsigned DiagID = 0;
12621   bool NeedType = false;
12622   switch (IsLV) { // C99 6.5.16p2
12623   case Expr::MLV_ConstQualified:
12624     // Use a specialized diagnostic when we're assigning to an object
12625     // from an enclosing function or block.
12626     if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
12627       if (NCCK == NCCK_Block)
12628         DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
12629       else
12630         DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
12631       break;
12632     }
12633 
12634     // In ARC, use some specialized diagnostics for occasions where we
12635     // infer 'const'.  These are always pseudo-strong variables.
12636     if (S.getLangOpts().ObjCAutoRefCount) {
12637       DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
12638       if (declRef && isa<VarDecl>(declRef->getDecl())) {
12639         VarDecl *var = cast<VarDecl>(declRef->getDecl());
12640 
12641         // Use the normal diagnostic if it's pseudo-__strong but the
12642         // user actually wrote 'const'.
12643         if (var->isARCPseudoStrong() &&
12644             (!var->getTypeSourceInfo() ||
12645              !var->getTypeSourceInfo()->getType().isConstQualified())) {
12646           // There are three pseudo-strong cases:
12647           //  - self
12648           ObjCMethodDecl *method = S.getCurMethodDecl();
12649           if (method && var == method->getSelfDecl()) {
12650             DiagID = method->isClassMethod()
12651               ? diag::err_typecheck_arc_assign_self_class_method
12652               : diag::err_typecheck_arc_assign_self;
12653 
12654           //  - Objective-C externally_retained attribute.
12655           } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
12656                      isa<ParmVarDecl>(var)) {
12657             DiagID = diag::err_typecheck_arc_assign_externally_retained;
12658 
12659           //  - fast enumeration variables
12660           } else {
12661             DiagID = diag::err_typecheck_arr_assign_enumeration;
12662           }
12663 
12664           SourceRange Assign;
12665           if (Loc != OrigLoc)
12666             Assign = SourceRange(OrigLoc, OrigLoc);
12667           S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
12668           // We need to preserve the AST regardless, so migration tool
12669           // can do its job.
12670           return false;
12671         }
12672       }
12673     }
12674 
12675     // If none of the special cases above are triggered, then this is a
12676     // simple const assignment.
12677     if (DiagID == 0) {
12678       DiagnoseConstAssignment(S, E, Loc);
12679       return true;
12680     }
12681 
12682     break;
12683   case Expr::MLV_ConstAddrSpace:
12684     DiagnoseConstAssignment(S, E, Loc);
12685     return true;
12686   case Expr::MLV_ConstQualifiedField:
12687     DiagnoseRecursiveConstFields(S, E, Loc);
12688     return true;
12689   case Expr::MLV_ArrayType:
12690   case Expr::MLV_ArrayTemporary:
12691     DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
12692     NeedType = true;
12693     break;
12694   case Expr::MLV_NotObjectType:
12695     DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
12696     NeedType = true;
12697     break;
12698   case Expr::MLV_LValueCast:
12699     DiagID = diag::err_typecheck_lvalue_casts_not_supported;
12700     break;
12701   case Expr::MLV_Valid:
12702     llvm_unreachable("did not take early return for MLV_Valid");
12703   case Expr::MLV_InvalidExpression:
12704   case Expr::MLV_MemberFunction:
12705   case Expr::MLV_ClassTemporary:
12706     DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
12707     break;
12708   case Expr::MLV_IncompleteType:
12709   case Expr::MLV_IncompleteVoidType:
12710     return S.RequireCompleteType(Loc, E->getType(),
12711              diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
12712   case Expr::MLV_DuplicateVectorComponents:
12713     DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
12714     break;
12715   case Expr::MLV_NoSetterProperty:
12716     llvm_unreachable("readonly properties should be processed differently");
12717   case Expr::MLV_InvalidMessageExpression:
12718     DiagID = diag::err_readonly_message_assignment;
12719     break;
12720   case Expr::MLV_SubObjCPropertySetting:
12721     DiagID = diag::err_no_subobject_property_setting;
12722     break;
12723   }
12724 
12725   SourceRange Assign;
12726   if (Loc != OrigLoc)
12727     Assign = SourceRange(OrigLoc, OrigLoc);
12728   if (NeedType)
12729     S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
12730   else
12731     S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
12732   return true;
12733 }
12734 
12735 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
12736                                          SourceLocation Loc,
12737                                          Sema &Sema) {
12738   if (Sema.inTemplateInstantiation())
12739     return;
12740   if (Sema.isUnevaluatedContext())
12741     return;
12742   if (Loc.isInvalid() || Loc.isMacroID())
12743     return;
12744   if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
12745     return;
12746 
12747   // C / C++ fields
12748   MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
12749   MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
12750   if (ML && MR) {
12751     if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
12752       return;
12753     const ValueDecl *LHSDecl =
12754         cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl());
12755     const ValueDecl *RHSDecl =
12756         cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl());
12757     if (LHSDecl != RHSDecl)
12758       return;
12759     if (LHSDecl->getType().isVolatileQualified())
12760       return;
12761     if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
12762       if (RefTy->getPointeeType().isVolatileQualified())
12763         return;
12764 
12765     Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
12766   }
12767 
12768   // Objective-C instance variables
12769   ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
12770   ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
12771   if (OL && OR && OL->getDecl() == OR->getDecl()) {
12772     DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
12773     DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
12774     if (RL && RR && RL->getDecl() == RR->getDecl())
12775       Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
12776   }
12777 }
12778 
12779 // C99 6.5.16.1
12780 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
12781                                        SourceLocation Loc,
12782                                        QualType CompoundType) {
12783   assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
12784 
12785   // Verify that LHS is a modifiable lvalue, and emit error if not.
12786   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
12787     return QualType();
12788 
12789   QualType LHSType = LHSExpr->getType();
12790   QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
12791                                              CompoundType;
12792   // OpenCL v1.2 s6.1.1.1 p2:
12793   // The half data type can only be used to declare a pointer to a buffer that
12794   // contains half values
12795   if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
12796     LHSType->isHalfType()) {
12797     Diag(Loc, diag::err_opencl_half_load_store) << 1
12798         << LHSType.getUnqualifiedType();
12799     return QualType();
12800   }
12801 
12802   AssignConvertType ConvTy;
12803   if (CompoundType.isNull()) {
12804     Expr *RHSCheck = RHS.get();
12805 
12806     CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
12807 
12808     QualType LHSTy(LHSType);
12809     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
12810     if (RHS.isInvalid())
12811       return QualType();
12812     // Special case of NSObject attributes on c-style pointer types.
12813     if (ConvTy == IncompatiblePointer &&
12814         ((Context.isObjCNSObjectType(LHSType) &&
12815           RHSType->isObjCObjectPointerType()) ||
12816          (Context.isObjCNSObjectType(RHSType) &&
12817           LHSType->isObjCObjectPointerType())))
12818       ConvTy = Compatible;
12819 
12820     if (ConvTy == Compatible &&
12821         LHSType->isObjCObjectType())
12822         Diag(Loc, diag::err_objc_object_assignment)
12823           << LHSType;
12824 
12825     // If the RHS is a unary plus or minus, check to see if they = and + are
12826     // right next to each other.  If so, the user may have typo'd "x =+ 4"
12827     // instead of "x += 4".
12828     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
12829       RHSCheck = ICE->getSubExpr();
12830     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
12831       if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
12832           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
12833           // Only if the two operators are exactly adjacent.
12834           Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
12835           // And there is a space or other character before the subexpr of the
12836           // unary +/-.  We don't want to warn on "x=-1".
12837           Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() &&
12838           UO->getSubExpr()->getBeginLoc().isFileID()) {
12839         Diag(Loc, diag::warn_not_compound_assign)
12840           << (UO->getOpcode() == UO_Plus ? "+" : "-")
12841           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
12842       }
12843     }
12844 
12845     if (ConvTy == Compatible) {
12846       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
12847         // Warn about retain cycles where a block captures the LHS, but
12848         // not if the LHS is a simple variable into which the block is
12849         // being stored...unless that variable can be captured by reference!
12850         const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
12851         const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
12852         if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
12853           checkRetainCycles(LHSExpr, RHS.get());
12854       }
12855 
12856       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
12857           LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
12858         // It is safe to assign a weak reference into a strong variable.
12859         // Although this code can still have problems:
12860         //   id x = self.weakProp;
12861         //   id y = self.weakProp;
12862         // we do not warn to warn spuriously when 'x' and 'y' are on separate
12863         // paths through the function. This should be revisited if
12864         // -Wrepeated-use-of-weak is made flow-sensitive.
12865         // For ObjCWeak only, we do not warn if the assign is to a non-weak
12866         // variable, which will be valid for the current autorelease scope.
12867         if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
12868                              RHS.get()->getBeginLoc()))
12869           getCurFunction()->markSafeWeakUse(RHS.get());
12870 
12871       } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
12872         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
12873       }
12874     }
12875   } else {
12876     // Compound assignment "x += y"
12877     ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
12878   }
12879 
12880   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
12881                                RHS.get(), AA_Assigning))
12882     return QualType();
12883 
12884   CheckForNullPointerDereference(*this, LHSExpr);
12885 
12886   if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) {
12887     if (CompoundType.isNull()) {
12888       // C++2a [expr.ass]p5:
12889       //   A simple-assignment whose left operand is of a volatile-qualified
12890       //   type is deprecated unless the assignment is either a discarded-value
12891       //   expression or an unevaluated operand
12892       ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr);
12893     } else {
12894       // C++2a [expr.ass]p6:
12895       //   [Compound-assignment] expressions are deprecated if E1 has
12896       //   volatile-qualified type
12897       Diag(Loc, diag::warn_deprecated_compound_assign_volatile) << LHSType;
12898     }
12899   }
12900 
12901   // C99 6.5.16p3: The type of an assignment expression is the type of the
12902   // left operand unless the left operand has qualified type, in which case
12903   // it is the unqualified version of the type of the left operand.
12904   // C99 6.5.16.1p2: In simple assignment, the value of the right operand
12905   // is converted to the type of the assignment expression (above).
12906   // C++ 5.17p1: the type of the assignment expression is that of its left
12907   // operand.
12908   return (getLangOpts().CPlusPlus
12909           ? LHSType : LHSType.getUnqualifiedType());
12910 }
12911 
12912 // Only ignore explicit casts to void.
12913 static bool IgnoreCommaOperand(const Expr *E) {
12914   E = E->IgnoreParens();
12915 
12916   if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
12917     if (CE->getCastKind() == CK_ToVoid) {
12918       return true;
12919     }
12920 
12921     // static_cast<void> on a dependent type will not show up as CK_ToVoid.
12922     if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
12923         CE->getSubExpr()->getType()->isDependentType()) {
12924       return true;
12925     }
12926   }
12927 
12928   return false;
12929 }
12930 
12931 // Look for instances where it is likely the comma operator is confused with
12932 // another operator.  There is an explicit list of acceptable expressions for
12933 // the left hand side of the comma operator, otherwise emit a warning.
12934 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
12935   // No warnings in macros
12936   if (Loc.isMacroID())
12937     return;
12938 
12939   // Don't warn in template instantiations.
12940   if (inTemplateInstantiation())
12941     return;
12942 
12943   // Scope isn't fine-grained enough to explicitly list the specific cases, so
12944   // instead, skip more than needed, then call back into here with the
12945   // CommaVisitor in SemaStmt.cpp.
12946   // The listed locations are the initialization and increment portions
12947   // of a for loop.  The additional checks are on the condition of
12948   // if statements, do/while loops, and for loops.
12949   // Differences in scope flags for C89 mode requires the extra logic.
12950   const unsigned ForIncrementFlags =
12951       getLangOpts().C99 || getLangOpts().CPlusPlus
12952           ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope
12953           : Scope::ContinueScope | Scope::BreakScope;
12954   const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
12955   const unsigned ScopeFlags = getCurScope()->getFlags();
12956   if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
12957       (ScopeFlags & ForInitFlags) == ForInitFlags)
12958     return;
12959 
12960   // If there are multiple comma operators used together, get the RHS of the
12961   // of the comma operator as the LHS.
12962   while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
12963     if (BO->getOpcode() != BO_Comma)
12964       break;
12965     LHS = BO->getRHS();
12966   }
12967 
12968   // Only allow some expressions on LHS to not warn.
12969   if (IgnoreCommaOperand(LHS))
12970     return;
12971 
12972   Diag(Loc, diag::warn_comma_operator);
12973   Diag(LHS->getBeginLoc(), diag::note_cast_to_void)
12974       << LHS->getSourceRange()
12975       << FixItHint::CreateInsertion(LHS->getBeginLoc(),
12976                                     LangOpts.CPlusPlus ? "static_cast<void>("
12977                                                        : "(void)(")
12978       << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()),
12979                                     ")");
12980 }
12981 
12982 // C99 6.5.17
12983 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
12984                                    SourceLocation Loc) {
12985   LHS = S.CheckPlaceholderExpr(LHS.get());
12986   RHS = S.CheckPlaceholderExpr(RHS.get());
12987   if (LHS.isInvalid() || RHS.isInvalid())
12988     return QualType();
12989 
12990   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
12991   // operands, but not unary promotions.
12992   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
12993 
12994   // So we treat the LHS as a ignored value, and in C++ we allow the
12995   // containing site to determine what should be done with the RHS.
12996   LHS = S.IgnoredValueConversions(LHS.get());
12997   if (LHS.isInvalid())
12998     return QualType();
12999 
13000   S.DiagnoseUnusedExprResult(LHS.get());
13001 
13002   if (!S.getLangOpts().CPlusPlus) {
13003     RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
13004     if (RHS.isInvalid())
13005       return QualType();
13006     if (!RHS.get()->getType()->isVoidType())
13007       S.RequireCompleteType(Loc, RHS.get()->getType(),
13008                             diag::err_incomplete_type);
13009   }
13010 
13011   if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
13012     S.DiagnoseCommaOperator(LHS.get(), Loc);
13013 
13014   return RHS.get()->getType();
13015 }
13016 
13017 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
13018 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
13019 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
13020                                                ExprValueKind &VK,
13021                                                ExprObjectKind &OK,
13022                                                SourceLocation OpLoc,
13023                                                bool IsInc, bool IsPrefix) {
13024   if (Op->isTypeDependent())
13025     return S.Context.DependentTy;
13026 
13027   QualType ResType = Op->getType();
13028   // Atomic types can be used for increment / decrement where the non-atomic
13029   // versions can, so ignore the _Atomic() specifier for the purpose of
13030   // checking.
13031   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
13032     ResType = ResAtomicType->getValueType();
13033 
13034   assert(!ResType.isNull() && "no type for increment/decrement expression");
13035 
13036   if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
13037     // Decrement of bool is not allowed.
13038     if (!IsInc) {
13039       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
13040       return QualType();
13041     }
13042     // Increment of bool sets it to true, but is deprecated.
13043     S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
13044                                               : diag::warn_increment_bool)
13045       << Op->getSourceRange();
13046   } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
13047     // Error on enum increments and decrements in C++ mode
13048     S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
13049     return QualType();
13050   } else if (ResType->isRealType()) {
13051     // OK!
13052   } else if (ResType->isPointerType()) {
13053     // C99 6.5.2.4p2, 6.5.6p2
13054     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
13055       return QualType();
13056   } else if (ResType->isObjCObjectPointerType()) {
13057     // On modern runtimes, ObjC pointer arithmetic is forbidden.
13058     // Otherwise, we just need a complete type.
13059     if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
13060         checkArithmeticOnObjCPointer(S, OpLoc, Op))
13061       return QualType();
13062   } else if (ResType->isAnyComplexType()) {
13063     // C99 does not support ++/-- on complex types, we allow as an extension.
13064     S.Diag(OpLoc, diag::ext_integer_increment_complex)
13065       << ResType << Op->getSourceRange();
13066   } else if (ResType->isPlaceholderType()) {
13067     ExprResult PR = S.CheckPlaceholderExpr(Op);
13068     if (PR.isInvalid()) return QualType();
13069     return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
13070                                           IsInc, IsPrefix);
13071   } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
13072     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
13073   } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
13074              (ResType->castAs<VectorType>()->getVectorKind() !=
13075               VectorType::AltiVecBool)) {
13076     // The z vector extensions allow ++ and -- for non-bool vectors.
13077   } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
13078             ResType->castAs<VectorType>()->getElementType()->isIntegerType()) {
13079     // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
13080   } else {
13081     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
13082       << ResType << int(IsInc) << Op->getSourceRange();
13083     return QualType();
13084   }
13085   // At this point, we know we have a real, complex or pointer type.
13086   // Now make sure the operand is a modifiable lvalue.
13087   if (CheckForModifiableLvalue(Op, OpLoc, S))
13088     return QualType();
13089   if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) {
13090     // C++2a [expr.pre.inc]p1, [expr.post.inc]p1:
13091     //   An operand with volatile-qualified type is deprecated
13092     S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile)
13093         << IsInc << ResType;
13094   }
13095   // In C++, a prefix increment is the same type as the operand. Otherwise
13096   // (in C or with postfix), the increment is the unqualified type of the
13097   // operand.
13098   if (IsPrefix && S.getLangOpts().CPlusPlus) {
13099     VK = VK_LValue;
13100     OK = Op->getObjectKind();
13101     return ResType;
13102   } else {
13103     VK = VK_RValue;
13104     return ResType.getUnqualifiedType();
13105   }
13106 }
13107 
13108 
13109 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
13110 /// This routine allows us to typecheck complex/recursive expressions
13111 /// where the declaration is needed for type checking. We only need to
13112 /// handle cases when the expression references a function designator
13113 /// or is an lvalue. Here are some examples:
13114 ///  - &(x) => x
13115 ///  - &*****f => f for f a function designator.
13116 ///  - &s.xx => s
13117 ///  - &s.zz[1].yy -> s, if zz is an array
13118 ///  - *(x + 1) -> x, if x is an array
13119 ///  - &"123"[2] -> 0
13120 ///  - & __real__ x -> x
13121 ///
13122 /// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to
13123 /// members.
13124 static ValueDecl *getPrimaryDecl(Expr *E) {
13125   switch (E->getStmtClass()) {
13126   case Stmt::DeclRefExprClass:
13127     return cast<DeclRefExpr>(E)->getDecl();
13128   case Stmt::MemberExprClass:
13129     // If this is an arrow operator, the address is an offset from
13130     // the base's value, so the object the base refers to is
13131     // irrelevant.
13132     if (cast<MemberExpr>(E)->isArrow())
13133       return nullptr;
13134     // Otherwise, the expression refers to a part of the base
13135     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
13136   case Stmt::ArraySubscriptExprClass: {
13137     // FIXME: This code shouldn't be necessary!  We should catch the implicit
13138     // promotion of register arrays earlier.
13139     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
13140     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
13141       if (ICE->getSubExpr()->getType()->isArrayType())
13142         return getPrimaryDecl(ICE->getSubExpr());
13143     }
13144     return nullptr;
13145   }
13146   case Stmt::UnaryOperatorClass: {
13147     UnaryOperator *UO = cast<UnaryOperator>(E);
13148 
13149     switch(UO->getOpcode()) {
13150     case UO_Real:
13151     case UO_Imag:
13152     case UO_Extension:
13153       return getPrimaryDecl(UO->getSubExpr());
13154     default:
13155       return nullptr;
13156     }
13157   }
13158   case Stmt::ParenExprClass:
13159     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
13160   case Stmt::ImplicitCastExprClass:
13161     // If the result of an implicit cast is an l-value, we care about
13162     // the sub-expression; otherwise, the result here doesn't matter.
13163     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
13164   case Stmt::CXXUuidofExprClass:
13165     return cast<CXXUuidofExpr>(E)->getGuidDecl();
13166   default:
13167     return nullptr;
13168   }
13169 }
13170 
13171 namespace {
13172 enum {
13173   AO_Bit_Field = 0,
13174   AO_Vector_Element = 1,
13175   AO_Property_Expansion = 2,
13176   AO_Register_Variable = 3,
13177   AO_Matrix_Element = 4,
13178   AO_No_Error = 5
13179 };
13180 }
13181 /// Diagnose invalid operand for address of operations.
13182 ///
13183 /// \param Type The type of operand which cannot have its address taken.
13184 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
13185                                          Expr *E, unsigned Type) {
13186   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
13187 }
13188 
13189 /// CheckAddressOfOperand - The operand of & must be either a function
13190 /// designator or an lvalue designating an object. If it is an lvalue, the
13191 /// object cannot be declared with storage class register or be a bit field.
13192 /// Note: The usual conversions are *not* applied to the operand of the &
13193 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
13194 /// In C++, the operand might be an overloaded function name, in which case
13195 /// we allow the '&' but retain the overloaded-function type.
13196 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
13197   if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
13198     if (PTy->getKind() == BuiltinType::Overload) {
13199       Expr *E = OrigOp.get()->IgnoreParens();
13200       if (!isa<OverloadExpr>(E)) {
13201         assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
13202         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
13203           << OrigOp.get()->getSourceRange();
13204         return QualType();
13205       }
13206 
13207       OverloadExpr *Ovl = cast<OverloadExpr>(E);
13208       if (isa<UnresolvedMemberExpr>(Ovl))
13209         if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
13210           Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
13211             << OrigOp.get()->getSourceRange();
13212           return QualType();
13213         }
13214 
13215       return Context.OverloadTy;
13216     }
13217 
13218     if (PTy->getKind() == BuiltinType::UnknownAny)
13219       return Context.UnknownAnyTy;
13220 
13221     if (PTy->getKind() == BuiltinType::BoundMember) {
13222       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
13223         << OrigOp.get()->getSourceRange();
13224       return QualType();
13225     }
13226 
13227     OrigOp = CheckPlaceholderExpr(OrigOp.get());
13228     if (OrigOp.isInvalid()) return QualType();
13229   }
13230 
13231   if (OrigOp.get()->isTypeDependent())
13232     return Context.DependentTy;
13233 
13234   assert(!OrigOp.get()->getType()->isPlaceholderType());
13235 
13236   // Make sure to ignore parentheses in subsequent checks
13237   Expr *op = OrigOp.get()->IgnoreParens();
13238 
13239   // In OpenCL captures for blocks called as lambda functions
13240   // are located in the private address space. Blocks used in
13241   // enqueue_kernel can be located in a different address space
13242   // depending on a vendor implementation. Thus preventing
13243   // taking an address of the capture to avoid invalid AS casts.
13244   if (LangOpts.OpenCL) {
13245     auto* VarRef = dyn_cast<DeclRefExpr>(op);
13246     if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
13247       Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
13248       return QualType();
13249     }
13250   }
13251 
13252   if (getLangOpts().C99) {
13253     // Implement C99-only parts of addressof rules.
13254     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
13255       if (uOp->getOpcode() == UO_Deref)
13256         // Per C99 6.5.3.2, the address of a deref always returns a valid result
13257         // (assuming the deref expression is valid).
13258         return uOp->getSubExpr()->getType();
13259     }
13260     // Technically, there should be a check for array subscript
13261     // expressions here, but the result of one is always an lvalue anyway.
13262   }
13263   ValueDecl *dcl = getPrimaryDecl(op);
13264 
13265   if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
13266     if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
13267                                            op->getBeginLoc()))
13268       return QualType();
13269 
13270   Expr::LValueClassification lval = op->ClassifyLValue(Context);
13271   unsigned AddressOfError = AO_No_Error;
13272 
13273   if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
13274     bool sfinae = (bool)isSFINAEContext();
13275     Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
13276                                   : diag::ext_typecheck_addrof_temporary)
13277       << op->getType() << op->getSourceRange();
13278     if (sfinae)
13279       return QualType();
13280     // Materialize the temporary as an lvalue so that we can take its address.
13281     OrigOp = op =
13282         CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
13283   } else if (isa<ObjCSelectorExpr>(op)) {
13284     return Context.getPointerType(op->getType());
13285   } else if (lval == Expr::LV_MemberFunction) {
13286     // If it's an instance method, make a member pointer.
13287     // The expression must have exactly the form &A::foo.
13288 
13289     // If the underlying expression isn't a decl ref, give up.
13290     if (!isa<DeclRefExpr>(op)) {
13291       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
13292         << OrigOp.get()->getSourceRange();
13293       return QualType();
13294     }
13295     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
13296     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
13297 
13298     // The id-expression was parenthesized.
13299     if (OrigOp.get() != DRE) {
13300       Diag(OpLoc, diag::err_parens_pointer_member_function)
13301         << OrigOp.get()->getSourceRange();
13302 
13303     // The method was named without a qualifier.
13304     } else if (!DRE->getQualifier()) {
13305       if (MD->getParent()->getName().empty())
13306         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
13307           << op->getSourceRange();
13308       else {
13309         SmallString<32> Str;
13310         StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
13311         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
13312           << op->getSourceRange()
13313           << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
13314       }
13315     }
13316 
13317     // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
13318     if (isa<CXXDestructorDecl>(MD))
13319       Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
13320 
13321     QualType MPTy = Context.getMemberPointerType(
13322         op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
13323     // Under the MS ABI, lock down the inheritance model now.
13324     if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13325       (void)isCompleteType(OpLoc, MPTy);
13326     return MPTy;
13327   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
13328     // C99 6.5.3.2p1
13329     // The operand must be either an l-value or a function designator
13330     if (!op->getType()->isFunctionType()) {
13331       // Use a special diagnostic for loads from property references.
13332       if (isa<PseudoObjectExpr>(op)) {
13333         AddressOfError = AO_Property_Expansion;
13334       } else {
13335         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
13336           << op->getType() << op->getSourceRange();
13337         return QualType();
13338       }
13339     }
13340   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
13341     // The operand cannot be a bit-field
13342     AddressOfError = AO_Bit_Field;
13343   } else if (op->getObjectKind() == OK_VectorComponent) {
13344     // The operand cannot be an element of a vector
13345     AddressOfError = AO_Vector_Element;
13346   } else if (op->getObjectKind() == OK_MatrixComponent) {
13347     // The operand cannot be an element of a matrix.
13348     AddressOfError = AO_Matrix_Element;
13349   } else if (dcl) { // C99 6.5.3.2p1
13350     // We have an lvalue with a decl. Make sure the decl is not declared
13351     // with the register storage-class specifier.
13352     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
13353       // in C++ it is not error to take address of a register
13354       // variable (c++03 7.1.1P3)
13355       if (vd->getStorageClass() == SC_Register &&
13356           !getLangOpts().CPlusPlus) {
13357         AddressOfError = AO_Register_Variable;
13358       }
13359     } else if (isa<MSPropertyDecl>(dcl)) {
13360       AddressOfError = AO_Property_Expansion;
13361     } else if (isa<FunctionTemplateDecl>(dcl)) {
13362       return Context.OverloadTy;
13363     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
13364       // Okay: we can take the address of a field.
13365       // Could be a pointer to member, though, if there is an explicit
13366       // scope qualifier for the class.
13367       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
13368         DeclContext *Ctx = dcl->getDeclContext();
13369         if (Ctx && Ctx->isRecord()) {
13370           if (dcl->getType()->isReferenceType()) {
13371             Diag(OpLoc,
13372                  diag::err_cannot_form_pointer_to_member_of_reference_type)
13373               << dcl->getDeclName() << dcl->getType();
13374             return QualType();
13375           }
13376 
13377           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
13378             Ctx = Ctx->getParent();
13379 
13380           QualType MPTy = Context.getMemberPointerType(
13381               op->getType(),
13382               Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
13383           // Under the MS ABI, lock down the inheritance model now.
13384           if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13385             (void)isCompleteType(OpLoc, MPTy);
13386           return MPTy;
13387         }
13388       }
13389     } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) &&
13390                !isa<BindingDecl>(dcl) && !isa<MSGuidDecl>(dcl))
13391       llvm_unreachable("Unknown/unexpected decl type");
13392   }
13393 
13394   if (AddressOfError != AO_No_Error) {
13395     diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
13396     return QualType();
13397   }
13398 
13399   if (lval == Expr::LV_IncompleteVoidType) {
13400     // Taking the address of a void variable is technically illegal, but we
13401     // allow it in cases which are otherwise valid.
13402     // Example: "extern void x; void* y = &x;".
13403     Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
13404   }
13405 
13406   // If the operand has type "type", the result has type "pointer to type".
13407   if (op->getType()->isObjCObjectType())
13408     return Context.getObjCObjectPointerType(op->getType());
13409 
13410   CheckAddressOfPackedMember(op);
13411 
13412   return Context.getPointerType(op->getType());
13413 }
13414 
13415 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
13416   const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
13417   if (!DRE)
13418     return;
13419   const Decl *D = DRE->getDecl();
13420   if (!D)
13421     return;
13422   const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
13423   if (!Param)
13424     return;
13425   if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
13426     if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
13427       return;
13428   if (FunctionScopeInfo *FD = S.getCurFunction())
13429     if (!FD->ModifiedNonNullParams.count(Param))
13430       FD->ModifiedNonNullParams.insert(Param);
13431 }
13432 
13433 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
13434 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
13435                                         SourceLocation OpLoc) {
13436   if (Op->isTypeDependent())
13437     return S.Context.DependentTy;
13438 
13439   ExprResult ConvResult = S.UsualUnaryConversions(Op);
13440   if (ConvResult.isInvalid())
13441     return QualType();
13442   Op = ConvResult.get();
13443   QualType OpTy = Op->getType();
13444   QualType Result;
13445 
13446   if (isa<CXXReinterpretCastExpr>(Op)) {
13447     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
13448     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
13449                                      Op->getSourceRange());
13450   }
13451 
13452   if (const PointerType *PT = OpTy->getAs<PointerType>())
13453   {
13454     Result = PT->getPointeeType();
13455   }
13456   else if (const ObjCObjectPointerType *OPT =
13457              OpTy->getAs<ObjCObjectPointerType>())
13458     Result = OPT->getPointeeType();
13459   else {
13460     ExprResult PR = S.CheckPlaceholderExpr(Op);
13461     if (PR.isInvalid()) return QualType();
13462     if (PR.get() != Op)
13463       return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
13464   }
13465 
13466   if (Result.isNull()) {
13467     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
13468       << OpTy << Op->getSourceRange();
13469     return QualType();
13470   }
13471 
13472   // Note that per both C89 and C99, indirection is always legal, even if Result
13473   // is an incomplete type or void.  It would be possible to warn about
13474   // dereferencing a void pointer, but it's completely well-defined, and such a
13475   // warning is unlikely to catch any mistakes. In C++, indirection is not valid
13476   // for pointers to 'void' but is fine for any other pointer type:
13477   //
13478   // C++ [expr.unary.op]p1:
13479   //   [...] the expression to which [the unary * operator] is applied shall
13480   //   be a pointer to an object type, or a pointer to a function type
13481   if (S.getLangOpts().CPlusPlus && Result->isVoidType())
13482     S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
13483       << OpTy << Op->getSourceRange();
13484 
13485   // Dereferences are usually l-values...
13486   VK = VK_LValue;
13487 
13488   // ...except that certain expressions are never l-values in C.
13489   if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
13490     VK = VK_RValue;
13491 
13492   return Result;
13493 }
13494 
13495 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
13496   BinaryOperatorKind Opc;
13497   switch (Kind) {
13498   default: llvm_unreachable("Unknown binop!");
13499   case tok::periodstar:           Opc = BO_PtrMemD; break;
13500   case tok::arrowstar:            Opc = BO_PtrMemI; break;
13501   case tok::star:                 Opc = BO_Mul; break;
13502   case tok::slash:                Opc = BO_Div; break;
13503   case tok::percent:              Opc = BO_Rem; break;
13504   case tok::plus:                 Opc = BO_Add; break;
13505   case tok::minus:                Opc = BO_Sub; break;
13506   case tok::lessless:             Opc = BO_Shl; break;
13507   case tok::greatergreater:       Opc = BO_Shr; break;
13508   case tok::lessequal:            Opc = BO_LE; break;
13509   case tok::less:                 Opc = BO_LT; break;
13510   case tok::greaterequal:         Opc = BO_GE; break;
13511   case tok::greater:              Opc = BO_GT; break;
13512   case tok::exclaimequal:         Opc = BO_NE; break;
13513   case tok::equalequal:           Opc = BO_EQ; break;
13514   case tok::spaceship:            Opc = BO_Cmp; break;
13515   case tok::amp:                  Opc = BO_And; break;
13516   case tok::caret:                Opc = BO_Xor; break;
13517   case tok::pipe:                 Opc = BO_Or; break;
13518   case tok::ampamp:               Opc = BO_LAnd; break;
13519   case tok::pipepipe:             Opc = BO_LOr; break;
13520   case tok::equal:                Opc = BO_Assign; break;
13521   case tok::starequal:            Opc = BO_MulAssign; break;
13522   case tok::slashequal:           Opc = BO_DivAssign; break;
13523   case tok::percentequal:         Opc = BO_RemAssign; break;
13524   case tok::plusequal:            Opc = BO_AddAssign; break;
13525   case tok::minusequal:           Opc = BO_SubAssign; break;
13526   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
13527   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
13528   case tok::ampequal:             Opc = BO_AndAssign; break;
13529   case tok::caretequal:           Opc = BO_XorAssign; break;
13530   case tok::pipeequal:            Opc = BO_OrAssign; break;
13531   case tok::comma:                Opc = BO_Comma; break;
13532   }
13533   return Opc;
13534 }
13535 
13536 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
13537   tok::TokenKind Kind) {
13538   UnaryOperatorKind Opc;
13539   switch (Kind) {
13540   default: llvm_unreachable("Unknown unary op!");
13541   case tok::plusplus:     Opc = UO_PreInc; break;
13542   case tok::minusminus:   Opc = UO_PreDec; break;
13543   case tok::amp:          Opc = UO_AddrOf; break;
13544   case tok::star:         Opc = UO_Deref; break;
13545   case tok::plus:         Opc = UO_Plus; break;
13546   case tok::minus:        Opc = UO_Minus; break;
13547   case tok::tilde:        Opc = UO_Not; break;
13548   case tok::exclaim:      Opc = UO_LNot; break;
13549   case tok::kw___real:    Opc = UO_Real; break;
13550   case tok::kw___imag:    Opc = UO_Imag; break;
13551   case tok::kw___extension__: Opc = UO_Extension; break;
13552   }
13553   return Opc;
13554 }
13555 
13556 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
13557 /// This warning suppressed in the event of macro expansions.
13558 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
13559                                    SourceLocation OpLoc, bool IsBuiltin) {
13560   if (S.inTemplateInstantiation())
13561     return;
13562   if (S.isUnevaluatedContext())
13563     return;
13564   if (OpLoc.isInvalid() || OpLoc.isMacroID())
13565     return;
13566   LHSExpr = LHSExpr->IgnoreParenImpCasts();
13567   RHSExpr = RHSExpr->IgnoreParenImpCasts();
13568   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
13569   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
13570   if (!LHSDeclRef || !RHSDeclRef ||
13571       LHSDeclRef->getLocation().isMacroID() ||
13572       RHSDeclRef->getLocation().isMacroID())
13573     return;
13574   const ValueDecl *LHSDecl =
13575     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
13576   const ValueDecl *RHSDecl =
13577     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
13578   if (LHSDecl != RHSDecl)
13579     return;
13580   if (LHSDecl->getType().isVolatileQualified())
13581     return;
13582   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
13583     if (RefTy->getPointeeType().isVolatileQualified())
13584       return;
13585 
13586   S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
13587                           : diag::warn_self_assignment_overloaded)
13588       << LHSDeclRef->getType() << LHSExpr->getSourceRange()
13589       << RHSExpr->getSourceRange();
13590 }
13591 
13592 /// Check if a bitwise-& is performed on an Objective-C pointer.  This
13593 /// is usually indicative of introspection within the Objective-C pointer.
13594 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
13595                                           SourceLocation OpLoc) {
13596   if (!S.getLangOpts().ObjC)
13597     return;
13598 
13599   const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
13600   const Expr *LHS = L.get();
13601   const Expr *RHS = R.get();
13602 
13603   if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
13604     ObjCPointerExpr = LHS;
13605     OtherExpr = RHS;
13606   }
13607   else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
13608     ObjCPointerExpr = RHS;
13609     OtherExpr = LHS;
13610   }
13611 
13612   // This warning is deliberately made very specific to reduce false
13613   // positives with logic that uses '&' for hashing.  This logic mainly
13614   // looks for code trying to introspect into tagged pointers, which
13615   // code should generally never do.
13616   if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
13617     unsigned Diag = diag::warn_objc_pointer_masking;
13618     // Determine if we are introspecting the result of performSelectorXXX.
13619     const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
13620     // Special case messages to -performSelector and friends, which
13621     // can return non-pointer values boxed in a pointer value.
13622     // Some clients may wish to silence warnings in this subcase.
13623     if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
13624       Selector S = ME->getSelector();
13625       StringRef SelArg0 = S.getNameForSlot(0);
13626       if (SelArg0.startswith("performSelector"))
13627         Diag = diag::warn_objc_pointer_masking_performSelector;
13628     }
13629 
13630     S.Diag(OpLoc, Diag)
13631       << ObjCPointerExpr->getSourceRange();
13632   }
13633 }
13634 
13635 static NamedDecl *getDeclFromExpr(Expr *E) {
13636   if (!E)
13637     return nullptr;
13638   if (auto *DRE = dyn_cast<DeclRefExpr>(E))
13639     return DRE->getDecl();
13640   if (auto *ME = dyn_cast<MemberExpr>(E))
13641     return ME->getMemberDecl();
13642   if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
13643     return IRE->getDecl();
13644   return nullptr;
13645 }
13646 
13647 // This helper function promotes a binary operator's operands (which are of a
13648 // half vector type) to a vector of floats and then truncates the result to
13649 // a vector of either half or short.
13650 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS,
13651                                       BinaryOperatorKind Opc, QualType ResultTy,
13652                                       ExprValueKind VK, ExprObjectKind OK,
13653                                       bool IsCompAssign, SourceLocation OpLoc,
13654                                       FPOptionsOverride FPFeatures) {
13655   auto &Context = S.getASTContext();
13656   assert((isVector(ResultTy, Context.HalfTy) ||
13657           isVector(ResultTy, Context.ShortTy)) &&
13658          "Result must be a vector of half or short");
13659   assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
13660          isVector(RHS.get()->getType(), Context.HalfTy) &&
13661          "both operands expected to be a half vector");
13662 
13663   RHS = convertVector(RHS.get(), Context.FloatTy, S);
13664   QualType BinOpResTy = RHS.get()->getType();
13665 
13666   // If Opc is a comparison, ResultType is a vector of shorts. In that case,
13667   // change BinOpResTy to a vector of ints.
13668   if (isVector(ResultTy, Context.ShortTy))
13669     BinOpResTy = S.GetSignedVectorType(BinOpResTy);
13670 
13671   if (IsCompAssign)
13672     return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc,
13673                                           ResultTy, VK, OK, OpLoc, FPFeatures,
13674                                           BinOpResTy, BinOpResTy);
13675 
13676   LHS = convertVector(LHS.get(), Context.FloatTy, S);
13677   auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc,
13678                                     BinOpResTy, VK, OK, OpLoc, FPFeatures);
13679   return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S);
13680 }
13681 
13682 static std::pair<ExprResult, ExprResult>
13683 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr,
13684                            Expr *RHSExpr) {
13685   ExprResult LHS = LHSExpr, RHS = RHSExpr;
13686   if (!S.getLangOpts().CPlusPlus) {
13687     // C cannot handle TypoExpr nodes on either side of a binop because it
13688     // doesn't handle dependent types properly, so make sure any TypoExprs have
13689     // been dealt with before checking the operands.
13690     LHS = S.CorrectDelayedTyposInExpr(LHS);
13691     RHS = S.CorrectDelayedTyposInExpr(
13692         RHS, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false,
13693         [Opc, LHS](Expr *E) {
13694           if (Opc != BO_Assign)
13695             return ExprResult(E);
13696           // Avoid correcting the RHS to the same Expr as the LHS.
13697           Decl *D = getDeclFromExpr(E);
13698           return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
13699         });
13700   }
13701   return std::make_pair(LHS, RHS);
13702 }
13703 
13704 /// Returns true if conversion between vectors of halfs and vectors of floats
13705 /// is needed.
13706 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
13707                                      Expr *E0, Expr *E1 = nullptr) {
13708   if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType ||
13709       Ctx.getTargetInfo().useFP16ConversionIntrinsics())
13710     return false;
13711 
13712   auto HasVectorOfHalfType = [&Ctx](Expr *E) {
13713     QualType Ty = E->IgnoreImplicit()->getType();
13714 
13715     // Don't promote half precision neon vectors like float16x4_t in arm_neon.h
13716     // to vectors of floats. Although the element type of the vectors is __fp16,
13717     // the vectors shouldn't be treated as storage-only types. See the
13718     // discussion here: https://reviews.llvm.org/rG825235c140e7
13719     if (const VectorType *VT = Ty->getAs<VectorType>()) {
13720       if (VT->getVectorKind() == VectorType::NeonVector)
13721         return false;
13722       return VT->getElementType().getCanonicalType() == Ctx.HalfTy;
13723     }
13724     return false;
13725   };
13726 
13727   return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1));
13728 }
13729 
13730 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
13731 /// operator @p Opc at location @c TokLoc. This routine only supports
13732 /// built-in operations; ActOnBinOp handles overloaded operators.
13733 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
13734                                     BinaryOperatorKind Opc,
13735                                     Expr *LHSExpr, Expr *RHSExpr) {
13736   if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
13737     // The syntax only allows initializer lists on the RHS of assignment,
13738     // so we don't need to worry about accepting invalid code for
13739     // non-assignment operators.
13740     // C++11 5.17p9:
13741     //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
13742     //   of x = {} is x = T().
13743     InitializationKind Kind = InitializationKind::CreateDirectList(
13744         RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
13745     InitializedEntity Entity =
13746         InitializedEntity::InitializeTemporary(LHSExpr->getType());
13747     InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
13748     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
13749     if (Init.isInvalid())
13750       return Init;
13751     RHSExpr = Init.get();
13752   }
13753 
13754   ExprResult LHS = LHSExpr, RHS = RHSExpr;
13755   QualType ResultTy;     // Result type of the binary operator.
13756   // The following two variables are used for compound assignment operators
13757   QualType CompLHSTy;    // Type of LHS after promotions for computation
13758   QualType CompResultTy; // Type of computation result
13759   ExprValueKind VK = VK_RValue;
13760   ExprObjectKind OK = OK_Ordinary;
13761   bool ConvertHalfVec = false;
13762 
13763   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
13764   if (!LHS.isUsable() || !RHS.isUsable())
13765     return ExprError();
13766 
13767   if (getLangOpts().OpenCL) {
13768     QualType LHSTy = LHSExpr->getType();
13769     QualType RHSTy = RHSExpr->getType();
13770     // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
13771     // the ATOMIC_VAR_INIT macro.
13772     if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
13773       SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
13774       if (BO_Assign == Opc)
13775         Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
13776       else
13777         ResultTy = InvalidOperands(OpLoc, LHS, RHS);
13778       return ExprError();
13779     }
13780 
13781     // OpenCL special types - image, sampler, pipe, and blocks are to be used
13782     // only with a builtin functions and therefore should be disallowed here.
13783     if (LHSTy->isImageType() || RHSTy->isImageType() ||
13784         LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
13785         LHSTy->isPipeType() || RHSTy->isPipeType() ||
13786         LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
13787       ResultTy = InvalidOperands(OpLoc, LHS, RHS);
13788       return ExprError();
13789     }
13790   }
13791 
13792   switch (Opc) {
13793   case BO_Assign:
13794     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
13795     if (getLangOpts().CPlusPlus &&
13796         LHS.get()->getObjectKind() != OK_ObjCProperty) {
13797       VK = LHS.get()->getValueKind();
13798       OK = LHS.get()->getObjectKind();
13799     }
13800     if (!ResultTy.isNull()) {
13801       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
13802       DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
13803 
13804       // Avoid copying a block to the heap if the block is assigned to a local
13805       // auto variable that is declared in the same scope as the block. This
13806       // optimization is unsafe if the local variable is declared in an outer
13807       // scope. For example:
13808       //
13809       // BlockTy b;
13810       // {
13811       //   b = ^{...};
13812       // }
13813       // // It is unsafe to invoke the block here if it wasn't copied to the
13814       // // heap.
13815       // b();
13816 
13817       if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens()))
13818         if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
13819           if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
13820             if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD))
13821               BE->getBlockDecl()->setCanAvoidCopyToHeap();
13822 
13823       if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion())
13824         checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(),
13825                               NTCUC_Assignment, NTCUK_Copy);
13826     }
13827     RecordModifiableNonNullParam(*this, LHS.get());
13828     break;
13829   case BO_PtrMemD:
13830   case BO_PtrMemI:
13831     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
13832                                             Opc == BO_PtrMemI);
13833     break;
13834   case BO_Mul:
13835   case BO_Div:
13836     ConvertHalfVec = true;
13837     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
13838                                            Opc == BO_Div);
13839     break;
13840   case BO_Rem:
13841     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
13842     break;
13843   case BO_Add:
13844     ConvertHalfVec = true;
13845     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
13846     break;
13847   case BO_Sub:
13848     ConvertHalfVec = true;
13849     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
13850     break;
13851   case BO_Shl:
13852   case BO_Shr:
13853     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
13854     break;
13855   case BO_LE:
13856   case BO_LT:
13857   case BO_GE:
13858   case BO_GT:
13859     ConvertHalfVec = true;
13860     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
13861     break;
13862   case BO_EQ:
13863   case BO_NE:
13864     ConvertHalfVec = true;
13865     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
13866     break;
13867   case BO_Cmp:
13868     ConvertHalfVec = true;
13869     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
13870     assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
13871     break;
13872   case BO_And:
13873     checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
13874     LLVM_FALLTHROUGH;
13875   case BO_Xor:
13876   case BO_Or:
13877     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
13878     break;
13879   case BO_LAnd:
13880   case BO_LOr:
13881     ConvertHalfVec = true;
13882     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
13883     break;
13884   case BO_MulAssign:
13885   case BO_DivAssign:
13886     ConvertHalfVec = true;
13887     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
13888                                                Opc == BO_DivAssign);
13889     CompLHSTy = CompResultTy;
13890     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13891       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13892     break;
13893   case BO_RemAssign:
13894     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
13895     CompLHSTy = CompResultTy;
13896     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13897       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13898     break;
13899   case BO_AddAssign:
13900     ConvertHalfVec = true;
13901     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
13902     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13903       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13904     break;
13905   case BO_SubAssign:
13906     ConvertHalfVec = true;
13907     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
13908     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13909       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13910     break;
13911   case BO_ShlAssign:
13912   case BO_ShrAssign:
13913     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
13914     CompLHSTy = CompResultTy;
13915     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13916       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13917     break;
13918   case BO_AndAssign:
13919   case BO_OrAssign: // fallthrough
13920     DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
13921     LLVM_FALLTHROUGH;
13922   case BO_XorAssign:
13923     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
13924     CompLHSTy = CompResultTy;
13925     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13926       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13927     break;
13928   case BO_Comma:
13929     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
13930     if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
13931       VK = RHS.get()->getValueKind();
13932       OK = RHS.get()->getObjectKind();
13933     }
13934     break;
13935   }
13936   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
13937     return ExprError();
13938 
13939   // Some of the binary operations require promoting operands of half vector to
13940   // float vectors and truncating the result back to half vector. For now, we do
13941   // this only when HalfArgsAndReturn is set (that is, when the target is arm or
13942   // arm64).
13943   assert(
13944       (Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) ==
13945                               isVector(LHS.get()->getType(), Context.HalfTy)) &&
13946       "both sides are half vectors or neither sides are");
13947   ConvertHalfVec =
13948       needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get());
13949 
13950   // Check for array bounds violations for both sides of the BinaryOperator
13951   CheckArrayAccess(LHS.get());
13952   CheckArrayAccess(RHS.get());
13953 
13954   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
13955     NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
13956                                                  &Context.Idents.get("object_setClass"),
13957                                                  SourceLocation(), LookupOrdinaryName);
13958     if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
13959       SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc());
13960       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign)
13961           << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(),
13962                                         "object_setClass(")
13963           << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc),
13964                                           ",")
13965           << FixItHint::CreateInsertion(RHSLocEnd, ")");
13966     }
13967     else
13968       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
13969   }
13970   else if (const ObjCIvarRefExpr *OIRE =
13971            dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
13972     DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
13973 
13974   // Opc is not a compound assignment if CompResultTy is null.
13975   if (CompResultTy.isNull()) {
13976     if (ConvertHalfVec)
13977       return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
13978                                  OpLoc, CurFPFeatureOverrides());
13979     return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy,
13980                                   VK, OK, OpLoc, CurFPFeatureOverrides());
13981   }
13982 
13983   // Handle compound assignments.
13984   if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
13985       OK_ObjCProperty) {
13986     VK = VK_LValue;
13987     OK = LHS.get()->getObjectKind();
13988   }
13989 
13990   // The LHS is not converted to the result type for fixed-point compound
13991   // assignment as the common type is computed on demand. Reset the CompLHSTy
13992   // to the LHS type we would have gotten after unary conversions.
13993   if (CompResultTy->isFixedPointType())
13994     CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType();
13995 
13996   if (ConvertHalfVec)
13997     return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
13998                                OpLoc, CurFPFeatureOverrides());
13999 
14000   return CompoundAssignOperator::Create(
14001       Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc,
14002       CurFPFeatureOverrides(), CompLHSTy, CompResultTy);
14003 }
14004 
14005 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
14006 /// operators are mixed in a way that suggests that the programmer forgot that
14007 /// comparison operators have higher precedence. The most typical example of
14008 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
14009 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
14010                                       SourceLocation OpLoc, Expr *LHSExpr,
14011                                       Expr *RHSExpr) {
14012   BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
14013   BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
14014 
14015   // Check that one of the sides is a comparison operator and the other isn't.
14016   bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
14017   bool isRightComp = RHSBO && RHSBO->isComparisonOp();
14018   if (isLeftComp == isRightComp)
14019     return;
14020 
14021   // Bitwise operations are sometimes used as eager logical ops.
14022   // Don't diagnose this.
14023   bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
14024   bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
14025   if (isLeftBitwise || isRightBitwise)
14026     return;
14027 
14028   SourceRange DiagRange = isLeftComp
14029                               ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
14030                               : SourceRange(OpLoc, RHSExpr->getEndLoc());
14031   StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
14032   SourceRange ParensRange =
14033       isLeftComp
14034           ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
14035           : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
14036 
14037   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
14038     << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
14039   SuggestParentheses(Self, OpLoc,
14040     Self.PDiag(diag::note_precedence_silence) << OpStr,
14041     (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
14042   SuggestParentheses(Self, OpLoc,
14043     Self.PDiag(diag::note_precedence_bitwise_first)
14044       << BinaryOperator::getOpcodeStr(Opc),
14045     ParensRange);
14046 }
14047 
14048 /// It accepts a '&&' expr that is inside a '||' one.
14049 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
14050 /// in parentheses.
14051 static void
14052 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
14053                                        BinaryOperator *Bop) {
14054   assert(Bop->getOpcode() == BO_LAnd);
14055   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
14056       << Bop->getSourceRange() << OpLoc;
14057   SuggestParentheses(Self, Bop->getOperatorLoc(),
14058     Self.PDiag(diag::note_precedence_silence)
14059       << Bop->getOpcodeStr(),
14060     Bop->getSourceRange());
14061 }
14062 
14063 /// Returns true if the given expression can be evaluated as a constant
14064 /// 'true'.
14065 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
14066   bool Res;
14067   return !E->isValueDependent() &&
14068          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
14069 }
14070 
14071 /// Returns true if the given expression can be evaluated as a constant
14072 /// 'false'.
14073 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
14074   bool Res;
14075   return !E->isValueDependent() &&
14076          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
14077 }
14078 
14079 /// Look for '&&' in the left hand of a '||' expr.
14080 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
14081                                              Expr *LHSExpr, Expr *RHSExpr) {
14082   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
14083     if (Bop->getOpcode() == BO_LAnd) {
14084       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
14085       if (EvaluatesAsFalse(S, RHSExpr))
14086         return;
14087       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
14088       if (!EvaluatesAsTrue(S, Bop->getLHS()))
14089         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
14090     } else if (Bop->getOpcode() == BO_LOr) {
14091       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
14092         // If it's "a || b && 1 || c" we didn't warn earlier for
14093         // "a || b && 1", but warn now.
14094         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
14095           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
14096       }
14097     }
14098   }
14099 }
14100 
14101 /// Look for '&&' in the right hand of a '||' expr.
14102 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
14103                                              Expr *LHSExpr, Expr *RHSExpr) {
14104   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
14105     if (Bop->getOpcode() == BO_LAnd) {
14106       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
14107       if (EvaluatesAsFalse(S, LHSExpr))
14108         return;
14109       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
14110       if (!EvaluatesAsTrue(S, Bop->getRHS()))
14111         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
14112     }
14113   }
14114 }
14115 
14116 /// Look for bitwise op in the left or right hand of a bitwise op with
14117 /// lower precedence and emit a diagnostic together with a fixit hint that wraps
14118 /// the '&' expression in parentheses.
14119 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
14120                                          SourceLocation OpLoc, Expr *SubExpr) {
14121   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
14122     if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
14123       S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
14124         << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
14125         << Bop->getSourceRange() << OpLoc;
14126       SuggestParentheses(S, Bop->getOperatorLoc(),
14127         S.PDiag(diag::note_precedence_silence)
14128           << Bop->getOpcodeStr(),
14129         Bop->getSourceRange());
14130     }
14131   }
14132 }
14133 
14134 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
14135                                     Expr *SubExpr, StringRef Shift) {
14136   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
14137     if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
14138       StringRef Op = Bop->getOpcodeStr();
14139       S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
14140           << Bop->getSourceRange() << OpLoc << Shift << Op;
14141       SuggestParentheses(S, Bop->getOperatorLoc(),
14142           S.PDiag(diag::note_precedence_silence) << Op,
14143           Bop->getSourceRange());
14144     }
14145   }
14146 }
14147 
14148 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
14149                                  Expr *LHSExpr, Expr *RHSExpr) {
14150   CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
14151   if (!OCE)
14152     return;
14153 
14154   FunctionDecl *FD = OCE->getDirectCallee();
14155   if (!FD || !FD->isOverloadedOperator())
14156     return;
14157 
14158   OverloadedOperatorKind Kind = FD->getOverloadedOperator();
14159   if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
14160     return;
14161 
14162   S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
14163       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
14164       << (Kind == OO_LessLess);
14165   SuggestParentheses(S, OCE->getOperatorLoc(),
14166                      S.PDiag(diag::note_precedence_silence)
14167                          << (Kind == OO_LessLess ? "<<" : ">>"),
14168                      OCE->getSourceRange());
14169   SuggestParentheses(
14170       S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first),
14171       SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc()));
14172 }
14173 
14174 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
14175 /// precedence.
14176 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
14177                                     SourceLocation OpLoc, Expr *LHSExpr,
14178                                     Expr *RHSExpr){
14179   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
14180   if (BinaryOperator::isBitwiseOp(Opc))
14181     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
14182 
14183   // Diagnose "arg1 & arg2 | arg3"
14184   if ((Opc == BO_Or || Opc == BO_Xor) &&
14185       !OpLoc.isMacroID()/* Don't warn in macros. */) {
14186     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
14187     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
14188   }
14189 
14190   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
14191   // We don't warn for 'assert(a || b && "bad")' since this is safe.
14192   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
14193     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
14194     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
14195   }
14196 
14197   if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
14198       || Opc == BO_Shr) {
14199     StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
14200     DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
14201     DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
14202   }
14203 
14204   // Warn on overloaded shift operators and comparisons, such as:
14205   // cout << 5 == 4;
14206   if (BinaryOperator::isComparisonOp(Opc))
14207     DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
14208 }
14209 
14210 // Binary Operators.  'Tok' is the token for the operator.
14211 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
14212                             tok::TokenKind Kind,
14213                             Expr *LHSExpr, Expr *RHSExpr) {
14214   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
14215   assert(LHSExpr && "ActOnBinOp(): missing left expression");
14216   assert(RHSExpr && "ActOnBinOp(): missing right expression");
14217 
14218   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
14219   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
14220 
14221   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
14222 }
14223 
14224 void Sema::LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc,
14225                        UnresolvedSetImpl &Functions) {
14226   OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
14227   if (OverOp != OO_None && OverOp != OO_Equal)
14228     LookupOverloadedOperatorName(OverOp, S, Functions);
14229 
14230   // In C++20 onwards, we may have a second operator to look up.
14231   if (getLangOpts().CPlusPlus20) {
14232     if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp))
14233       LookupOverloadedOperatorName(ExtraOp, S, Functions);
14234   }
14235 }
14236 
14237 /// Build an overloaded binary operator expression in the given scope.
14238 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
14239                                        BinaryOperatorKind Opc,
14240                                        Expr *LHS, Expr *RHS) {
14241   switch (Opc) {
14242   case BO_Assign:
14243   case BO_DivAssign:
14244   case BO_RemAssign:
14245   case BO_SubAssign:
14246   case BO_AndAssign:
14247   case BO_OrAssign:
14248   case BO_XorAssign:
14249     DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
14250     CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
14251     break;
14252   default:
14253     break;
14254   }
14255 
14256   // Find all of the overloaded operators visible from this point.
14257   UnresolvedSet<16> Functions;
14258   S.LookupBinOp(Sc, OpLoc, Opc, Functions);
14259 
14260   // Build the (potentially-overloaded, potentially-dependent)
14261   // binary operation.
14262   return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
14263 }
14264 
14265 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
14266                             BinaryOperatorKind Opc,
14267                             Expr *LHSExpr, Expr *RHSExpr) {
14268   ExprResult LHS, RHS;
14269   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
14270   if (!LHS.isUsable() || !RHS.isUsable())
14271     return ExprError();
14272   LHSExpr = LHS.get();
14273   RHSExpr = RHS.get();
14274 
14275   // We want to end up calling one of checkPseudoObjectAssignment
14276   // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
14277   // both expressions are overloadable or either is type-dependent),
14278   // or CreateBuiltinBinOp (in any other case).  We also want to get
14279   // any placeholder types out of the way.
14280 
14281   // Handle pseudo-objects in the LHS.
14282   if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
14283     // Assignments with a pseudo-object l-value need special analysis.
14284     if (pty->getKind() == BuiltinType::PseudoObject &&
14285         BinaryOperator::isAssignmentOp(Opc))
14286       return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
14287 
14288     // Don't resolve overloads if the other type is overloadable.
14289     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
14290       // We can't actually test that if we still have a placeholder,
14291       // though.  Fortunately, none of the exceptions we see in that
14292       // code below are valid when the LHS is an overload set.  Note
14293       // that an overload set can be dependently-typed, but it never
14294       // instantiates to having an overloadable type.
14295       ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
14296       if (resolvedRHS.isInvalid()) return ExprError();
14297       RHSExpr = resolvedRHS.get();
14298 
14299       if (RHSExpr->isTypeDependent() ||
14300           RHSExpr->getType()->isOverloadableType())
14301         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14302     }
14303 
14304     // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
14305     // template, diagnose the missing 'template' keyword instead of diagnosing
14306     // an invalid use of a bound member function.
14307     //
14308     // Note that "A::x < b" might be valid if 'b' has an overloadable type due
14309     // to C++1z [over.over]/1.4, but we already checked for that case above.
14310     if (Opc == BO_LT && inTemplateInstantiation() &&
14311         (pty->getKind() == BuiltinType::BoundMember ||
14312          pty->getKind() == BuiltinType::Overload)) {
14313       auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
14314       if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
14315           std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) {
14316             return isa<FunctionTemplateDecl>(ND);
14317           })) {
14318         Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
14319                                 : OE->getNameLoc(),
14320              diag::err_template_kw_missing)
14321           << OE->getName().getAsString() << "";
14322         return ExprError();
14323       }
14324     }
14325 
14326     ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
14327     if (LHS.isInvalid()) return ExprError();
14328     LHSExpr = LHS.get();
14329   }
14330 
14331   // Handle pseudo-objects in the RHS.
14332   if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
14333     // An overload in the RHS can potentially be resolved by the type
14334     // being assigned to.
14335     if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
14336       if (getLangOpts().CPlusPlus &&
14337           (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
14338            LHSExpr->getType()->isOverloadableType()))
14339         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14340 
14341       return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
14342     }
14343 
14344     // Don't resolve overloads if the other type is overloadable.
14345     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
14346         LHSExpr->getType()->isOverloadableType())
14347       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14348 
14349     ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
14350     if (!resolvedRHS.isUsable()) return ExprError();
14351     RHSExpr = resolvedRHS.get();
14352   }
14353 
14354   if (getLangOpts().CPlusPlus) {
14355     // If either expression is type-dependent, always build an
14356     // overloaded op.
14357     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
14358       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14359 
14360     // Otherwise, build an overloaded op if either expression has an
14361     // overloadable type.
14362     if (LHSExpr->getType()->isOverloadableType() ||
14363         RHSExpr->getType()->isOverloadableType())
14364       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14365   }
14366 
14367   // Build a built-in binary operation.
14368   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
14369 }
14370 
14371 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
14372   if (T.isNull() || T->isDependentType())
14373     return false;
14374 
14375   if (!T->isPromotableIntegerType())
14376     return true;
14377 
14378   return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
14379 }
14380 
14381 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
14382                                       UnaryOperatorKind Opc,
14383                                       Expr *InputExpr) {
14384   ExprResult Input = InputExpr;
14385   ExprValueKind VK = VK_RValue;
14386   ExprObjectKind OK = OK_Ordinary;
14387   QualType resultType;
14388   bool CanOverflow = false;
14389 
14390   bool ConvertHalfVec = false;
14391   if (getLangOpts().OpenCL) {
14392     QualType Ty = InputExpr->getType();
14393     // The only legal unary operation for atomics is '&'.
14394     if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
14395     // OpenCL special types - image, sampler, pipe, and blocks are to be used
14396     // only with a builtin functions and therefore should be disallowed here.
14397         (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
14398         || Ty->isBlockPointerType())) {
14399       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14400                        << InputExpr->getType()
14401                        << Input.get()->getSourceRange());
14402     }
14403   }
14404 
14405   switch (Opc) {
14406   case UO_PreInc:
14407   case UO_PreDec:
14408   case UO_PostInc:
14409   case UO_PostDec:
14410     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
14411                                                 OpLoc,
14412                                                 Opc == UO_PreInc ||
14413                                                 Opc == UO_PostInc,
14414                                                 Opc == UO_PreInc ||
14415                                                 Opc == UO_PreDec);
14416     CanOverflow = isOverflowingIntegerType(Context, resultType);
14417     break;
14418   case UO_AddrOf:
14419     resultType = CheckAddressOfOperand(Input, OpLoc);
14420     CheckAddressOfNoDeref(InputExpr);
14421     RecordModifiableNonNullParam(*this, InputExpr);
14422     break;
14423   case UO_Deref: {
14424     Input = DefaultFunctionArrayLvalueConversion(Input.get());
14425     if (Input.isInvalid()) return ExprError();
14426     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
14427     break;
14428   }
14429   case UO_Plus:
14430   case UO_Minus:
14431     CanOverflow = Opc == UO_Minus &&
14432                   isOverflowingIntegerType(Context, Input.get()->getType());
14433     Input = UsualUnaryConversions(Input.get());
14434     if (Input.isInvalid()) return ExprError();
14435     // Unary plus and minus require promoting an operand of half vector to a
14436     // float vector and truncating the result back to a half vector. For now, we
14437     // do this only when HalfArgsAndReturns is set (that is, when the target is
14438     // arm or arm64).
14439     ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get());
14440 
14441     // If the operand is a half vector, promote it to a float vector.
14442     if (ConvertHalfVec)
14443       Input = convertVector(Input.get(), Context.FloatTy, *this);
14444     resultType = Input.get()->getType();
14445     if (resultType->isDependentType())
14446       break;
14447     if (resultType->isArithmeticType()) // C99 6.5.3.3p1
14448       break;
14449     else if (resultType->isVectorType() &&
14450              // The z vector extensions don't allow + or - with bool vectors.
14451              (!Context.getLangOpts().ZVector ||
14452               resultType->castAs<VectorType>()->getVectorKind() !=
14453               VectorType::AltiVecBool))
14454       break;
14455     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
14456              Opc == UO_Plus &&
14457              resultType->isPointerType())
14458       break;
14459 
14460     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14461       << resultType << Input.get()->getSourceRange());
14462 
14463   case UO_Not: // bitwise complement
14464     Input = UsualUnaryConversions(Input.get());
14465     if (Input.isInvalid())
14466       return ExprError();
14467     resultType = Input.get()->getType();
14468     if (resultType->isDependentType())
14469       break;
14470     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
14471     if (resultType->isComplexType() || resultType->isComplexIntegerType())
14472       // C99 does not support '~' for complex conjugation.
14473       Diag(OpLoc, diag::ext_integer_complement_complex)
14474           << resultType << Input.get()->getSourceRange();
14475     else if (resultType->hasIntegerRepresentation())
14476       break;
14477     else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
14478       // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
14479       // on vector float types.
14480       QualType T = resultType->castAs<ExtVectorType>()->getElementType();
14481       if (!T->isIntegerType())
14482         return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14483                           << resultType << Input.get()->getSourceRange());
14484     } else {
14485       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14486                        << resultType << Input.get()->getSourceRange());
14487     }
14488     break;
14489 
14490   case UO_LNot: // logical negation
14491     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
14492     Input = DefaultFunctionArrayLvalueConversion(Input.get());
14493     if (Input.isInvalid()) return ExprError();
14494     resultType = Input.get()->getType();
14495 
14496     // Though we still have to promote half FP to float...
14497     if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
14498       Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
14499       resultType = Context.FloatTy;
14500     }
14501 
14502     if (resultType->isDependentType())
14503       break;
14504     if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
14505       // C99 6.5.3.3p1: ok, fallthrough;
14506       if (Context.getLangOpts().CPlusPlus) {
14507         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
14508         // operand contextually converted to bool.
14509         Input = ImpCastExprToType(Input.get(), Context.BoolTy,
14510                                   ScalarTypeToBooleanCastKind(resultType));
14511       } else if (Context.getLangOpts().OpenCL &&
14512                  Context.getLangOpts().OpenCLVersion < 120) {
14513         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
14514         // operate on scalar float types.
14515         if (!resultType->isIntegerType() && !resultType->isPointerType())
14516           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14517                            << resultType << Input.get()->getSourceRange());
14518       }
14519     } else if (resultType->isExtVectorType()) {
14520       if (Context.getLangOpts().OpenCL &&
14521           Context.getLangOpts().OpenCLVersion < 120 &&
14522           !Context.getLangOpts().OpenCLCPlusPlus) {
14523         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
14524         // operate on vector float types.
14525         QualType T = resultType->castAs<ExtVectorType>()->getElementType();
14526         if (!T->isIntegerType())
14527           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14528                            << resultType << Input.get()->getSourceRange());
14529       }
14530       // Vector logical not returns the signed variant of the operand type.
14531       resultType = GetSignedVectorType(resultType);
14532       break;
14533     } else if (Context.getLangOpts().CPlusPlus && resultType->isVectorType()) {
14534       const VectorType *VTy = resultType->castAs<VectorType>();
14535       if (VTy->getVectorKind() != VectorType::GenericVector)
14536         return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14537                          << resultType << Input.get()->getSourceRange());
14538 
14539       // Vector logical not returns the signed variant of the operand type.
14540       resultType = GetSignedVectorType(resultType);
14541       break;
14542     } else {
14543       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14544         << resultType << Input.get()->getSourceRange());
14545     }
14546 
14547     // LNot always has type int. C99 6.5.3.3p5.
14548     // In C++, it's bool. C++ 5.3.1p8
14549     resultType = Context.getLogicalOperationType();
14550     break;
14551   case UO_Real:
14552   case UO_Imag:
14553     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
14554     // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
14555     // complex l-values to ordinary l-values and all other values to r-values.
14556     if (Input.isInvalid()) return ExprError();
14557     if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
14558       if (Input.get()->getValueKind() != VK_RValue &&
14559           Input.get()->getObjectKind() == OK_Ordinary)
14560         VK = Input.get()->getValueKind();
14561     } else if (!getLangOpts().CPlusPlus) {
14562       // In C, a volatile scalar is read by __imag. In C++, it is not.
14563       Input = DefaultLvalueConversion(Input.get());
14564     }
14565     break;
14566   case UO_Extension:
14567     resultType = Input.get()->getType();
14568     VK = Input.get()->getValueKind();
14569     OK = Input.get()->getObjectKind();
14570     break;
14571   case UO_Coawait:
14572     // It's unnecessary to represent the pass-through operator co_await in the
14573     // AST; just return the input expression instead.
14574     assert(!Input.get()->getType()->isDependentType() &&
14575                    "the co_await expression must be non-dependant before "
14576                    "building operator co_await");
14577     return Input;
14578   }
14579   if (resultType.isNull() || Input.isInvalid())
14580     return ExprError();
14581 
14582   // Check for array bounds violations in the operand of the UnaryOperator,
14583   // except for the '*' and '&' operators that have to be handled specially
14584   // by CheckArrayAccess (as there are special cases like &array[arraysize]
14585   // that are explicitly defined as valid by the standard).
14586   if (Opc != UO_AddrOf && Opc != UO_Deref)
14587     CheckArrayAccess(Input.get());
14588 
14589   auto *UO =
14590       UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK,
14591                             OpLoc, CanOverflow, CurFPFeatureOverrides());
14592 
14593   if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) &&
14594       !isa<ArrayType>(UO->getType().getDesugaredType(Context)))
14595     ExprEvalContexts.back().PossibleDerefs.insert(UO);
14596 
14597   // Convert the result back to a half vector.
14598   if (ConvertHalfVec)
14599     return convertVector(UO, Context.HalfTy, *this);
14600   return UO;
14601 }
14602 
14603 /// Determine whether the given expression is a qualified member
14604 /// access expression, of a form that could be turned into a pointer to member
14605 /// with the address-of operator.
14606 bool Sema::isQualifiedMemberAccess(Expr *E) {
14607   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
14608     if (!DRE->getQualifier())
14609       return false;
14610 
14611     ValueDecl *VD = DRE->getDecl();
14612     if (!VD->isCXXClassMember())
14613       return false;
14614 
14615     if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
14616       return true;
14617     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
14618       return Method->isInstance();
14619 
14620     return false;
14621   }
14622 
14623   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
14624     if (!ULE->getQualifier())
14625       return false;
14626 
14627     for (NamedDecl *D : ULE->decls()) {
14628       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
14629         if (Method->isInstance())
14630           return true;
14631       } else {
14632         // Overload set does not contain methods.
14633         break;
14634       }
14635     }
14636 
14637     return false;
14638   }
14639 
14640   return false;
14641 }
14642 
14643 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
14644                               UnaryOperatorKind Opc, Expr *Input) {
14645   // First things first: handle placeholders so that the
14646   // overloaded-operator check considers the right type.
14647   if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
14648     // Increment and decrement of pseudo-object references.
14649     if (pty->getKind() == BuiltinType::PseudoObject &&
14650         UnaryOperator::isIncrementDecrementOp(Opc))
14651       return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
14652 
14653     // extension is always a builtin operator.
14654     if (Opc == UO_Extension)
14655       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
14656 
14657     // & gets special logic for several kinds of placeholder.
14658     // The builtin code knows what to do.
14659     if (Opc == UO_AddrOf &&
14660         (pty->getKind() == BuiltinType::Overload ||
14661          pty->getKind() == BuiltinType::UnknownAny ||
14662          pty->getKind() == BuiltinType::BoundMember))
14663       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
14664 
14665     // Anything else needs to be handled now.
14666     ExprResult Result = CheckPlaceholderExpr(Input);
14667     if (Result.isInvalid()) return ExprError();
14668     Input = Result.get();
14669   }
14670 
14671   if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
14672       UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
14673       !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
14674     // Find all of the overloaded operators visible from this point.
14675     UnresolvedSet<16> Functions;
14676     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
14677     if (S && OverOp != OO_None)
14678       LookupOverloadedOperatorName(OverOp, S, Functions);
14679 
14680     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
14681   }
14682 
14683   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
14684 }
14685 
14686 // Unary Operators.  'Tok' is the token for the operator.
14687 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
14688                               tok::TokenKind Op, Expr *Input) {
14689   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
14690 }
14691 
14692 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
14693 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
14694                                 LabelDecl *TheDecl) {
14695   TheDecl->markUsed(Context);
14696   // Create the AST node.  The address of a label always has type 'void*'.
14697   return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
14698                                      Context.getPointerType(Context.VoidTy));
14699 }
14700 
14701 void Sema::ActOnStartStmtExpr() {
14702   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
14703 }
14704 
14705 void Sema::ActOnStmtExprError() {
14706   // Note that function is also called by TreeTransform when leaving a
14707   // StmtExpr scope without rebuilding anything.
14708 
14709   DiscardCleanupsInEvaluationContext();
14710   PopExpressionEvaluationContext();
14711 }
14712 
14713 ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt,
14714                                SourceLocation RPLoc) {
14715   return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S));
14716 }
14717 
14718 ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
14719                                SourceLocation RPLoc, unsigned TemplateDepth) {
14720   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
14721   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
14722 
14723   if (hasAnyUnrecoverableErrorsInThisFunction())
14724     DiscardCleanupsInEvaluationContext();
14725   assert(!Cleanup.exprNeedsCleanups() &&
14726          "cleanups within StmtExpr not correctly bound!");
14727   PopExpressionEvaluationContext();
14728 
14729   // FIXME: there are a variety of strange constraints to enforce here, for
14730   // example, it is not possible to goto into a stmt expression apparently.
14731   // More semantic analysis is needed.
14732 
14733   // If there are sub-stmts in the compound stmt, take the type of the last one
14734   // as the type of the stmtexpr.
14735   QualType Ty = Context.VoidTy;
14736   bool StmtExprMayBindToTemp = false;
14737   if (!Compound->body_empty()) {
14738     // For GCC compatibility we get the last Stmt excluding trailing NullStmts.
14739     if (const auto *LastStmt =
14740             dyn_cast<ValueStmt>(Compound->getStmtExprResult())) {
14741       if (const Expr *Value = LastStmt->getExprStmt()) {
14742         StmtExprMayBindToTemp = true;
14743         Ty = Value->getType();
14744       }
14745     }
14746   }
14747 
14748   // FIXME: Check that expression type is complete/non-abstract; statement
14749   // expressions are not lvalues.
14750   Expr *ResStmtExpr =
14751       new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth);
14752   if (StmtExprMayBindToTemp)
14753     return MaybeBindToTemporary(ResStmtExpr);
14754   return ResStmtExpr;
14755 }
14756 
14757 ExprResult Sema::ActOnStmtExprResult(ExprResult ER) {
14758   if (ER.isInvalid())
14759     return ExprError();
14760 
14761   // Do function/array conversion on the last expression, but not
14762   // lvalue-to-rvalue.  However, initialize an unqualified type.
14763   ER = DefaultFunctionArrayConversion(ER.get());
14764   if (ER.isInvalid())
14765     return ExprError();
14766   Expr *E = ER.get();
14767 
14768   if (E->isTypeDependent())
14769     return E;
14770 
14771   // In ARC, if the final expression ends in a consume, splice
14772   // the consume out and bind it later.  In the alternate case
14773   // (when dealing with a retainable type), the result
14774   // initialization will create a produce.  In both cases the
14775   // result will be +1, and we'll need to balance that out with
14776   // a bind.
14777   auto *Cast = dyn_cast<ImplicitCastExpr>(E);
14778   if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
14779     return Cast->getSubExpr();
14780 
14781   // FIXME: Provide a better location for the initialization.
14782   return PerformCopyInitialization(
14783       InitializedEntity::InitializeStmtExprResult(
14784           E->getBeginLoc(), E->getType().getUnqualifiedType()),
14785       SourceLocation(), E);
14786 }
14787 
14788 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
14789                                       TypeSourceInfo *TInfo,
14790                                       ArrayRef<OffsetOfComponent> Components,
14791                                       SourceLocation RParenLoc) {
14792   QualType ArgTy = TInfo->getType();
14793   bool Dependent = ArgTy->isDependentType();
14794   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
14795 
14796   // We must have at least one component that refers to the type, and the first
14797   // one is known to be a field designator.  Verify that the ArgTy represents
14798   // a struct/union/class.
14799   if (!Dependent && !ArgTy->isRecordType())
14800     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
14801                        << ArgTy << TypeRange);
14802 
14803   // Type must be complete per C99 7.17p3 because a declaring a variable
14804   // with an incomplete type would be ill-formed.
14805   if (!Dependent
14806       && RequireCompleteType(BuiltinLoc, ArgTy,
14807                              diag::err_offsetof_incomplete_type, TypeRange))
14808     return ExprError();
14809 
14810   bool DidWarnAboutNonPOD = false;
14811   QualType CurrentType = ArgTy;
14812   SmallVector<OffsetOfNode, 4> Comps;
14813   SmallVector<Expr*, 4> Exprs;
14814   for (const OffsetOfComponent &OC : Components) {
14815     if (OC.isBrackets) {
14816       // Offset of an array sub-field.  TODO: Should we allow vector elements?
14817       if (!CurrentType->isDependentType()) {
14818         const ArrayType *AT = Context.getAsArrayType(CurrentType);
14819         if(!AT)
14820           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
14821                            << CurrentType);
14822         CurrentType = AT->getElementType();
14823       } else
14824         CurrentType = Context.DependentTy;
14825 
14826       ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
14827       if (IdxRval.isInvalid())
14828         return ExprError();
14829       Expr *Idx = IdxRval.get();
14830 
14831       // The expression must be an integral expression.
14832       // FIXME: An integral constant expression?
14833       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
14834           !Idx->getType()->isIntegerType())
14835         return ExprError(
14836             Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer)
14837             << Idx->getSourceRange());
14838 
14839       // Record this array index.
14840       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
14841       Exprs.push_back(Idx);
14842       continue;
14843     }
14844 
14845     // Offset of a field.
14846     if (CurrentType->isDependentType()) {
14847       // We have the offset of a field, but we can't look into the dependent
14848       // type. Just record the identifier of the field.
14849       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
14850       CurrentType = Context.DependentTy;
14851       continue;
14852     }
14853 
14854     // We need to have a complete type to look into.
14855     if (RequireCompleteType(OC.LocStart, CurrentType,
14856                             diag::err_offsetof_incomplete_type))
14857       return ExprError();
14858 
14859     // Look for the designated field.
14860     const RecordType *RC = CurrentType->getAs<RecordType>();
14861     if (!RC)
14862       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
14863                        << CurrentType);
14864     RecordDecl *RD = RC->getDecl();
14865 
14866     // C++ [lib.support.types]p5:
14867     //   The macro offsetof accepts a restricted set of type arguments in this
14868     //   International Standard. type shall be a POD structure or a POD union
14869     //   (clause 9).
14870     // C++11 [support.types]p4:
14871     //   If type is not a standard-layout class (Clause 9), the results are
14872     //   undefined.
14873     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
14874       bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
14875       unsigned DiagID =
14876         LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
14877                             : diag::ext_offsetof_non_pod_type;
14878 
14879       if (!IsSafe && !DidWarnAboutNonPOD &&
14880           DiagRuntimeBehavior(BuiltinLoc, nullptr,
14881                               PDiag(DiagID)
14882                               << SourceRange(Components[0].LocStart, OC.LocEnd)
14883                               << CurrentType))
14884         DidWarnAboutNonPOD = true;
14885     }
14886 
14887     // Look for the field.
14888     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
14889     LookupQualifiedName(R, RD);
14890     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
14891     IndirectFieldDecl *IndirectMemberDecl = nullptr;
14892     if (!MemberDecl) {
14893       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
14894         MemberDecl = IndirectMemberDecl->getAnonField();
14895     }
14896 
14897     if (!MemberDecl)
14898       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
14899                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
14900                                                               OC.LocEnd));
14901 
14902     // C99 7.17p3:
14903     //   (If the specified member is a bit-field, the behavior is undefined.)
14904     //
14905     // We diagnose this as an error.
14906     if (MemberDecl->isBitField()) {
14907       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
14908         << MemberDecl->getDeclName()
14909         << SourceRange(BuiltinLoc, RParenLoc);
14910       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
14911       return ExprError();
14912     }
14913 
14914     RecordDecl *Parent = MemberDecl->getParent();
14915     if (IndirectMemberDecl)
14916       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
14917 
14918     // If the member was found in a base class, introduce OffsetOfNodes for
14919     // the base class indirections.
14920     CXXBasePaths Paths;
14921     if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
14922                       Paths)) {
14923       if (Paths.getDetectedVirtual()) {
14924         Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
14925           << MemberDecl->getDeclName()
14926           << SourceRange(BuiltinLoc, RParenLoc);
14927         return ExprError();
14928       }
14929 
14930       CXXBasePath &Path = Paths.front();
14931       for (const CXXBasePathElement &B : Path)
14932         Comps.push_back(OffsetOfNode(B.Base));
14933     }
14934 
14935     if (IndirectMemberDecl) {
14936       for (auto *FI : IndirectMemberDecl->chain()) {
14937         assert(isa<FieldDecl>(FI));
14938         Comps.push_back(OffsetOfNode(OC.LocStart,
14939                                      cast<FieldDecl>(FI), OC.LocEnd));
14940       }
14941     } else
14942       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
14943 
14944     CurrentType = MemberDecl->getType().getNonReferenceType();
14945   }
14946 
14947   return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
14948                               Comps, Exprs, RParenLoc);
14949 }
14950 
14951 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
14952                                       SourceLocation BuiltinLoc,
14953                                       SourceLocation TypeLoc,
14954                                       ParsedType ParsedArgTy,
14955                                       ArrayRef<OffsetOfComponent> Components,
14956                                       SourceLocation RParenLoc) {
14957 
14958   TypeSourceInfo *ArgTInfo;
14959   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
14960   if (ArgTy.isNull())
14961     return ExprError();
14962 
14963   if (!ArgTInfo)
14964     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
14965 
14966   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
14967 }
14968 
14969 
14970 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
14971                                  Expr *CondExpr,
14972                                  Expr *LHSExpr, Expr *RHSExpr,
14973                                  SourceLocation RPLoc) {
14974   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
14975 
14976   ExprValueKind VK = VK_RValue;
14977   ExprObjectKind OK = OK_Ordinary;
14978   QualType resType;
14979   bool CondIsTrue = false;
14980   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
14981     resType = Context.DependentTy;
14982   } else {
14983     // The conditional expression is required to be a constant expression.
14984     llvm::APSInt condEval(32);
14985     ExprResult CondICE
14986       = VerifyIntegerConstantExpression(CondExpr, &condEval,
14987           diag::err_typecheck_choose_expr_requires_constant, false);
14988     if (CondICE.isInvalid())
14989       return ExprError();
14990     CondExpr = CondICE.get();
14991     CondIsTrue = condEval.getZExtValue();
14992 
14993     // If the condition is > zero, then the AST type is the same as the LHSExpr.
14994     Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
14995 
14996     resType = ActiveExpr->getType();
14997     VK = ActiveExpr->getValueKind();
14998     OK = ActiveExpr->getObjectKind();
14999   }
15000 
15001   return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
15002                                   resType, VK, OK, RPLoc, CondIsTrue);
15003 }
15004 
15005 //===----------------------------------------------------------------------===//
15006 // Clang Extensions.
15007 //===----------------------------------------------------------------------===//
15008 
15009 /// ActOnBlockStart - This callback is invoked when a block literal is started.
15010 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
15011   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
15012 
15013   if (LangOpts.CPlusPlus) {
15014     MangleNumberingContext *MCtx;
15015     Decl *ManglingContextDecl;
15016     std::tie(MCtx, ManglingContextDecl) =
15017         getCurrentMangleNumberContext(Block->getDeclContext());
15018     if (MCtx) {
15019       unsigned ManglingNumber = MCtx->getManglingNumber(Block);
15020       Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
15021     }
15022   }
15023 
15024   PushBlockScope(CurScope, Block);
15025   CurContext->addDecl(Block);
15026   if (CurScope)
15027     PushDeclContext(CurScope, Block);
15028   else
15029     CurContext = Block;
15030 
15031   getCurBlock()->HasImplicitReturnType = true;
15032 
15033   // Enter a new evaluation context to insulate the block from any
15034   // cleanups from the enclosing full-expression.
15035   PushExpressionEvaluationContext(
15036       ExpressionEvaluationContext::PotentiallyEvaluated);
15037 }
15038 
15039 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
15040                                Scope *CurScope) {
15041   assert(ParamInfo.getIdentifier() == nullptr &&
15042          "block-id should have no identifier!");
15043   assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteralContext);
15044   BlockScopeInfo *CurBlock = getCurBlock();
15045 
15046   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
15047   QualType T = Sig->getType();
15048 
15049   // FIXME: We should allow unexpanded parameter packs here, but that would,
15050   // in turn, make the block expression contain unexpanded parameter packs.
15051   if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
15052     // Drop the parameters.
15053     FunctionProtoType::ExtProtoInfo EPI;
15054     EPI.HasTrailingReturn = false;
15055     EPI.TypeQuals.addConst();
15056     T = Context.getFunctionType(Context.DependentTy, None, EPI);
15057     Sig = Context.getTrivialTypeSourceInfo(T);
15058   }
15059 
15060   // GetTypeForDeclarator always produces a function type for a block
15061   // literal signature.  Furthermore, it is always a FunctionProtoType
15062   // unless the function was written with a typedef.
15063   assert(T->isFunctionType() &&
15064          "GetTypeForDeclarator made a non-function block signature");
15065 
15066   // Look for an explicit signature in that function type.
15067   FunctionProtoTypeLoc ExplicitSignature;
15068 
15069   if ((ExplicitSignature = Sig->getTypeLoc()
15070                                .getAsAdjusted<FunctionProtoTypeLoc>())) {
15071 
15072     // Check whether that explicit signature was synthesized by
15073     // GetTypeForDeclarator.  If so, don't save that as part of the
15074     // written signature.
15075     if (ExplicitSignature.getLocalRangeBegin() ==
15076         ExplicitSignature.getLocalRangeEnd()) {
15077       // This would be much cheaper if we stored TypeLocs instead of
15078       // TypeSourceInfos.
15079       TypeLoc Result = ExplicitSignature.getReturnLoc();
15080       unsigned Size = Result.getFullDataSize();
15081       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
15082       Sig->getTypeLoc().initializeFullCopy(Result, Size);
15083 
15084       ExplicitSignature = FunctionProtoTypeLoc();
15085     }
15086   }
15087 
15088   CurBlock->TheDecl->setSignatureAsWritten(Sig);
15089   CurBlock->FunctionType = T;
15090 
15091   const FunctionType *Fn = T->getAs<FunctionType>();
15092   QualType RetTy = Fn->getReturnType();
15093   bool isVariadic =
15094     (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
15095 
15096   CurBlock->TheDecl->setIsVariadic(isVariadic);
15097 
15098   // Context.DependentTy is used as a placeholder for a missing block
15099   // return type.  TODO:  what should we do with declarators like:
15100   //   ^ * { ... }
15101   // If the answer is "apply template argument deduction"....
15102   if (RetTy != Context.DependentTy) {
15103     CurBlock->ReturnType = RetTy;
15104     CurBlock->TheDecl->setBlockMissingReturnType(false);
15105     CurBlock->HasImplicitReturnType = false;
15106   }
15107 
15108   // Push block parameters from the declarator if we had them.
15109   SmallVector<ParmVarDecl*, 8> Params;
15110   if (ExplicitSignature) {
15111     for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
15112       ParmVarDecl *Param = ExplicitSignature.getParam(I);
15113       if (Param->getIdentifier() == nullptr && !Param->isImplicit() &&
15114           !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) {
15115         // Diagnose this as an extension in C17 and earlier.
15116         if (!getLangOpts().C2x)
15117           Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x);
15118       }
15119       Params.push_back(Param);
15120     }
15121 
15122   // Fake up parameter variables if we have a typedef, like
15123   //   ^ fntype { ... }
15124   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
15125     for (const auto &I : Fn->param_types()) {
15126       ParmVarDecl *Param = BuildParmVarDeclForTypedef(
15127           CurBlock->TheDecl, ParamInfo.getBeginLoc(), I);
15128       Params.push_back(Param);
15129     }
15130   }
15131 
15132   // Set the parameters on the block decl.
15133   if (!Params.empty()) {
15134     CurBlock->TheDecl->setParams(Params);
15135     CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
15136                              /*CheckParameterNames=*/false);
15137   }
15138 
15139   // Finally we can process decl attributes.
15140   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
15141 
15142   // Put the parameter variables in scope.
15143   for (auto AI : CurBlock->TheDecl->parameters()) {
15144     AI->setOwningFunction(CurBlock->TheDecl);
15145 
15146     // If this has an identifier, add it to the scope stack.
15147     if (AI->getIdentifier()) {
15148       CheckShadow(CurBlock->TheScope, AI);
15149 
15150       PushOnScopeChains(AI, CurBlock->TheScope);
15151     }
15152   }
15153 }
15154 
15155 /// ActOnBlockError - If there is an error parsing a block, this callback
15156 /// is invoked to pop the information about the block from the action impl.
15157 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
15158   // Leave the expression-evaluation context.
15159   DiscardCleanupsInEvaluationContext();
15160   PopExpressionEvaluationContext();
15161 
15162   // Pop off CurBlock, handle nested blocks.
15163   PopDeclContext();
15164   PopFunctionScopeInfo();
15165 }
15166 
15167 /// ActOnBlockStmtExpr - This is called when the body of a block statement
15168 /// literal was successfully completed.  ^(int x){...}
15169 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
15170                                     Stmt *Body, Scope *CurScope) {
15171   // If blocks are disabled, emit an error.
15172   if (!LangOpts.Blocks)
15173     Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
15174 
15175   // Leave the expression-evaluation context.
15176   if (hasAnyUnrecoverableErrorsInThisFunction())
15177     DiscardCleanupsInEvaluationContext();
15178   assert(!Cleanup.exprNeedsCleanups() &&
15179          "cleanups within block not correctly bound!");
15180   PopExpressionEvaluationContext();
15181 
15182   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
15183   BlockDecl *BD = BSI->TheDecl;
15184 
15185   if (BSI->HasImplicitReturnType)
15186     deduceClosureReturnType(*BSI);
15187 
15188   QualType RetTy = Context.VoidTy;
15189   if (!BSI->ReturnType.isNull())
15190     RetTy = BSI->ReturnType;
15191 
15192   bool NoReturn = BD->hasAttr<NoReturnAttr>();
15193   QualType BlockTy;
15194 
15195   // If the user wrote a function type in some form, try to use that.
15196   if (!BSI->FunctionType.isNull()) {
15197     const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>();
15198 
15199     FunctionType::ExtInfo Ext = FTy->getExtInfo();
15200     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
15201 
15202     // Turn protoless block types into nullary block types.
15203     if (isa<FunctionNoProtoType>(FTy)) {
15204       FunctionProtoType::ExtProtoInfo EPI;
15205       EPI.ExtInfo = Ext;
15206       BlockTy = Context.getFunctionType(RetTy, None, EPI);
15207 
15208     // Otherwise, if we don't need to change anything about the function type,
15209     // preserve its sugar structure.
15210     } else if (FTy->getReturnType() == RetTy &&
15211                (!NoReturn || FTy->getNoReturnAttr())) {
15212       BlockTy = BSI->FunctionType;
15213 
15214     // Otherwise, make the minimal modifications to the function type.
15215     } else {
15216       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
15217       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
15218       EPI.TypeQuals = Qualifiers();
15219       EPI.ExtInfo = Ext;
15220       BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
15221     }
15222 
15223   // If we don't have a function type, just build one from nothing.
15224   } else {
15225     FunctionProtoType::ExtProtoInfo EPI;
15226     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
15227     BlockTy = Context.getFunctionType(RetTy, None, EPI);
15228   }
15229 
15230   DiagnoseUnusedParameters(BD->parameters());
15231   BlockTy = Context.getBlockPointerType(BlockTy);
15232 
15233   // If needed, diagnose invalid gotos and switches in the block.
15234   if (getCurFunction()->NeedsScopeChecking() &&
15235       !PP.isCodeCompletionEnabled())
15236     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
15237 
15238   BD->setBody(cast<CompoundStmt>(Body));
15239 
15240   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
15241     DiagnoseUnguardedAvailabilityViolations(BD);
15242 
15243   // Try to apply the named return value optimization. We have to check again
15244   // if we can do this, though, because blocks keep return statements around
15245   // to deduce an implicit return type.
15246   if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
15247       !BD->isDependentContext())
15248     computeNRVO(Body, BSI);
15249 
15250   if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() ||
15251       RetTy.hasNonTrivialToPrimitiveCopyCUnion())
15252     checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn,
15253                           NTCUK_Destruct|NTCUK_Copy);
15254 
15255   PopDeclContext();
15256 
15257   // Pop the block scope now but keep it alive to the end of this function.
15258   AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
15259   PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy);
15260 
15261   // Set the captured variables on the block.
15262   SmallVector<BlockDecl::Capture, 4> Captures;
15263   for (Capture &Cap : BSI->Captures) {
15264     if (Cap.isInvalid() || Cap.isThisCapture())
15265       continue;
15266 
15267     VarDecl *Var = Cap.getVariable();
15268     Expr *CopyExpr = nullptr;
15269     if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) {
15270       if (const RecordType *Record =
15271               Cap.getCaptureType()->getAs<RecordType>()) {
15272         // The capture logic needs the destructor, so make sure we mark it.
15273         // Usually this is unnecessary because most local variables have
15274         // their destructors marked at declaration time, but parameters are
15275         // an exception because it's technically only the call site that
15276         // actually requires the destructor.
15277         if (isa<ParmVarDecl>(Var))
15278           FinalizeVarWithDestructor(Var, Record);
15279 
15280         // Enter a separate potentially-evaluated context while building block
15281         // initializers to isolate their cleanups from those of the block
15282         // itself.
15283         // FIXME: Is this appropriate even when the block itself occurs in an
15284         // unevaluated operand?
15285         EnterExpressionEvaluationContext EvalContext(
15286             *this, ExpressionEvaluationContext::PotentiallyEvaluated);
15287 
15288         SourceLocation Loc = Cap.getLocation();
15289 
15290         ExprResult Result = BuildDeclarationNameExpr(
15291             CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
15292 
15293         // According to the blocks spec, the capture of a variable from
15294         // the stack requires a const copy constructor.  This is not true
15295         // of the copy/move done to move a __block variable to the heap.
15296         if (!Result.isInvalid() &&
15297             !Result.get()->getType().isConstQualified()) {
15298           Result = ImpCastExprToType(Result.get(),
15299                                      Result.get()->getType().withConst(),
15300                                      CK_NoOp, VK_LValue);
15301         }
15302 
15303         if (!Result.isInvalid()) {
15304           Result = PerformCopyInitialization(
15305               InitializedEntity::InitializeBlock(Var->getLocation(),
15306                                                  Cap.getCaptureType(), false),
15307               Loc, Result.get());
15308         }
15309 
15310         // Build a full-expression copy expression if initialization
15311         // succeeded and used a non-trivial constructor.  Recover from
15312         // errors by pretending that the copy isn't necessary.
15313         if (!Result.isInvalid() &&
15314             !cast<CXXConstructExpr>(Result.get())->getConstructor()
15315                 ->isTrivial()) {
15316           Result = MaybeCreateExprWithCleanups(Result);
15317           CopyExpr = Result.get();
15318         }
15319       }
15320     }
15321 
15322     BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(),
15323                               CopyExpr);
15324     Captures.push_back(NewCap);
15325   }
15326   BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
15327 
15328   BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy);
15329 
15330   // If the block isn't obviously global, i.e. it captures anything at
15331   // all, then we need to do a few things in the surrounding context:
15332   if (Result->getBlockDecl()->hasCaptures()) {
15333     // First, this expression has a new cleanup object.
15334     ExprCleanupObjects.push_back(Result->getBlockDecl());
15335     Cleanup.setExprNeedsCleanups(true);
15336 
15337     // It also gets a branch-protected scope if any of the captured
15338     // variables needs destruction.
15339     for (const auto &CI : Result->getBlockDecl()->captures()) {
15340       const VarDecl *var = CI.getVariable();
15341       if (var->getType().isDestructedType() != QualType::DK_none) {
15342         setFunctionHasBranchProtectedScope();
15343         break;
15344       }
15345     }
15346   }
15347 
15348   if (getCurFunction())
15349     getCurFunction()->addBlock(BD);
15350 
15351   return Result;
15352 }
15353 
15354 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
15355                             SourceLocation RPLoc) {
15356   TypeSourceInfo *TInfo;
15357   GetTypeFromParser(Ty, &TInfo);
15358   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
15359 }
15360 
15361 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
15362                                 Expr *E, TypeSourceInfo *TInfo,
15363                                 SourceLocation RPLoc) {
15364   Expr *OrigExpr = E;
15365   bool IsMS = false;
15366 
15367   // CUDA device code does not support varargs.
15368   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
15369     if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
15370       CUDAFunctionTarget T = IdentifyCUDATarget(F);
15371       if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
15372         return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device));
15373     }
15374   }
15375 
15376   // NVPTX does not support va_arg expression.
15377   if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
15378       Context.getTargetInfo().getTriple().isNVPTX())
15379     targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device);
15380 
15381   // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
15382   // as Microsoft ABI on an actual Microsoft platform, where
15383   // __builtin_ms_va_list and __builtin_va_list are the same.)
15384   if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
15385       Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
15386     QualType MSVaListType = Context.getBuiltinMSVaListType();
15387     if (Context.hasSameType(MSVaListType, E->getType())) {
15388       if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
15389         return ExprError();
15390       IsMS = true;
15391     }
15392   }
15393 
15394   // Get the va_list type
15395   QualType VaListType = Context.getBuiltinVaListType();
15396   if (!IsMS) {
15397     if (VaListType->isArrayType()) {
15398       // Deal with implicit array decay; for example, on x86-64,
15399       // va_list is an array, but it's supposed to decay to
15400       // a pointer for va_arg.
15401       VaListType = Context.getArrayDecayedType(VaListType);
15402       // Make sure the input expression also decays appropriately.
15403       ExprResult Result = UsualUnaryConversions(E);
15404       if (Result.isInvalid())
15405         return ExprError();
15406       E = Result.get();
15407     } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
15408       // If va_list is a record type and we are compiling in C++ mode,
15409       // check the argument using reference binding.
15410       InitializedEntity Entity = InitializedEntity::InitializeParameter(
15411           Context, Context.getLValueReferenceType(VaListType), false);
15412       ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
15413       if (Init.isInvalid())
15414         return ExprError();
15415       E = Init.getAs<Expr>();
15416     } else {
15417       // Otherwise, the va_list argument must be an l-value because
15418       // it is modified by va_arg.
15419       if (!E->isTypeDependent() &&
15420           CheckForModifiableLvalue(E, BuiltinLoc, *this))
15421         return ExprError();
15422     }
15423   }
15424 
15425   if (!IsMS && !E->isTypeDependent() &&
15426       !Context.hasSameType(VaListType, E->getType()))
15427     return ExprError(
15428         Diag(E->getBeginLoc(),
15429              diag::err_first_argument_to_va_arg_not_of_type_va_list)
15430         << OrigExpr->getType() << E->getSourceRange());
15431 
15432   if (!TInfo->getType()->isDependentType()) {
15433     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
15434                             diag::err_second_parameter_to_va_arg_incomplete,
15435                             TInfo->getTypeLoc()))
15436       return ExprError();
15437 
15438     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
15439                                TInfo->getType(),
15440                                diag::err_second_parameter_to_va_arg_abstract,
15441                                TInfo->getTypeLoc()))
15442       return ExprError();
15443 
15444     if (!TInfo->getType().isPODType(Context)) {
15445       Diag(TInfo->getTypeLoc().getBeginLoc(),
15446            TInfo->getType()->isObjCLifetimeType()
15447              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
15448              : diag::warn_second_parameter_to_va_arg_not_pod)
15449         << TInfo->getType()
15450         << TInfo->getTypeLoc().getSourceRange();
15451     }
15452 
15453     // Check for va_arg where arguments of the given type will be promoted
15454     // (i.e. this va_arg is guaranteed to have undefined behavior).
15455     QualType PromoteType;
15456     if (TInfo->getType()->isPromotableIntegerType()) {
15457       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
15458       if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
15459         PromoteType = QualType();
15460     }
15461     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
15462       PromoteType = Context.DoubleTy;
15463     if (!PromoteType.isNull())
15464       DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
15465                   PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
15466                           << TInfo->getType()
15467                           << PromoteType
15468                           << TInfo->getTypeLoc().getSourceRange());
15469   }
15470 
15471   QualType T = TInfo->getType().getNonLValueExprType(Context);
15472   return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
15473 }
15474 
15475 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
15476   // The type of __null will be int or long, depending on the size of
15477   // pointers on the target.
15478   QualType Ty;
15479   unsigned pw = Context.getTargetInfo().getPointerWidth(0);
15480   if (pw == Context.getTargetInfo().getIntWidth())
15481     Ty = Context.IntTy;
15482   else if (pw == Context.getTargetInfo().getLongWidth())
15483     Ty = Context.LongTy;
15484   else if (pw == Context.getTargetInfo().getLongLongWidth())
15485     Ty = Context.LongLongTy;
15486   else {
15487     llvm_unreachable("I don't know size of pointer!");
15488   }
15489 
15490   return new (Context) GNUNullExpr(Ty, TokenLoc);
15491 }
15492 
15493 ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind,
15494                                     SourceLocation BuiltinLoc,
15495                                     SourceLocation RPLoc) {
15496   return BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, CurContext);
15497 }
15498 
15499 ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind,
15500                                     SourceLocation BuiltinLoc,
15501                                     SourceLocation RPLoc,
15502                                     DeclContext *ParentContext) {
15503   return new (Context)
15504       SourceLocExpr(Context, Kind, BuiltinLoc, RPLoc, ParentContext);
15505 }
15506 
15507 bool Sema::CheckConversionToObjCLiteral(QualType DstType, Expr *&Exp,
15508                                         bool Diagnose) {
15509   if (!getLangOpts().ObjC)
15510     return false;
15511 
15512   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
15513   if (!PT)
15514     return false;
15515   const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
15516 
15517   // Ignore any parens, implicit casts (should only be
15518   // array-to-pointer decays), and not-so-opaque values.  The last is
15519   // important for making this trigger for property assignments.
15520   Expr *SrcExpr = Exp->IgnoreParenImpCasts();
15521   if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
15522     if (OV->getSourceExpr())
15523       SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
15524 
15525   if (auto *SL = dyn_cast<StringLiteral>(SrcExpr)) {
15526     if (!PT->isObjCIdType() &&
15527         !(ID && ID->getIdentifier()->isStr("NSString")))
15528       return false;
15529     if (!SL->isAscii())
15530       return false;
15531 
15532     if (Diagnose) {
15533       Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix)
15534           << /*string*/0 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@");
15535       Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get();
15536     }
15537     return true;
15538   }
15539 
15540   if ((isa<IntegerLiteral>(SrcExpr) || isa<CharacterLiteral>(SrcExpr) ||
15541       isa<FloatingLiteral>(SrcExpr) || isa<ObjCBoolLiteralExpr>(SrcExpr) ||
15542       isa<CXXBoolLiteralExpr>(SrcExpr)) &&
15543       !SrcExpr->isNullPointerConstant(
15544           getASTContext(), Expr::NPC_NeverValueDependent)) {
15545     if (!ID || !ID->getIdentifier()->isStr("NSNumber"))
15546       return false;
15547     if (Diagnose) {
15548       Diag(SrcExpr->getBeginLoc(), diag::err_missing_atsign_prefix)
15549           << /*number*/1
15550           << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(), "@");
15551       Expr *NumLit =
15552           BuildObjCNumericLiteral(SrcExpr->getBeginLoc(), SrcExpr).get();
15553       if (NumLit)
15554         Exp = NumLit;
15555     }
15556     return true;
15557   }
15558 
15559   return false;
15560 }
15561 
15562 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
15563                                               const Expr *SrcExpr) {
15564   if (!DstType->isFunctionPointerType() ||
15565       !SrcExpr->getType()->isFunctionType())
15566     return false;
15567 
15568   auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
15569   if (!DRE)
15570     return false;
15571 
15572   auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
15573   if (!FD)
15574     return false;
15575 
15576   return !S.checkAddressOfFunctionIsAvailable(FD,
15577                                               /*Complain=*/true,
15578                                               SrcExpr->getBeginLoc());
15579 }
15580 
15581 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
15582                                     SourceLocation Loc,
15583                                     QualType DstType, QualType SrcType,
15584                                     Expr *SrcExpr, AssignmentAction Action,
15585                                     bool *Complained) {
15586   if (Complained)
15587     *Complained = false;
15588 
15589   // Decode the result (notice that AST's are still created for extensions).
15590   bool CheckInferredResultType = false;
15591   bool isInvalid = false;
15592   unsigned DiagKind = 0;
15593   ConversionFixItGenerator ConvHints;
15594   bool MayHaveConvFixit = false;
15595   bool MayHaveFunctionDiff = false;
15596   const ObjCInterfaceDecl *IFace = nullptr;
15597   const ObjCProtocolDecl *PDecl = nullptr;
15598 
15599   switch (ConvTy) {
15600   case Compatible:
15601       DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
15602       return false;
15603 
15604   case PointerToInt:
15605     if (getLangOpts().CPlusPlus) {
15606       DiagKind = diag::err_typecheck_convert_pointer_int;
15607       isInvalid = true;
15608     } else {
15609       DiagKind = diag::ext_typecheck_convert_pointer_int;
15610     }
15611     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15612     MayHaveConvFixit = true;
15613     break;
15614   case IntToPointer:
15615     if (getLangOpts().CPlusPlus) {
15616       DiagKind = diag::err_typecheck_convert_int_pointer;
15617       isInvalid = true;
15618     } else {
15619       DiagKind = diag::ext_typecheck_convert_int_pointer;
15620     }
15621     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15622     MayHaveConvFixit = true;
15623     break;
15624   case IncompatibleFunctionPointer:
15625     if (getLangOpts().CPlusPlus) {
15626       DiagKind = diag::err_typecheck_convert_incompatible_function_pointer;
15627       isInvalid = true;
15628     } else {
15629       DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
15630     }
15631     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15632     MayHaveConvFixit = true;
15633     break;
15634   case IncompatiblePointer:
15635     if (Action == AA_Passing_CFAudited) {
15636       DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
15637     } else if (getLangOpts().CPlusPlus) {
15638       DiagKind = diag::err_typecheck_convert_incompatible_pointer;
15639       isInvalid = true;
15640     } else {
15641       DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
15642     }
15643     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
15644       SrcType->isObjCObjectPointerType();
15645     if (!CheckInferredResultType) {
15646       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15647     } else if (CheckInferredResultType) {
15648       SrcType = SrcType.getUnqualifiedType();
15649       DstType = DstType.getUnqualifiedType();
15650     }
15651     MayHaveConvFixit = true;
15652     break;
15653   case IncompatiblePointerSign:
15654     if (getLangOpts().CPlusPlus) {
15655       DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign;
15656       isInvalid = true;
15657     } else {
15658       DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
15659     }
15660     break;
15661   case FunctionVoidPointer:
15662     if (getLangOpts().CPlusPlus) {
15663       DiagKind = diag::err_typecheck_convert_pointer_void_func;
15664       isInvalid = true;
15665     } else {
15666       DiagKind = diag::ext_typecheck_convert_pointer_void_func;
15667     }
15668     break;
15669   case IncompatiblePointerDiscardsQualifiers: {
15670     // Perform array-to-pointer decay if necessary.
15671     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
15672 
15673     isInvalid = true;
15674 
15675     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
15676     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
15677     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
15678       DiagKind = diag::err_typecheck_incompatible_address_space;
15679       break;
15680 
15681     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
15682       DiagKind = diag::err_typecheck_incompatible_ownership;
15683       break;
15684     }
15685 
15686     llvm_unreachable("unknown error case for discarding qualifiers!");
15687     // fallthrough
15688   }
15689   case CompatiblePointerDiscardsQualifiers:
15690     // If the qualifiers lost were because we were applying the
15691     // (deprecated) C++ conversion from a string literal to a char*
15692     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
15693     // Ideally, this check would be performed in
15694     // checkPointerTypesForAssignment. However, that would require a
15695     // bit of refactoring (so that the second argument is an
15696     // expression, rather than a type), which should be done as part
15697     // of a larger effort to fix checkPointerTypesForAssignment for
15698     // C++ semantics.
15699     if (getLangOpts().CPlusPlus &&
15700         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
15701       return false;
15702     if (getLangOpts().CPlusPlus) {
15703       DiagKind =  diag::err_typecheck_convert_discards_qualifiers;
15704       isInvalid = true;
15705     } else {
15706       DiagKind =  diag::ext_typecheck_convert_discards_qualifiers;
15707     }
15708 
15709     break;
15710   case IncompatibleNestedPointerQualifiers:
15711     if (getLangOpts().CPlusPlus) {
15712       isInvalid = true;
15713       DiagKind = diag::err_nested_pointer_qualifier_mismatch;
15714     } else {
15715       DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
15716     }
15717     break;
15718   case IncompatibleNestedPointerAddressSpaceMismatch:
15719     DiagKind = diag::err_typecheck_incompatible_nested_address_space;
15720     isInvalid = true;
15721     break;
15722   case IntToBlockPointer:
15723     DiagKind = diag::err_int_to_block_pointer;
15724     isInvalid = true;
15725     break;
15726   case IncompatibleBlockPointer:
15727     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
15728     isInvalid = true;
15729     break;
15730   case IncompatibleObjCQualifiedId: {
15731     if (SrcType->isObjCQualifiedIdType()) {
15732       const ObjCObjectPointerType *srcOPT =
15733                 SrcType->castAs<ObjCObjectPointerType>();
15734       for (auto *srcProto : srcOPT->quals()) {
15735         PDecl = srcProto;
15736         break;
15737       }
15738       if (const ObjCInterfaceType *IFaceT =
15739             DstType->castAs<ObjCObjectPointerType>()->getInterfaceType())
15740         IFace = IFaceT->getDecl();
15741     }
15742     else if (DstType->isObjCQualifiedIdType()) {
15743       const ObjCObjectPointerType *dstOPT =
15744         DstType->castAs<ObjCObjectPointerType>();
15745       for (auto *dstProto : dstOPT->quals()) {
15746         PDecl = dstProto;
15747         break;
15748       }
15749       if (const ObjCInterfaceType *IFaceT =
15750             SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType())
15751         IFace = IFaceT->getDecl();
15752     }
15753     if (getLangOpts().CPlusPlus) {
15754       DiagKind = diag::err_incompatible_qualified_id;
15755       isInvalid = true;
15756     } else {
15757       DiagKind = diag::warn_incompatible_qualified_id;
15758     }
15759     break;
15760   }
15761   case IncompatibleVectors:
15762     if (getLangOpts().CPlusPlus) {
15763       DiagKind = diag::err_incompatible_vectors;
15764       isInvalid = true;
15765     } else {
15766       DiagKind = diag::warn_incompatible_vectors;
15767     }
15768     break;
15769   case IncompatibleObjCWeakRef:
15770     DiagKind = diag::err_arc_weak_unavailable_assign;
15771     isInvalid = true;
15772     break;
15773   case Incompatible:
15774     if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
15775       if (Complained)
15776         *Complained = true;
15777       return true;
15778     }
15779 
15780     DiagKind = diag::err_typecheck_convert_incompatible;
15781     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15782     MayHaveConvFixit = true;
15783     isInvalid = true;
15784     MayHaveFunctionDiff = true;
15785     break;
15786   }
15787 
15788   QualType FirstType, SecondType;
15789   switch (Action) {
15790   case AA_Assigning:
15791   case AA_Initializing:
15792     // The destination type comes first.
15793     FirstType = DstType;
15794     SecondType = SrcType;
15795     break;
15796 
15797   case AA_Returning:
15798   case AA_Passing:
15799   case AA_Passing_CFAudited:
15800   case AA_Converting:
15801   case AA_Sending:
15802   case AA_Casting:
15803     // The source type comes first.
15804     FirstType = SrcType;
15805     SecondType = DstType;
15806     break;
15807   }
15808 
15809   PartialDiagnostic FDiag = PDiag(DiagKind);
15810   if (Action == AA_Passing_CFAudited)
15811     FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
15812   else
15813     FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
15814 
15815   // If we can fix the conversion, suggest the FixIts.
15816   if (!ConvHints.isNull()) {
15817     for (FixItHint &H : ConvHints.Hints)
15818       FDiag << H;
15819   }
15820 
15821   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
15822 
15823   if (MayHaveFunctionDiff)
15824     HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
15825 
15826   Diag(Loc, FDiag);
15827   if ((DiagKind == diag::warn_incompatible_qualified_id ||
15828        DiagKind == diag::err_incompatible_qualified_id) &&
15829       PDecl && IFace && !IFace->hasDefinition())
15830     Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
15831         << IFace << PDecl;
15832 
15833   if (SecondType == Context.OverloadTy)
15834     NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
15835                               FirstType, /*TakingAddress=*/true);
15836 
15837   if (CheckInferredResultType)
15838     EmitRelatedResultTypeNote(SrcExpr);
15839 
15840   if (Action == AA_Returning && ConvTy == IncompatiblePointer)
15841     EmitRelatedResultTypeNoteForReturn(DstType);
15842 
15843   if (Complained)
15844     *Complained = true;
15845   return isInvalid;
15846 }
15847 
15848 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
15849                                                  llvm::APSInt *Result) {
15850   class SimpleICEDiagnoser : public VerifyICEDiagnoser {
15851   public:
15852     SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc,
15853                                              QualType T) override {
15854       return S.Diag(Loc, diag::err_ice_not_integral)
15855              << T << S.LangOpts.CPlusPlus;
15856     }
15857     SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
15858       return S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus;
15859     }
15860   } Diagnoser;
15861 
15862   return VerifyIntegerConstantExpression(E, Result, Diagnoser);
15863 }
15864 
15865 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
15866                                                  llvm::APSInt *Result,
15867                                                  unsigned DiagID,
15868                                                  bool AllowFold) {
15869   class IDDiagnoser : public VerifyICEDiagnoser {
15870     unsigned DiagID;
15871 
15872   public:
15873     IDDiagnoser(unsigned DiagID)
15874       : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
15875 
15876     SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
15877       return S.Diag(Loc, DiagID);
15878     }
15879   } Diagnoser(DiagID);
15880 
15881   return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
15882 }
15883 
15884 Sema::SemaDiagnosticBuilder
15885 Sema::VerifyICEDiagnoser::diagnoseNotICEType(Sema &S, SourceLocation Loc,
15886                                              QualType T) {
15887   return diagnoseNotICE(S, Loc);
15888 }
15889 
15890 Sema::SemaDiagnosticBuilder
15891 Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc) {
15892   return S.Diag(Loc, diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus;
15893 }
15894 
15895 ExprResult
15896 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
15897                                       VerifyICEDiagnoser &Diagnoser,
15898                                       bool AllowFold) {
15899   SourceLocation DiagLoc = E->getBeginLoc();
15900 
15901   if (getLangOpts().CPlusPlus11) {
15902     // C++11 [expr.const]p5:
15903     //   If an expression of literal class type is used in a context where an
15904     //   integral constant expression is required, then that class type shall
15905     //   have a single non-explicit conversion function to an integral or
15906     //   unscoped enumeration type
15907     ExprResult Converted;
15908     class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
15909       VerifyICEDiagnoser &BaseDiagnoser;
15910     public:
15911       CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser)
15912           : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false,
15913                                 BaseDiagnoser.Suppress, true),
15914             BaseDiagnoser(BaseDiagnoser) {}
15915 
15916       SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
15917                                            QualType T) override {
15918         return BaseDiagnoser.diagnoseNotICEType(S, Loc, T);
15919       }
15920 
15921       SemaDiagnosticBuilder diagnoseIncomplete(
15922           Sema &S, SourceLocation Loc, QualType T) override {
15923         return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
15924       }
15925 
15926       SemaDiagnosticBuilder diagnoseExplicitConv(
15927           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
15928         return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
15929       }
15930 
15931       SemaDiagnosticBuilder noteExplicitConv(
15932           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
15933         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
15934                  << ConvTy->isEnumeralType() << ConvTy;
15935       }
15936 
15937       SemaDiagnosticBuilder diagnoseAmbiguous(
15938           Sema &S, SourceLocation Loc, QualType T) override {
15939         return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
15940       }
15941 
15942       SemaDiagnosticBuilder noteAmbiguous(
15943           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
15944         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
15945                  << ConvTy->isEnumeralType() << ConvTy;
15946       }
15947 
15948       SemaDiagnosticBuilder diagnoseConversion(
15949           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
15950         llvm_unreachable("conversion functions are permitted");
15951       }
15952     } ConvertDiagnoser(Diagnoser);
15953 
15954     Converted = PerformContextualImplicitConversion(DiagLoc, E,
15955                                                     ConvertDiagnoser);
15956     if (Converted.isInvalid())
15957       return Converted;
15958     E = Converted.get();
15959     if (!E->getType()->isIntegralOrUnscopedEnumerationType())
15960       return ExprError();
15961   } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
15962     // An ICE must be of integral or unscoped enumeration type.
15963     if (!Diagnoser.Suppress)
15964       Diagnoser.diagnoseNotICEType(*this, DiagLoc, E->getType())
15965           << E->getSourceRange();
15966     return ExprError();
15967   }
15968 
15969   ExprResult RValueExpr = DefaultLvalueConversion(E);
15970   if (RValueExpr.isInvalid())
15971     return ExprError();
15972 
15973   E = RValueExpr.get();
15974 
15975   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
15976   // in the non-ICE case.
15977   if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
15978     if (Result)
15979       *Result = E->EvaluateKnownConstIntCheckOverflow(Context);
15980     if (!isa<ConstantExpr>(E))
15981       E = ConstantExpr::Create(Context, E);
15982     return E;
15983   }
15984 
15985   Expr::EvalResult EvalResult;
15986   SmallVector<PartialDiagnosticAt, 8> Notes;
15987   EvalResult.Diag = &Notes;
15988 
15989   // Try to evaluate the expression, and produce diagnostics explaining why it's
15990   // not a constant expression as a side-effect.
15991   bool Folded =
15992       E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) &&
15993       EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
15994 
15995   if (!isa<ConstantExpr>(E))
15996     E = ConstantExpr::Create(Context, E, EvalResult.Val);
15997 
15998   // In C++11, we can rely on diagnostics being produced for any expression
15999   // which is not a constant expression. If no diagnostics were produced, then
16000   // this is a constant expression.
16001   if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
16002     if (Result)
16003       *Result = EvalResult.Val.getInt();
16004     return E;
16005   }
16006 
16007   // If our only note is the usual "invalid subexpression" note, just point
16008   // the caret at its location rather than producing an essentially
16009   // redundant note.
16010   if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
16011         diag::note_invalid_subexpr_in_const_expr) {
16012     DiagLoc = Notes[0].first;
16013     Notes.clear();
16014   }
16015 
16016   if (!Folded || !AllowFold) {
16017     if (!Diagnoser.Suppress) {
16018       Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange();
16019       for (const PartialDiagnosticAt &Note : Notes)
16020         Diag(Note.first, Note.second);
16021     }
16022 
16023     return ExprError();
16024   }
16025 
16026   Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange();
16027   for (const PartialDiagnosticAt &Note : Notes)
16028     Diag(Note.first, Note.second);
16029 
16030   if (Result)
16031     *Result = EvalResult.Val.getInt();
16032   return E;
16033 }
16034 
16035 namespace {
16036   // Handle the case where we conclude a expression which we speculatively
16037   // considered to be unevaluated is actually evaluated.
16038   class TransformToPE : public TreeTransform<TransformToPE> {
16039     typedef TreeTransform<TransformToPE> BaseTransform;
16040 
16041   public:
16042     TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
16043 
16044     // Make sure we redo semantic analysis
16045     bool AlwaysRebuild() { return true; }
16046     bool ReplacingOriginal() { return true; }
16047 
16048     // We need to special-case DeclRefExprs referring to FieldDecls which
16049     // are not part of a member pointer formation; normal TreeTransforming
16050     // doesn't catch this case because of the way we represent them in the AST.
16051     // FIXME: This is a bit ugly; is it really the best way to handle this
16052     // case?
16053     //
16054     // Error on DeclRefExprs referring to FieldDecls.
16055     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
16056       if (isa<FieldDecl>(E->getDecl()) &&
16057           !SemaRef.isUnevaluatedContext())
16058         return SemaRef.Diag(E->getLocation(),
16059                             diag::err_invalid_non_static_member_use)
16060             << E->getDecl() << E->getSourceRange();
16061 
16062       return BaseTransform::TransformDeclRefExpr(E);
16063     }
16064 
16065     // Exception: filter out member pointer formation
16066     ExprResult TransformUnaryOperator(UnaryOperator *E) {
16067       if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
16068         return E;
16069 
16070       return BaseTransform::TransformUnaryOperator(E);
16071     }
16072 
16073     // The body of a lambda-expression is in a separate expression evaluation
16074     // context so never needs to be transformed.
16075     // FIXME: Ideally we wouldn't transform the closure type either, and would
16076     // just recreate the capture expressions and lambda expression.
16077     StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
16078       return SkipLambdaBody(E, Body);
16079     }
16080   };
16081 }
16082 
16083 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
16084   assert(isUnevaluatedContext() &&
16085          "Should only transform unevaluated expressions");
16086   ExprEvalContexts.back().Context =
16087       ExprEvalContexts[ExprEvalContexts.size()-2].Context;
16088   if (isUnevaluatedContext())
16089     return E;
16090   return TransformToPE(*this).TransformExpr(E);
16091 }
16092 
16093 void
16094 Sema::PushExpressionEvaluationContext(
16095     ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
16096     ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
16097   ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
16098                                 LambdaContextDecl, ExprContext);
16099   Cleanup.reset();
16100   if (!MaybeODRUseExprs.empty())
16101     std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
16102 }
16103 
16104 void
16105 Sema::PushExpressionEvaluationContext(
16106     ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
16107     ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
16108   Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
16109   PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);
16110 }
16111 
16112 namespace {
16113 
16114 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
16115   PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
16116   if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) {
16117     if (E->getOpcode() == UO_Deref)
16118       return CheckPossibleDeref(S, E->getSubExpr());
16119   } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) {
16120     return CheckPossibleDeref(S, E->getBase());
16121   } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) {
16122     return CheckPossibleDeref(S, E->getBase());
16123   } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) {
16124     QualType Inner;
16125     QualType Ty = E->getType();
16126     if (const auto *Ptr = Ty->getAs<PointerType>())
16127       Inner = Ptr->getPointeeType();
16128     else if (const auto *Arr = S.Context.getAsArrayType(Ty))
16129       Inner = Arr->getElementType();
16130     else
16131       return nullptr;
16132 
16133     if (Inner->hasAttr(attr::NoDeref))
16134       return E;
16135   }
16136   return nullptr;
16137 }
16138 
16139 } // namespace
16140 
16141 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) {
16142   for (const Expr *E : Rec.PossibleDerefs) {
16143     const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E);
16144     if (DeclRef) {
16145       const ValueDecl *Decl = DeclRef->getDecl();
16146       Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type)
16147           << Decl->getName() << E->getSourceRange();
16148       Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName();
16149     } else {
16150       Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl)
16151           << E->getSourceRange();
16152     }
16153   }
16154   Rec.PossibleDerefs.clear();
16155 }
16156 
16157 /// Check whether E, which is either a discarded-value expression or an
16158 /// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue,
16159 /// and if so, remove it from the list of volatile-qualified assignments that
16160 /// we are going to warn are deprecated.
16161 void Sema::CheckUnusedVolatileAssignment(Expr *E) {
16162   if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20)
16163     return;
16164 
16165   // Note: ignoring parens here is not justified by the standard rules, but
16166   // ignoring parentheses seems like a more reasonable approach, and this only
16167   // drives a deprecation warning so doesn't affect conformance.
16168   if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) {
16169     if (BO->getOpcode() == BO_Assign) {
16170       auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs;
16171       LHSs.erase(std::remove(LHSs.begin(), LHSs.end(), BO->getLHS()),
16172                  LHSs.end());
16173     }
16174   }
16175 }
16176 
16177 ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) {
16178   if (!E.isUsable() || !Decl || !Decl->isConsteval() || isConstantEvaluated() ||
16179       RebuildingImmediateInvocation)
16180     return E;
16181 
16182   /// Opportunistically remove the callee from ReferencesToConsteval if we can.
16183   /// It's OK if this fails; we'll also remove this in
16184   /// HandleImmediateInvocations, but catching it here allows us to avoid
16185   /// walking the AST looking for it in simple cases.
16186   if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit()))
16187     if (auto *DeclRef =
16188             dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()))
16189       ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef);
16190 
16191   E = MaybeCreateExprWithCleanups(E);
16192 
16193   ConstantExpr *Res = ConstantExpr::Create(
16194       getASTContext(), E.get(),
16195       ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(),
16196                                    getASTContext()),
16197       /*IsImmediateInvocation*/ true);
16198   ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0);
16199   return Res;
16200 }
16201 
16202 static void EvaluateAndDiagnoseImmediateInvocation(
16203     Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) {
16204   llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
16205   Expr::EvalResult Eval;
16206   Eval.Diag = &Notes;
16207   ConstantExpr *CE = Candidate.getPointer();
16208   bool Result = CE->EvaluateAsConstantExpr(Eval, Expr::EvaluateForCodeGen,
16209                                            SemaRef.getASTContext(), true);
16210   if (!Result || !Notes.empty()) {
16211     Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit();
16212     if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr))
16213       InnerExpr = FunctionalCast->getSubExpr();
16214     FunctionDecl *FD = nullptr;
16215     if (auto *Call = dyn_cast<CallExpr>(InnerExpr))
16216       FD = cast<FunctionDecl>(Call->getCalleeDecl());
16217     else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr))
16218       FD = Call->getConstructor();
16219     else
16220       llvm_unreachable("unhandled decl kind");
16221     assert(FD->isConsteval());
16222     SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call) << FD;
16223     for (auto &Note : Notes)
16224       SemaRef.Diag(Note.first, Note.second);
16225     return;
16226   }
16227   CE->MoveIntoResult(Eval.Val, SemaRef.getASTContext());
16228 }
16229 
16230 static void RemoveNestedImmediateInvocation(
16231     Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec,
16232     SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) {
16233   struct ComplexRemove : TreeTransform<ComplexRemove> {
16234     using Base = TreeTransform<ComplexRemove>;
16235     llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
16236     SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet;
16237     SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator
16238         CurrentII;
16239     ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR,
16240                   SmallVector<Sema::ImmediateInvocationCandidate, 4> &II,
16241                   SmallVector<Sema::ImmediateInvocationCandidate,
16242                               4>::reverse_iterator Current)
16243         : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {}
16244     void RemoveImmediateInvocation(ConstantExpr* E) {
16245       auto It = std::find_if(CurrentII, IISet.rend(),
16246                              [E](Sema::ImmediateInvocationCandidate Elem) {
16247                                return Elem.getPointer() == E;
16248                              });
16249       assert(It != IISet.rend() &&
16250              "ConstantExpr marked IsImmediateInvocation should "
16251              "be present");
16252       It->setInt(1); // Mark as deleted
16253     }
16254     ExprResult TransformConstantExpr(ConstantExpr *E) {
16255       if (!E->isImmediateInvocation())
16256         return Base::TransformConstantExpr(E);
16257       RemoveImmediateInvocation(E);
16258       return Base::TransformExpr(E->getSubExpr());
16259     }
16260     /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so
16261     /// we need to remove its DeclRefExpr from the DRSet.
16262     ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
16263       DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit()));
16264       return Base::TransformCXXOperatorCallExpr(E);
16265     }
16266     /// Base::TransformInitializer skip ConstantExpr so we need to visit them
16267     /// here.
16268     ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) {
16269       if (!Init)
16270         return Init;
16271       /// ConstantExpr are the first layer of implicit node to be removed so if
16272       /// Init isn't a ConstantExpr, no ConstantExpr will be skipped.
16273       if (auto *CE = dyn_cast<ConstantExpr>(Init))
16274         if (CE->isImmediateInvocation())
16275           RemoveImmediateInvocation(CE);
16276       return Base::TransformInitializer(Init, NotCopyInit);
16277     }
16278     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
16279       DRSet.erase(E);
16280       return E;
16281     }
16282     bool AlwaysRebuild() { return false; }
16283     bool ReplacingOriginal() { return true; }
16284     bool AllowSkippingCXXConstructExpr() {
16285       bool Res = AllowSkippingFirstCXXConstructExpr;
16286       AllowSkippingFirstCXXConstructExpr = true;
16287       return Res;
16288     }
16289     bool AllowSkippingFirstCXXConstructExpr = true;
16290   } Transformer(SemaRef, Rec.ReferenceToConsteval,
16291                 Rec.ImmediateInvocationCandidates, It);
16292 
16293   /// CXXConstructExpr with a single argument are getting skipped by
16294   /// TreeTransform in some situtation because they could be implicit. This
16295   /// can only occur for the top-level CXXConstructExpr because it is used
16296   /// nowhere in the expression being transformed therefore will not be rebuilt.
16297   /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from
16298   /// skipping the first CXXConstructExpr.
16299   if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit()))
16300     Transformer.AllowSkippingFirstCXXConstructExpr = false;
16301 
16302   ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr());
16303   assert(Res.isUsable());
16304   Res = SemaRef.MaybeCreateExprWithCleanups(Res);
16305   It->getPointer()->setSubExpr(Res.get());
16306 }
16307 
16308 static void
16309 HandleImmediateInvocations(Sema &SemaRef,
16310                            Sema::ExpressionEvaluationContextRecord &Rec) {
16311   if ((Rec.ImmediateInvocationCandidates.size() == 0 &&
16312        Rec.ReferenceToConsteval.size() == 0) ||
16313       SemaRef.RebuildingImmediateInvocation)
16314     return;
16315 
16316   /// When we have more then 1 ImmediateInvocationCandidates we need to check
16317   /// for nested ImmediateInvocationCandidates. when we have only 1 we only
16318   /// need to remove ReferenceToConsteval in the immediate invocation.
16319   if (Rec.ImmediateInvocationCandidates.size() > 1) {
16320 
16321     /// Prevent sema calls during the tree transform from adding pointers that
16322     /// are already in the sets.
16323     llvm::SaveAndRestore<bool> DisableIITracking(
16324         SemaRef.RebuildingImmediateInvocation, true);
16325 
16326     /// Prevent diagnostic during tree transfrom as they are duplicates
16327     Sema::TentativeAnalysisScope DisableDiag(SemaRef);
16328 
16329     for (auto It = Rec.ImmediateInvocationCandidates.rbegin();
16330          It != Rec.ImmediateInvocationCandidates.rend(); It++)
16331       if (!It->getInt())
16332         RemoveNestedImmediateInvocation(SemaRef, Rec, It);
16333   } else if (Rec.ImmediateInvocationCandidates.size() == 1 &&
16334              Rec.ReferenceToConsteval.size()) {
16335     struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> {
16336       llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
16337       SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {}
16338       bool VisitDeclRefExpr(DeclRefExpr *E) {
16339         DRSet.erase(E);
16340         return DRSet.size();
16341       }
16342     } Visitor(Rec.ReferenceToConsteval);
16343     Visitor.TraverseStmt(
16344         Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr());
16345   }
16346   for (auto CE : Rec.ImmediateInvocationCandidates)
16347     if (!CE.getInt())
16348       EvaluateAndDiagnoseImmediateInvocation(SemaRef, CE);
16349   for (auto DR : Rec.ReferenceToConsteval) {
16350     auto *FD = cast<FunctionDecl>(DR->getDecl());
16351     SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address)
16352         << FD;
16353     SemaRef.Diag(FD->getLocation(), diag::note_declared_at);
16354   }
16355 }
16356 
16357 void Sema::PopExpressionEvaluationContext() {
16358   ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
16359   unsigned NumTypos = Rec.NumTypos;
16360 
16361   if (!Rec.Lambdas.empty()) {
16362     using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind;
16363     if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || Rec.isUnevaluated() ||
16364         (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17)) {
16365       unsigned D;
16366       if (Rec.isUnevaluated()) {
16367         // C++11 [expr.prim.lambda]p2:
16368         //   A lambda-expression shall not appear in an unevaluated operand
16369         //   (Clause 5).
16370         D = diag::err_lambda_unevaluated_operand;
16371       } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
16372         // C++1y [expr.const]p2:
16373         //   A conditional-expression e is a core constant expression unless the
16374         //   evaluation of e, following the rules of the abstract machine, would
16375         //   evaluate [...] a lambda-expression.
16376         D = diag::err_lambda_in_constant_expression;
16377       } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
16378         // C++17 [expr.prim.lamda]p2:
16379         // A lambda-expression shall not appear [...] in a template-argument.
16380         D = diag::err_lambda_in_invalid_context;
16381       } else
16382         llvm_unreachable("Couldn't infer lambda error message.");
16383 
16384       for (const auto *L : Rec.Lambdas)
16385         Diag(L->getBeginLoc(), D);
16386     }
16387   }
16388 
16389   WarnOnPendingNoDerefs(Rec);
16390   HandleImmediateInvocations(*this, Rec);
16391 
16392   // Warn on any volatile-qualified simple-assignments that are not discarded-
16393   // value expressions nor unevaluated operands (those cases get removed from
16394   // this list by CheckUnusedVolatileAssignment).
16395   for (auto *BO : Rec.VolatileAssignmentLHSs)
16396     Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile)
16397         << BO->getType();
16398 
16399   // When are coming out of an unevaluated context, clear out any
16400   // temporaries that we may have created as part of the evaluation of
16401   // the expression in that context: they aren't relevant because they
16402   // will never be constructed.
16403   if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
16404     ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
16405                              ExprCleanupObjects.end());
16406     Cleanup = Rec.ParentCleanup;
16407     CleanupVarDeclMarking();
16408     std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
16409   // Otherwise, merge the contexts together.
16410   } else {
16411     Cleanup.mergeFrom(Rec.ParentCleanup);
16412     MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
16413                             Rec.SavedMaybeODRUseExprs.end());
16414   }
16415 
16416   // Pop the current expression evaluation context off the stack.
16417   ExprEvalContexts.pop_back();
16418 
16419   // The global expression evaluation context record is never popped.
16420   ExprEvalContexts.back().NumTypos += NumTypos;
16421 }
16422 
16423 void Sema::DiscardCleanupsInEvaluationContext() {
16424   ExprCleanupObjects.erase(
16425          ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
16426          ExprCleanupObjects.end());
16427   Cleanup.reset();
16428   MaybeODRUseExprs.clear();
16429 }
16430 
16431 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
16432   ExprResult Result = CheckPlaceholderExpr(E);
16433   if (Result.isInvalid())
16434     return ExprError();
16435   E = Result.get();
16436   if (!E->getType()->isVariablyModifiedType())
16437     return E;
16438   return TransformToPotentiallyEvaluated(E);
16439 }
16440 
16441 /// Are we in a context that is potentially constant evaluated per C++20
16442 /// [expr.const]p12?
16443 static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) {
16444   /// C++2a [expr.const]p12:
16445   //   An expression or conversion is potentially constant evaluated if it is
16446   switch (SemaRef.ExprEvalContexts.back().Context) {
16447     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
16448       // -- a manifestly constant-evaluated expression,
16449     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
16450     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
16451     case Sema::ExpressionEvaluationContext::DiscardedStatement:
16452       // -- a potentially-evaluated expression,
16453     case Sema::ExpressionEvaluationContext::UnevaluatedList:
16454       // -- an immediate subexpression of a braced-init-list,
16455 
16456       // -- [FIXME] an expression of the form & cast-expression that occurs
16457       //    within a templated entity
16458       // -- a subexpression of one of the above that is not a subexpression of
16459       // a nested unevaluated operand.
16460       return true;
16461 
16462     case Sema::ExpressionEvaluationContext::Unevaluated:
16463     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
16464       // Expressions in this context are never evaluated.
16465       return false;
16466   }
16467   llvm_unreachable("Invalid context");
16468 }
16469 
16470 /// Return true if this function has a calling convention that requires mangling
16471 /// in the size of the parameter pack.
16472 static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) {
16473   // These manglings don't do anything on non-Windows or non-x86 platforms, so
16474   // we don't need parameter type sizes.
16475   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
16476   if (!TT.isOSWindows() || !TT.isX86())
16477     return false;
16478 
16479   // If this is C++ and this isn't an extern "C" function, parameters do not
16480   // need to be complete. In this case, C++ mangling will apply, which doesn't
16481   // use the size of the parameters.
16482   if (S.getLangOpts().CPlusPlus && !FD->isExternC())
16483     return false;
16484 
16485   // Stdcall, fastcall, and vectorcall need this special treatment.
16486   CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
16487   switch (CC) {
16488   case CC_X86StdCall:
16489   case CC_X86FastCall:
16490   case CC_X86VectorCall:
16491     return true;
16492   default:
16493     break;
16494   }
16495   return false;
16496 }
16497 
16498 /// Require that all of the parameter types of function be complete. Normally,
16499 /// parameter types are only required to be complete when a function is called
16500 /// or defined, but to mangle functions with certain calling conventions, the
16501 /// mangler needs to know the size of the parameter list. In this situation,
16502 /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles
16503 /// the function as _foo@0, i.e. zero bytes of parameters, which will usually
16504 /// result in a linker error. Clang doesn't implement this behavior, and instead
16505 /// attempts to error at compile time.
16506 static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD,
16507                                                   SourceLocation Loc) {
16508   class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser {
16509     FunctionDecl *FD;
16510     ParmVarDecl *Param;
16511 
16512   public:
16513     ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param)
16514         : FD(FD), Param(Param) {}
16515 
16516     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
16517       CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
16518       StringRef CCName;
16519       switch (CC) {
16520       case CC_X86StdCall:
16521         CCName = "stdcall";
16522         break;
16523       case CC_X86FastCall:
16524         CCName = "fastcall";
16525         break;
16526       case CC_X86VectorCall:
16527         CCName = "vectorcall";
16528         break;
16529       default:
16530         llvm_unreachable("CC does not need mangling");
16531       }
16532 
16533       S.Diag(Loc, diag::err_cconv_incomplete_param_type)
16534           << Param->getDeclName() << FD->getDeclName() << CCName;
16535     }
16536   };
16537 
16538   for (ParmVarDecl *Param : FD->parameters()) {
16539     ParamIncompleteTypeDiagnoser Diagnoser(FD, Param);
16540     S.RequireCompleteType(Loc, Param->getType(), Diagnoser);
16541   }
16542 }
16543 
16544 namespace {
16545 enum class OdrUseContext {
16546   /// Declarations in this context are not odr-used.
16547   None,
16548   /// Declarations in this context are formally odr-used, but this is a
16549   /// dependent context.
16550   Dependent,
16551   /// Declarations in this context are odr-used but not actually used (yet).
16552   FormallyOdrUsed,
16553   /// Declarations in this context are used.
16554   Used
16555 };
16556 }
16557 
16558 /// Are we within a context in which references to resolved functions or to
16559 /// variables result in odr-use?
16560 static OdrUseContext isOdrUseContext(Sema &SemaRef) {
16561   OdrUseContext Result;
16562 
16563   switch (SemaRef.ExprEvalContexts.back().Context) {
16564     case Sema::ExpressionEvaluationContext::Unevaluated:
16565     case Sema::ExpressionEvaluationContext::UnevaluatedList:
16566     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
16567       return OdrUseContext::None;
16568 
16569     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
16570     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
16571       Result = OdrUseContext::Used;
16572       break;
16573 
16574     case Sema::ExpressionEvaluationContext::DiscardedStatement:
16575       Result = OdrUseContext::FormallyOdrUsed;
16576       break;
16577 
16578     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
16579       // A default argument formally results in odr-use, but doesn't actually
16580       // result in a use in any real sense until it itself is used.
16581       Result = OdrUseContext::FormallyOdrUsed;
16582       break;
16583   }
16584 
16585   if (SemaRef.CurContext->isDependentContext())
16586     return OdrUseContext::Dependent;
16587 
16588   return Result;
16589 }
16590 
16591 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
16592   if (!Func->isConstexpr())
16593     return false;
16594 
16595   if (Func->isImplicitlyInstantiable() || !Func->isUserProvided())
16596     return true;
16597   auto *CCD = dyn_cast<CXXConstructorDecl>(Func);
16598   return CCD && CCD->getInheritedConstructor();
16599 }
16600 
16601 /// Mark a function referenced, and check whether it is odr-used
16602 /// (C++ [basic.def.odr]p2, C99 6.9p3)
16603 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
16604                                   bool MightBeOdrUse) {
16605   assert(Func && "No function?");
16606 
16607   Func->setReferenced();
16608 
16609   // Recursive functions aren't really used until they're used from some other
16610   // context.
16611   bool IsRecursiveCall = CurContext == Func;
16612 
16613   // C++11 [basic.def.odr]p3:
16614   //   A function whose name appears as a potentially-evaluated expression is
16615   //   odr-used if it is the unique lookup result or the selected member of a
16616   //   set of overloaded functions [...].
16617   //
16618   // We (incorrectly) mark overload resolution as an unevaluated context, so we
16619   // can just check that here.
16620   OdrUseContext OdrUse =
16621       MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None;
16622   if (IsRecursiveCall && OdrUse == OdrUseContext::Used)
16623     OdrUse = OdrUseContext::FormallyOdrUsed;
16624 
16625   // Trivial default constructors and destructors are never actually used.
16626   // FIXME: What about other special members?
16627   if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() &&
16628       OdrUse == OdrUseContext::Used) {
16629     if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func))
16630       if (Constructor->isDefaultConstructor())
16631         OdrUse = OdrUseContext::FormallyOdrUsed;
16632     if (isa<CXXDestructorDecl>(Func))
16633       OdrUse = OdrUseContext::FormallyOdrUsed;
16634   }
16635 
16636   // C++20 [expr.const]p12:
16637   //   A function [...] is needed for constant evaluation if it is [...] a
16638   //   constexpr function that is named by an expression that is potentially
16639   //   constant evaluated
16640   bool NeededForConstantEvaluation =
16641       isPotentiallyConstantEvaluatedContext(*this) &&
16642       isImplicitlyDefinableConstexprFunction(Func);
16643 
16644   // Determine whether we require a function definition to exist, per
16645   // C++11 [temp.inst]p3:
16646   //   Unless a function template specialization has been explicitly
16647   //   instantiated or explicitly specialized, the function template
16648   //   specialization is implicitly instantiated when the specialization is
16649   //   referenced in a context that requires a function definition to exist.
16650   // C++20 [temp.inst]p7:
16651   //   The existence of a definition of a [...] function is considered to
16652   //   affect the semantics of the program if the [...] function is needed for
16653   //   constant evaluation by an expression
16654   // C++20 [basic.def.odr]p10:
16655   //   Every program shall contain exactly one definition of every non-inline
16656   //   function or variable that is odr-used in that program outside of a
16657   //   discarded statement
16658   // C++20 [special]p1:
16659   //   The implementation will implicitly define [defaulted special members]
16660   //   if they are odr-used or needed for constant evaluation.
16661   //
16662   // Note that we skip the implicit instantiation of templates that are only
16663   // used in unused default arguments or by recursive calls to themselves.
16664   // This is formally non-conforming, but seems reasonable in practice.
16665   bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used ||
16666                                              NeededForConstantEvaluation);
16667 
16668   // C++14 [temp.expl.spec]p6:
16669   //   If a template [...] is explicitly specialized then that specialization
16670   //   shall be declared before the first use of that specialization that would
16671   //   cause an implicit instantiation to take place, in every translation unit
16672   //   in which such a use occurs
16673   if (NeedDefinition &&
16674       (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
16675        Func->getMemberSpecializationInfo()))
16676     checkSpecializationVisibility(Loc, Func);
16677 
16678   if (getLangOpts().CUDA)
16679     CheckCUDACall(Loc, Func);
16680 
16681   if (getLangOpts().SYCLIsDevice)
16682     checkSYCLDeviceFunction(Loc, Func);
16683 
16684   // If we need a definition, try to create one.
16685   if (NeedDefinition && !Func->getBody()) {
16686     runWithSufficientStackSpace(Loc, [&] {
16687       if (CXXConstructorDecl *Constructor =
16688               dyn_cast<CXXConstructorDecl>(Func)) {
16689         Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
16690         if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
16691           if (Constructor->isDefaultConstructor()) {
16692             if (Constructor->isTrivial() &&
16693                 !Constructor->hasAttr<DLLExportAttr>())
16694               return;
16695             DefineImplicitDefaultConstructor(Loc, Constructor);
16696           } else if (Constructor->isCopyConstructor()) {
16697             DefineImplicitCopyConstructor(Loc, Constructor);
16698           } else if (Constructor->isMoveConstructor()) {
16699             DefineImplicitMoveConstructor(Loc, Constructor);
16700           }
16701         } else if (Constructor->getInheritedConstructor()) {
16702           DefineInheritingConstructor(Loc, Constructor);
16703         }
16704       } else if (CXXDestructorDecl *Destructor =
16705                      dyn_cast<CXXDestructorDecl>(Func)) {
16706         Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
16707         if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
16708           if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
16709             return;
16710           DefineImplicitDestructor(Loc, Destructor);
16711         }
16712         if (Destructor->isVirtual() && getLangOpts().AppleKext)
16713           MarkVTableUsed(Loc, Destructor->getParent());
16714       } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
16715         if (MethodDecl->isOverloadedOperator() &&
16716             MethodDecl->getOverloadedOperator() == OO_Equal) {
16717           MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
16718           if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
16719             if (MethodDecl->isCopyAssignmentOperator())
16720               DefineImplicitCopyAssignment(Loc, MethodDecl);
16721             else if (MethodDecl->isMoveAssignmentOperator())
16722               DefineImplicitMoveAssignment(Loc, MethodDecl);
16723           }
16724         } else if (isa<CXXConversionDecl>(MethodDecl) &&
16725                    MethodDecl->getParent()->isLambda()) {
16726           CXXConversionDecl *Conversion =
16727               cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
16728           if (Conversion->isLambdaToBlockPointerConversion())
16729             DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
16730           else
16731             DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
16732         } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
16733           MarkVTableUsed(Loc, MethodDecl->getParent());
16734       }
16735 
16736       if (Func->isDefaulted() && !Func->isDeleted()) {
16737         DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func);
16738         if (DCK != DefaultedComparisonKind::None)
16739           DefineDefaultedComparison(Loc, Func, DCK);
16740       }
16741 
16742       // Implicit instantiation of function templates and member functions of
16743       // class templates.
16744       if (Func->isImplicitlyInstantiable()) {
16745         TemplateSpecializationKind TSK =
16746             Func->getTemplateSpecializationKindForInstantiation();
16747         SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
16748         bool FirstInstantiation = PointOfInstantiation.isInvalid();
16749         if (FirstInstantiation) {
16750           PointOfInstantiation = Loc;
16751           Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
16752         } else if (TSK != TSK_ImplicitInstantiation) {
16753           // Use the point of use as the point of instantiation, instead of the
16754           // point of explicit instantiation (which we track as the actual point
16755           // of instantiation). This gives better backtraces in diagnostics.
16756           PointOfInstantiation = Loc;
16757         }
16758 
16759         if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
16760             Func->isConstexpr()) {
16761           if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
16762               cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
16763               CodeSynthesisContexts.size())
16764             PendingLocalImplicitInstantiations.push_back(
16765                 std::make_pair(Func, PointOfInstantiation));
16766           else if (Func->isConstexpr())
16767             // Do not defer instantiations of constexpr functions, to avoid the
16768             // expression evaluator needing to call back into Sema if it sees a
16769             // call to such a function.
16770             InstantiateFunctionDefinition(PointOfInstantiation, Func);
16771           else {
16772             Func->setInstantiationIsPending(true);
16773             PendingInstantiations.push_back(
16774                 std::make_pair(Func, PointOfInstantiation));
16775             // Notify the consumer that a function was implicitly instantiated.
16776             Consumer.HandleCXXImplicitFunctionInstantiation(Func);
16777           }
16778         }
16779       } else {
16780         // Walk redefinitions, as some of them may be instantiable.
16781         for (auto i : Func->redecls()) {
16782           if (!i->isUsed(false) && i->isImplicitlyInstantiable())
16783             MarkFunctionReferenced(Loc, i, MightBeOdrUse);
16784         }
16785       }
16786     });
16787   }
16788 
16789   // C++14 [except.spec]p17:
16790   //   An exception-specification is considered to be needed when:
16791   //   - the function is odr-used or, if it appears in an unevaluated operand,
16792   //     would be odr-used if the expression were potentially-evaluated;
16793   //
16794   // Note, we do this even if MightBeOdrUse is false. That indicates that the
16795   // function is a pure virtual function we're calling, and in that case the
16796   // function was selected by overload resolution and we need to resolve its
16797   // exception specification for a different reason.
16798   const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
16799   if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
16800     ResolveExceptionSpec(Loc, FPT);
16801 
16802   // If this is the first "real" use, act on that.
16803   if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) {
16804     // Keep track of used but undefined functions.
16805     if (!Func->isDefined()) {
16806       if (mightHaveNonExternalLinkage(Func))
16807         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
16808       else if (Func->getMostRecentDecl()->isInlined() &&
16809                !LangOpts.GNUInline &&
16810                !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
16811         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
16812       else if (isExternalWithNoLinkageType(Func))
16813         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
16814     }
16815 
16816     // Some x86 Windows calling conventions mangle the size of the parameter
16817     // pack into the name. Computing the size of the parameters requires the
16818     // parameter types to be complete. Check that now.
16819     if (funcHasParameterSizeMangling(*this, Func))
16820       CheckCompleteParameterTypesForMangler(*this, Func, Loc);
16821 
16822     // In the MS C++ ABI, the compiler emits destructor variants where they are
16823     // used. If the destructor is used here but defined elsewhere, mark the
16824     // virtual base destructors referenced. If those virtual base destructors
16825     // are inline, this will ensure they are defined when emitting the complete
16826     // destructor variant. This checking may be redundant if the destructor is
16827     // provided later in this TU.
16828     if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
16829       if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) {
16830         CXXRecordDecl *Parent = Dtor->getParent();
16831         if (Parent->getNumVBases() > 0 && !Dtor->getBody())
16832           CheckCompleteDestructorVariant(Loc, Dtor);
16833       }
16834     }
16835 
16836     Func->markUsed(Context);
16837   }
16838 }
16839 
16840 /// Directly mark a variable odr-used. Given a choice, prefer to use
16841 /// MarkVariableReferenced since it does additional checks and then
16842 /// calls MarkVarDeclODRUsed.
16843 /// If the variable must be captured:
16844 ///  - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
16845 ///  - else capture it in the DeclContext that maps to the
16846 ///    *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
16847 static void
16848 MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef,
16849                    const unsigned *const FunctionScopeIndexToStopAt = nullptr) {
16850   // Keep track of used but undefined variables.
16851   // FIXME: We shouldn't suppress this warning for static data members.
16852   if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
16853       (!Var->isExternallyVisible() || Var->isInline() ||
16854        SemaRef.isExternalWithNoLinkageType(Var)) &&
16855       !(Var->isStaticDataMember() && Var->hasInit())) {
16856     SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()];
16857     if (old.isInvalid())
16858       old = Loc;
16859   }
16860   QualType CaptureType, DeclRefType;
16861   if (SemaRef.LangOpts.OpenMP)
16862     SemaRef.tryCaptureOpenMPLambdas(Var);
16863   SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit,
16864     /*EllipsisLoc*/ SourceLocation(),
16865     /*BuildAndDiagnose*/ true,
16866     CaptureType, DeclRefType,
16867     FunctionScopeIndexToStopAt);
16868 
16869   Var->markUsed(SemaRef.Context);
16870 }
16871 
16872 void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture,
16873                                              SourceLocation Loc,
16874                                              unsigned CapturingScopeIndex) {
16875   MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex);
16876 }
16877 
16878 static void
16879 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
16880                                    ValueDecl *var, DeclContext *DC) {
16881   DeclContext *VarDC = var->getDeclContext();
16882 
16883   //  If the parameter still belongs to the translation unit, then
16884   //  we're actually just using one parameter in the declaration of
16885   //  the next.
16886   if (isa<ParmVarDecl>(var) &&
16887       isa<TranslationUnitDecl>(VarDC))
16888     return;
16889 
16890   // For C code, don't diagnose about capture if we're not actually in code
16891   // right now; it's impossible to write a non-constant expression outside of
16892   // function context, so we'll get other (more useful) diagnostics later.
16893   //
16894   // For C++, things get a bit more nasty... it would be nice to suppress this
16895   // diagnostic for certain cases like using a local variable in an array bound
16896   // for a member of a local class, but the correct predicate is not obvious.
16897   if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
16898     return;
16899 
16900   unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
16901   unsigned ContextKind = 3; // unknown
16902   if (isa<CXXMethodDecl>(VarDC) &&
16903       cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
16904     ContextKind = 2;
16905   } else if (isa<FunctionDecl>(VarDC)) {
16906     ContextKind = 0;
16907   } else if (isa<BlockDecl>(VarDC)) {
16908     ContextKind = 1;
16909   }
16910 
16911   S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
16912     << var << ValueKind << ContextKind << VarDC;
16913   S.Diag(var->getLocation(), diag::note_entity_declared_at)
16914       << var;
16915 
16916   // FIXME: Add additional diagnostic info about class etc. which prevents
16917   // capture.
16918 }
16919 
16920 
16921 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
16922                                       bool &SubCapturesAreNested,
16923                                       QualType &CaptureType,
16924                                       QualType &DeclRefType) {
16925    // Check whether we've already captured it.
16926   if (CSI->CaptureMap.count(Var)) {
16927     // If we found a capture, any subcaptures are nested.
16928     SubCapturesAreNested = true;
16929 
16930     // Retrieve the capture type for this variable.
16931     CaptureType = CSI->getCapture(Var).getCaptureType();
16932 
16933     // Compute the type of an expression that refers to this variable.
16934     DeclRefType = CaptureType.getNonReferenceType();
16935 
16936     // Similarly to mutable captures in lambda, all the OpenMP captures by copy
16937     // are mutable in the sense that user can change their value - they are
16938     // private instances of the captured declarations.
16939     const Capture &Cap = CSI->getCapture(Var);
16940     if (Cap.isCopyCapture() &&
16941         !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
16942         !(isa<CapturedRegionScopeInfo>(CSI) &&
16943           cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
16944       DeclRefType.addConst();
16945     return true;
16946   }
16947   return false;
16948 }
16949 
16950 // Only block literals, captured statements, and lambda expressions can
16951 // capture; other scopes don't work.
16952 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
16953                                  SourceLocation Loc,
16954                                  const bool Diagnose, Sema &S) {
16955   if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
16956     return getLambdaAwareParentOfDeclContext(DC);
16957   else if (Var->hasLocalStorage()) {
16958     if (Diagnose)
16959        diagnoseUncapturableValueReference(S, Loc, Var, DC);
16960   }
16961   return nullptr;
16962 }
16963 
16964 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
16965 // certain types of variables (unnamed, variably modified types etc.)
16966 // so check for eligibility.
16967 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
16968                                  SourceLocation Loc,
16969                                  const bool Diagnose, Sema &S) {
16970 
16971   bool IsBlock = isa<BlockScopeInfo>(CSI);
16972   bool IsLambda = isa<LambdaScopeInfo>(CSI);
16973 
16974   // Lambdas are not allowed to capture unnamed variables
16975   // (e.g. anonymous unions).
16976   // FIXME: The C++11 rule don't actually state this explicitly, but I'm
16977   // assuming that's the intent.
16978   if (IsLambda && !Var->getDeclName()) {
16979     if (Diagnose) {
16980       S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
16981       S.Diag(Var->getLocation(), diag::note_declared_at);
16982     }
16983     return false;
16984   }
16985 
16986   // Prohibit variably-modified types in blocks; they're difficult to deal with.
16987   if (Var->getType()->isVariablyModifiedType() && IsBlock) {
16988     if (Diagnose) {
16989       S.Diag(Loc, diag::err_ref_vm_type);
16990       S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
16991     }
16992     return false;
16993   }
16994   // Prohibit structs with flexible array members too.
16995   // We cannot capture what is in the tail end of the struct.
16996   if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
16997     if (VTTy->getDecl()->hasFlexibleArrayMember()) {
16998       if (Diagnose) {
16999         if (IsBlock)
17000           S.Diag(Loc, diag::err_ref_flexarray_type);
17001         else
17002           S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var;
17003         S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17004       }
17005       return false;
17006     }
17007   }
17008   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
17009   // Lambdas and captured statements are not allowed to capture __block
17010   // variables; they don't support the expected semantics.
17011   if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
17012     if (Diagnose) {
17013       S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda;
17014       S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17015     }
17016     return false;
17017   }
17018   // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
17019   if (S.getLangOpts().OpenCL && IsBlock &&
17020       Var->getType()->isBlockPointerType()) {
17021     if (Diagnose)
17022       S.Diag(Loc, diag::err_opencl_block_ref_block);
17023     return false;
17024   }
17025 
17026   return true;
17027 }
17028 
17029 // Returns true if the capture by block was successful.
17030 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
17031                                  SourceLocation Loc,
17032                                  const bool BuildAndDiagnose,
17033                                  QualType &CaptureType,
17034                                  QualType &DeclRefType,
17035                                  const bool Nested,
17036                                  Sema &S, bool Invalid) {
17037   bool ByRef = false;
17038 
17039   // Blocks are not allowed to capture arrays, excepting OpenCL.
17040   // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
17041   // (decayed to pointers).
17042   if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
17043     if (BuildAndDiagnose) {
17044       S.Diag(Loc, diag::err_ref_array_type);
17045       S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17046       Invalid = true;
17047     } else {
17048       return false;
17049     }
17050   }
17051 
17052   // Forbid the block-capture of autoreleasing variables.
17053   if (!Invalid &&
17054       CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
17055     if (BuildAndDiagnose) {
17056       S.Diag(Loc, diag::err_arc_autoreleasing_capture)
17057         << /*block*/ 0;
17058       S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17059       Invalid = true;
17060     } else {
17061       return false;
17062     }
17063   }
17064 
17065   // Warn about implicitly autoreleasing indirect parameters captured by blocks.
17066   if (const auto *PT = CaptureType->getAs<PointerType>()) {
17067     QualType PointeeTy = PT->getPointeeType();
17068 
17069     if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() &&
17070         PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
17071         !S.Context.hasDirectOwnershipQualifier(PointeeTy)) {
17072       if (BuildAndDiagnose) {
17073         SourceLocation VarLoc = Var->getLocation();
17074         S.Diag(Loc, diag::warn_block_capture_autoreleasing);
17075         S.Diag(VarLoc, diag::note_declare_parameter_strong);
17076       }
17077     }
17078   }
17079 
17080   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
17081   if (HasBlocksAttr || CaptureType->isReferenceType() ||
17082       (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) {
17083     // Block capture by reference does not change the capture or
17084     // declaration reference types.
17085     ByRef = true;
17086   } else {
17087     // Block capture by copy introduces 'const'.
17088     CaptureType = CaptureType.getNonReferenceType().withConst();
17089     DeclRefType = CaptureType;
17090   }
17091 
17092   // Actually capture the variable.
17093   if (BuildAndDiagnose)
17094     BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(),
17095                     CaptureType, Invalid);
17096 
17097   return !Invalid;
17098 }
17099 
17100 
17101 /// Capture the given variable in the captured region.
17102 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
17103                                     VarDecl *Var,
17104                                     SourceLocation Loc,
17105                                     const bool BuildAndDiagnose,
17106                                     QualType &CaptureType,
17107                                     QualType &DeclRefType,
17108                                     const bool RefersToCapturedVariable,
17109                                     Sema &S, bool Invalid) {
17110   // By default, capture variables by reference.
17111   bool ByRef = true;
17112   // Using an LValue reference type is consistent with Lambdas (see below).
17113   if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
17114     if (S.isOpenMPCapturedDecl(Var)) {
17115       bool HasConst = DeclRefType.isConstQualified();
17116       DeclRefType = DeclRefType.getUnqualifiedType();
17117       // Don't lose diagnostics about assignments to const.
17118       if (HasConst)
17119         DeclRefType.addConst();
17120     }
17121     // Do not capture firstprivates in tasks.
17122     if (S.isOpenMPPrivateDecl(Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel) !=
17123         OMPC_unknown)
17124       return true;
17125     ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel,
17126                                     RSI->OpenMPCaptureLevel);
17127   }
17128 
17129   if (ByRef)
17130     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
17131   else
17132     CaptureType = DeclRefType;
17133 
17134   // Actually capture the variable.
17135   if (BuildAndDiagnose)
17136     RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable,
17137                     Loc, SourceLocation(), CaptureType, Invalid);
17138 
17139   return !Invalid;
17140 }
17141 
17142 /// Capture the given variable in the lambda.
17143 static bool captureInLambda(LambdaScopeInfo *LSI,
17144                             VarDecl *Var,
17145                             SourceLocation Loc,
17146                             const bool BuildAndDiagnose,
17147                             QualType &CaptureType,
17148                             QualType &DeclRefType,
17149                             const bool RefersToCapturedVariable,
17150                             const Sema::TryCaptureKind Kind,
17151                             SourceLocation EllipsisLoc,
17152                             const bool IsTopScope,
17153                             Sema &S, bool Invalid) {
17154   // Determine whether we are capturing by reference or by value.
17155   bool ByRef = false;
17156   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
17157     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
17158   } else {
17159     ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
17160   }
17161 
17162   // Compute the type of the field that will capture this variable.
17163   if (ByRef) {
17164     // C++11 [expr.prim.lambda]p15:
17165     //   An entity is captured by reference if it is implicitly or
17166     //   explicitly captured but not captured by copy. It is
17167     //   unspecified whether additional unnamed non-static data
17168     //   members are declared in the closure type for entities
17169     //   captured by reference.
17170     //
17171     // FIXME: It is not clear whether we want to build an lvalue reference
17172     // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
17173     // to do the former, while EDG does the latter. Core issue 1249 will
17174     // clarify, but for now we follow GCC because it's a more permissive and
17175     // easily defensible position.
17176     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
17177   } else {
17178     // C++11 [expr.prim.lambda]p14:
17179     //   For each entity captured by copy, an unnamed non-static
17180     //   data member is declared in the closure type. The
17181     //   declaration order of these members is unspecified. The type
17182     //   of such a data member is the type of the corresponding
17183     //   captured entity if the entity is not a reference to an
17184     //   object, or the referenced type otherwise. [Note: If the
17185     //   captured entity is a reference to a function, the
17186     //   corresponding data member is also a reference to a
17187     //   function. - end note ]
17188     if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
17189       if (!RefType->getPointeeType()->isFunctionType())
17190         CaptureType = RefType->getPointeeType();
17191     }
17192 
17193     // Forbid the lambda copy-capture of autoreleasing variables.
17194     if (!Invalid &&
17195         CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
17196       if (BuildAndDiagnose) {
17197         S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
17198         S.Diag(Var->getLocation(), diag::note_previous_decl)
17199           << Var->getDeclName();
17200         Invalid = true;
17201       } else {
17202         return false;
17203       }
17204     }
17205 
17206     // Make sure that by-copy captures are of a complete and non-abstract type.
17207     if (!Invalid && BuildAndDiagnose) {
17208       if (!CaptureType->isDependentType() &&
17209           S.RequireCompleteSizedType(
17210               Loc, CaptureType,
17211               diag::err_capture_of_incomplete_or_sizeless_type,
17212               Var->getDeclName()))
17213         Invalid = true;
17214       else if (S.RequireNonAbstractType(Loc, CaptureType,
17215                                         diag::err_capture_of_abstract_type))
17216         Invalid = true;
17217     }
17218   }
17219 
17220   // Compute the type of a reference to this captured variable.
17221   if (ByRef)
17222     DeclRefType = CaptureType.getNonReferenceType();
17223   else {
17224     // C++ [expr.prim.lambda]p5:
17225     //   The closure type for a lambda-expression has a public inline
17226     //   function call operator [...]. This function call operator is
17227     //   declared const (9.3.1) if and only if the lambda-expression's
17228     //   parameter-declaration-clause is not followed by mutable.
17229     DeclRefType = CaptureType.getNonReferenceType();
17230     if (!LSI->Mutable && !CaptureType->isReferenceType())
17231       DeclRefType.addConst();
17232   }
17233 
17234   // Add the capture.
17235   if (BuildAndDiagnose)
17236     LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable,
17237                     Loc, EllipsisLoc, CaptureType, Invalid);
17238 
17239   return !Invalid;
17240 }
17241 
17242 bool Sema::tryCaptureVariable(
17243     VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
17244     SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
17245     QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
17246   // An init-capture is notionally from the context surrounding its
17247   // declaration, but its parent DC is the lambda class.
17248   DeclContext *VarDC = Var->getDeclContext();
17249   if (Var->isInitCapture())
17250     VarDC = VarDC->getParent();
17251 
17252   DeclContext *DC = CurContext;
17253   const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
17254       ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
17255   // We need to sync up the Declaration Context with the
17256   // FunctionScopeIndexToStopAt
17257   if (FunctionScopeIndexToStopAt) {
17258     unsigned FSIndex = FunctionScopes.size() - 1;
17259     while (FSIndex != MaxFunctionScopesIndex) {
17260       DC = getLambdaAwareParentOfDeclContext(DC);
17261       --FSIndex;
17262     }
17263   }
17264 
17265 
17266   // If the variable is declared in the current context, there is no need to
17267   // capture it.
17268   if (VarDC == DC) return true;
17269 
17270   // Capture global variables if it is required to use private copy of this
17271   // variable.
17272   bool IsGlobal = !Var->hasLocalStorage();
17273   if (IsGlobal &&
17274       !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true,
17275                                                 MaxFunctionScopesIndex)))
17276     return true;
17277   Var = Var->getCanonicalDecl();
17278 
17279   // Walk up the stack to determine whether we can capture the variable,
17280   // performing the "simple" checks that don't depend on type. We stop when
17281   // we've either hit the declared scope of the variable or find an existing
17282   // capture of that variable.  We start from the innermost capturing-entity
17283   // (the DC) and ensure that all intervening capturing-entities
17284   // (blocks/lambdas etc.) between the innermost capturer and the variable`s
17285   // declcontext can either capture the variable or have already captured
17286   // the variable.
17287   CaptureType = Var->getType();
17288   DeclRefType = CaptureType.getNonReferenceType();
17289   bool Nested = false;
17290   bool Explicit = (Kind != TryCapture_Implicit);
17291   unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
17292   do {
17293     // Only block literals, captured statements, and lambda expressions can
17294     // capture; other scopes don't work.
17295     DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
17296                                                               ExprLoc,
17297                                                               BuildAndDiagnose,
17298                                                               *this);
17299     // We need to check for the parent *first* because, if we *have*
17300     // private-captured a global variable, we need to recursively capture it in
17301     // intermediate blocks, lambdas, etc.
17302     if (!ParentDC) {
17303       if (IsGlobal) {
17304         FunctionScopesIndex = MaxFunctionScopesIndex - 1;
17305         break;
17306       }
17307       return true;
17308     }
17309 
17310     FunctionScopeInfo  *FSI = FunctionScopes[FunctionScopesIndex];
17311     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
17312 
17313 
17314     // Check whether we've already captured it.
17315     if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
17316                                              DeclRefType)) {
17317       CSI->getCapture(Var).markUsed(BuildAndDiagnose);
17318       break;
17319     }
17320     // If we are instantiating a generic lambda call operator body,
17321     // we do not want to capture new variables.  What was captured
17322     // during either a lambdas transformation or initial parsing
17323     // should be used.
17324     if (isGenericLambdaCallOperatorSpecialization(DC)) {
17325       if (BuildAndDiagnose) {
17326         LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
17327         if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
17328           Diag(ExprLoc, diag::err_lambda_impcap) << Var;
17329           Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17330           Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
17331         } else
17332           diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
17333       }
17334       return true;
17335     }
17336 
17337     // Try to capture variable-length arrays types.
17338     if (Var->getType()->isVariablyModifiedType()) {
17339       // We're going to walk down into the type and look for VLA
17340       // expressions.
17341       QualType QTy = Var->getType();
17342       if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
17343         QTy = PVD->getOriginalType();
17344       captureVariablyModifiedType(Context, QTy, CSI);
17345     }
17346 
17347     if (getLangOpts().OpenMP) {
17348       if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
17349         // OpenMP private variables should not be captured in outer scope, so
17350         // just break here. Similarly, global variables that are captured in a
17351         // target region should not be captured outside the scope of the region.
17352         if (RSI->CapRegionKind == CR_OpenMP) {
17353           OpenMPClauseKind IsOpenMPPrivateDecl = isOpenMPPrivateDecl(
17354               Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel);
17355           // If the variable is private (i.e. not captured) and has variably
17356           // modified type, we still need to capture the type for correct
17357           // codegen in all regions, associated with the construct. Currently,
17358           // it is captured in the innermost captured region only.
17359           if (IsOpenMPPrivateDecl != OMPC_unknown &&
17360               Var->getType()->isVariablyModifiedType()) {
17361             QualType QTy = Var->getType();
17362             if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
17363               QTy = PVD->getOriginalType();
17364             for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel);
17365                  I < E; ++I) {
17366               auto *OuterRSI = cast<CapturedRegionScopeInfo>(
17367                   FunctionScopes[FunctionScopesIndex - I]);
17368               assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel &&
17369                      "Wrong number of captured regions associated with the "
17370                      "OpenMP construct.");
17371               captureVariablyModifiedType(Context, QTy, OuterRSI);
17372             }
17373           }
17374           bool IsTargetCap =
17375               IsOpenMPPrivateDecl != OMPC_private &&
17376               isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel,
17377                                          RSI->OpenMPCaptureLevel);
17378           // Do not capture global if it is not privatized in outer regions.
17379           bool IsGlobalCap =
17380               IsGlobal && isOpenMPGlobalCapturedDecl(Var, RSI->OpenMPLevel,
17381                                                      RSI->OpenMPCaptureLevel);
17382 
17383           // When we detect target captures we are looking from inside the
17384           // target region, therefore we need to propagate the capture from the
17385           // enclosing region. Therefore, the capture is not initially nested.
17386           if (IsTargetCap)
17387             adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel);
17388 
17389           if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private ||
17390               (IsGlobal && !IsGlobalCap)) {
17391             Nested = !IsTargetCap;
17392             DeclRefType = DeclRefType.getUnqualifiedType();
17393             CaptureType = Context.getLValueReferenceType(DeclRefType);
17394             break;
17395           }
17396         }
17397       }
17398     }
17399     if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
17400       // No capture-default, and this is not an explicit capture
17401       // so cannot capture this variable.
17402       if (BuildAndDiagnose) {
17403         Diag(ExprLoc, diag::err_lambda_impcap) << Var;
17404         Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17405         if (cast<LambdaScopeInfo>(CSI)->Lambda)
17406           Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getBeginLoc(),
17407                diag::note_lambda_decl);
17408         // FIXME: If we error out because an outer lambda can not implicitly
17409         // capture a variable that an inner lambda explicitly captures, we
17410         // should have the inner lambda do the explicit capture - because
17411         // it makes for cleaner diagnostics later.  This would purely be done
17412         // so that the diagnostic does not misleadingly claim that a variable
17413         // can not be captured by a lambda implicitly even though it is captured
17414         // explicitly.  Suggestion:
17415         //  - create const bool VariableCaptureWasInitiallyExplicit = Explicit
17416         //    at the function head
17417         //  - cache the StartingDeclContext - this must be a lambda
17418         //  - captureInLambda in the innermost lambda the variable.
17419       }
17420       return true;
17421     }
17422 
17423     FunctionScopesIndex--;
17424     DC = ParentDC;
17425     Explicit = false;
17426   } while (!VarDC->Equals(DC));
17427 
17428   // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
17429   // computing the type of the capture at each step, checking type-specific
17430   // requirements, and adding captures if requested.
17431   // If the variable had already been captured previously, we start capturing
17432   // at the lambda nested within that one.
17433   bool Invalid = false;
17434   for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
17435        ++I) {
17436     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
17437 
17438     // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
17439     // certain types of variables (unnamed, variably modified types etc.)
17440     // so check for eligibility.
17441     if (!Invalid)
17442       Invalid =
17443           !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this);
17444 
17445     // After encountering an error, if we're actually supposed to capture, keep
17446     // capturing in nested contexts to suppress any follow-on diagnostics.
17447     if (Invalid && !BuildAndDiagnose)
17448       return true;
17449 
17450     if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
17451       Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
17452                                DeclRefType, Nested, *this, Invalid);
17453       Nested = true;
17454     } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
17455       Invalid = !captureInCapturedRegion(RSI, Var, ExprLoc, BuildAndDiagnose,
17456                                          CaptureType, DeclRefType, Nested,
17457                                          *this, Invalid);
17458       Nested = true;
17459     } else {
17460       LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
17461       Invalid =
17462           !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
17463                            DeclRefType, Nested, Kind, EllipsisLoc,
17464                            /*IsTopScope*/ I == N - 1, *this, Invalid);
17465       Nested = true;
17466     }
17467 
17468     if (Invalid && !BuildAndDiagnose)
17469       return true;
17470   }
17471   return Invalid;
17472 }
17473 
17474 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
17475                               TryCaptureKind Kind, SourceLocation EllipsisLoc) {
17476   QualType CaptureType;
17477   QualType DeclRefType;
17478   return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
17479                             /*BuildAndDiagnose=*/true, CaptureType,
17480                             DeclRefType, nullptr);
17481 }
17482 
17483 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
17484   QualType CaptureType;
17485   QualType DeclRefType;
17486   return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
17487                              /*BuildAndDiagnose=*/false, CaptureType,
17488                              DeclRefType, nullptr);
17489 }
17490 
17491 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
17492   QualType CaptureType;
17493   QualType DeclRefType;
17494 
17495   // Determine whether we can capture this variable.
17496   if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
17497                          /*BuildAndDiagnose=*/false, CaptureType,
17498                          DeclRefType, nullptr))
17499     return QualType();
17500 
17501   return DeclRefType;
17502 }
17503 
17504 namespace {
17505 // Helper to copy the template arguments from a DeclRefExpr or MemberExpr.
17506 // The produced TemplateArgumentListInfo* points to data stored within this
17507 // object, so should only be used in contexts where the pointer will not be
17508 // used after the CopiedTemplateArgs object is destroyed.
17509 class CopiedTemplateArgs {
17510   bool HasArgs;
17511   TemplateArgumentListInfo TemplateArgStorage;
17512 public:
17513   template<typename RefExpr>
17514   CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) {
17515     if (HasArgs)
17516       E->copyTemplateArgumentsInto(TemplateArgStorage);
17517   }
17518   operator TemplateArgumentListInfo*()
17519 #ifdef __has_cpp_attribute
17520 #if __has_cpp_attribute(clang::lifetimebound)
17521   [[clang::lifetimebound]]
17522 #endif
17523 #endif
17524   {
17525     return HasArgs ? &TemplateArgStorage : nullptr;
17526   }
17527 };
17528 }
17529 
17530 /// Walk the set of potential results of an expression and mark them all as
17531 /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason.
17532 ///
17533 /// \return A new expression if we found any potential results, ExprEmpty() if
17534 ///         not, and ExprError() if we diagnosed an error.
17535 static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E,
17536                                                       NonOdrUseReason NOUR) {
17537   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
17538   // an object that satisfies the requirements for appearing in a
17539   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
17540   // is immediately applied."  This function handles the lvalue-to-rvalue
17541   // conversion part.
17542   //
17543   // If we encounter a node that claims to be an odr-use but shouldn't be, we
17544   // transform it into the relevant kind of non-odr-use node and rebuild the
17545   // tree of nodes leading to it.
17546   //
17547   // This is a mini-TreeTransform that only transforms a restricted subset of
17548   // nodes (and only certain operands of them).
17549 
17550   // Rebuild a subexpression.
17551   auto Rebuild = [&](Expr *Sub) {
17552     return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR);
17553   };
17554 
17555   // Check whether a potential result satisfies the requirements of NOUR.
17556   auto IsPotentialResultOdrUsed = [&](NamedDecl *D) {
17557     // Any entity other than a VarDecl is always odr-used whenever it's named
17558     // in a potentially-evaluated expression.
17559     auto *VD = dyn_cast<VarDecl>(D);
17560     if (!VD)
17561       return true;
17562 
17563     // C++2a [basic.def.odr]p4:
17564     //   A variable x whose name appears as a potentially-evalauted expression
17565     //   e is odr-used by e unless
17566     //   -- x is a reference that is usable in constant expressions, or
17567     //   -- x is a variable of non-reference type that is usable in constant
17568     //      expressions and has no mutable subobjects, and e is an element of
17569     //      the set of potential results of an expression of
17570     //      non-volatile-qualified non-class type to which the lvalue-to-rvalue
17571     //      conversion is applied, or
17572     //   -- x is a variable of non-reference type, and e is an element of the
17573     //      set of potential results of a discarded-value expression to which
17574     //      the lvalue-to-rvalue conversion is not applied
17575     //
17576     // We check the first bullet and the "potentially-evaluated" condition in
17577     // BuildDeclRefExpr. We check the type requirements in the second bullet
17578     // in CheckLValueToRValueConversionOperand below.
17579     switch (NOUR) {
17580     case NOUR_None:
17581     case NOUR_Unevaluated:
17582       llvm_unreachable("unexpected non-odr-use-reason");
17583 
17584     case NOUR_Constant:
17585       // Constant references were handled when they were built.
17586       if (VD->getType()->isReferenceType())
17587         return true;
17588       if (auto *RD = VD->getType()->getAsCXXRecordDecl())
17589         if (RD->hasMutableFields())
17590           return true;
17591       if (!VD->isUsableInConstantExpressions(S.Context))
17592         return true;
17593       break;
17594 
17595     case NOUR_Discarded:
17596       if (VD->getType()->isReferenceType())
17597         return true;
17598       break;
17599     }
17600     return false;
17601   };
17602 
17603   // Mark that this expression does not constitute an odr-use.
17604   auto MarkNotOdrUsed = [&] {
17605     S.MaybeODRUseExprs.remove(E);
17606     if (LambdaScopeInfo *LSI = S.getCurLambda())
17607       LSI->markVariableExprAsNonODRUsed(E);
17608   };
17609 
17610   // C++2a [basic.def.odr]p2:
17611   //   The set of potential results of an expression e is defined as follows:
17612   switch (E->getStmtClass()) {
17613   //   -- If e is an id-expression, ...
17614   case Expr::DeclRefExprClass: {
17615     auto *DRE = cast<DeclRefExpr>(E);
17616     if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl()))
17617       break;
17618 
17619     // Rebuild as a non-odr-use DeclRefExpr.
17620     MarkNotOdrUsed();
17621     return DeclRefExpr::Create(
17622         S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(),
17623         DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(),
17624         DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(),
17625         DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR);
17626   }
17627 
17628   case Expr::FunctionParmPackExprClass: {
17629     auto *FPPE = cast<FunctionParmPackExpr>(E);
17630     // If any of the declarations in the pack is odr-used, then the expression
17631     // as a whole constitutes an odr-use.
17632     for (VarDecl *D : *FPPE)
17633       if (IsPotentialResultOdrUsed(D))
17634         return ExprEmpty();
17635 
17636     // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice,
17637     // nothing cares about whether we marked this as an odr-use, but it might
17638     // be useful for non-compiler tools.
17639     MarkNotOdrUsed();
17640     break;
17641   }
17642 
17643   //   -- If e is a subscripting operation with an array operand...
17644   case Expr::ArraySubscriptExprClass: {
17645     auto *ASE = cast<ArraySubscriptExpr>(E);
17646     Expr *OldBase = ASE->getBase()->IgnoreImplicit();
17647     if (!OldBase->getType()->isArrayType())
17648       break;
17649     ExprResult Base = Rebuild(OldBase);
17650     if (!Base.isUsable())
17651       return Base;
17652     Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS();
17653     Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS();
17654     SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored.
17655     return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS,
17656                                      ASE->getRBracketLoc());
17657   }
17658 
17659   case Expr::MemberExprClass: {
17660     auto *ME = cast<MemberExpr>(E);
17661     // -- If e is a class member access expression [...] naming a non-static
17662     //    data member...
17663     if (isa<FieldDecl>(ME->getMemberDecl())) {
17664       ExprResult Base = Rebuild(ME->getBase());
17665       if (!Base.isUsable())
17666         return Base;
17667       return MemberExpr::Create(
17668           S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(),
17669           ME->getQualifierLoc(), ME->getTemplateKeywordLoc(),
17670           ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(),
17671           CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(),
17672           ME->getObjectKind(), ME->isNonOdrUse());
17673     }
17674 
17675     if (ME->getMemberDecl()->isCXXInstanceMember())
17676       break;
17677 
17678     // -- If e is a class member access expression naming a static data member,
17679     //    ...
17680     if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl()))
17681       break;
17682 
17683     // Rebuild as a non-odr-use MemberExpr.
17684     MarkNotOdrUsed();
17685     return MemberExpr::Create(
17686         S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(),
17687         ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(),
17688         ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME),
17689         ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR);
17690     return ExprEmpty();
17691   }
17692 
17693   case Expr::BinaryOperatorClass: {
17694     auto *BO = cast<BinaryOperator>(E);
17695     Expr *LHS = BO->getLHS();
17696     Expr *RHS = BO->getRHS();
17697     // -- If e is a pointer-to-member expression of the form e1 .* e2 ...
17698     if (BO->getOpcode() == BO_PtrMemD) {
17699       ExprResult Sub = Rebuild(LHS);
17700       if (!Sub.isUsable())
17701         return Sub;
17702       LHS = Sub.get();
17703     //   -- If e is a comma expression, ...
17704     } else if (BO->getOpcode() == BO_Comma) {
17705       ExprResult Sub = Rebuild(RHS);
17706       if (!Sub.isUsable())
17707         return Sub;
17708       RHS = Sub.get();
17709     } else {
17710       break;
17711     }
17712     return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(),
17713                         LHS, RHS);
17714   }
17715 
17716   //   -- If e has the form (e1)...
17717   case Expr::ParenExprClass: {
17718     auto *PE = cast<ParenExpr>(E);
17719     ExprResult Sub = Rebuild(PE->getSubExpr());
17720     if (!Sub.isUsable())
17721       return Sub;
17722     return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get());
17723   }
17724 
17725   //   -- If e is a glvalue conditional expression, ...
17726   // We don't apply this to a binary conditional operator. FIXME: Should we?
17727   case Expr::ConditionalOperatorClass: {
17728     auto *CO = cast<ConditionalOperator>(E);
17729     ExprResult LHS = Rebuild(CO->getLHS());
17730     if (LHS.isInvalid())
17731       return ExprError();
17732     ExprResult RHS = Rebuild(CO->getRHS());
17733     if (RHS.isInvalid())
17734       return ExprError();
17735     if (!LHS.isUsable() && !RHS.isUsable())
17736       return ExprEmpty();
17737     if (!LHS.isUsable())
17738       LHS = CO->getLHS();
17739     if (!RHS.isUsable())
17740       RHS = CO->getRHS();
17741     return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(),
17742                                 CO->getCond(), LHS.get(), RHS.get());
17743   }
17744 
17745   // [Clang extension]
17746   //   -- If e has the form __extension__ e1...
17747   case Expr::UnaryOperatorClass: {
17748     auto *UO = cast<UnaryOperator>(E);
17749     if (UO->getOpcode() != UO_Extension)
17750       break;
17751     ExprResult Sub = Rebuild(UO->getSubExpr());
17752     if (!Sub.isUsable())
17753       return Sub;
17754     return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension,
17755                           Sub.get());
17756   }
17757 
17758   // [Clang extension]
17759   //   -- If e has the form _Generic(...), the set of potential results is the
17760   //      union of the sets of potential results of the associated expressions.
17761   case Expr::GenericSelectionExprClass: {
17762     auto *GSE = cast<GenericSelectionExpr>(E);
17763 
17764     SmallVector<Expr *, 4> AssocExprs;
17765     bool AnyChanged = false;
17766     for (Expr *OrigAssocExpr : GSE->getAssocExprs()) {
17767       ExprResult AssocExpr = Rebuild(OrigAssocExpr);
17768       if (AssocExpr.isInvalid())
17769         return ExprError();
17770       if (AssocExpr.isUsable()) {
17771         AssocExprs.push_back(AssocExpr.get());
17772         AnyChanged = true;
17773       } else {
17774         AssocExprs.push_back(OrigAssocExpr);
17775       }
17776     }
17777 
17778     return AnyChanged ? S.CreateGenericSelectionExpr(
17779                             GSE->getGenericLoc(), GSE->getDefaultLoc(),
17780                             GSE->getRParenLoc(), GSE->getControllingExpr(),
17781                             GSE->getAssocTypeSourceInfos(), AssocExprs)
17782                       : ExprEmpty();
17783   }
17784 
17785   // [Clang extension]
17786   //   -- If e has the form __builtin_choose_expr(...), the set of potential
17787   //      results is the union of the sets of potential results of the
17788   //      second and third subexpressions.
17789   case Expr::ChooseExprClass: {
17790     auto *CE = cast<ChooseExpr>(E);
17791 
17792     ExprResult LHS = Rebuild(CE->getLHS());
17793     if (LHS.isInvalid())
17794       return ExprError();
17795 
17796     ExprResult RHS = Rebuild(CE->getLHS());
17797     if (RHS.isInvalid())
17798       return ExprError();
17799 
17800     if (!LHS.get() && !RHS.get())
17801       return ExprEmpty();
17802     if (!LHS.isUsable())
17803       LHS = CE->getLHS();
17804     if (!RHS.isUsable())
17805       RHS = CE->getRHS();
17806 
17807     return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(),
17808                              RHS.get(), CE->getRParenLoc());
17809   }
17810 
17811   // Step through non-syntactic nodes.
17812   case Expr::ConstantExprClass: {
17813     auto *CE = cast<ConstantExpr>(E);
17814     ExprResult Sub = Rebuild(CE->getSubExpr());
17815     if (!Sub.isUsable())
17816       return Sub;
17817     return ConstantExpr::Create(S.Context, Sub.get());
17818   }
17819 
17820   // We could mostly rely on the recursive rebuilding to rebuild implicit
17821   // casts, but not at the top level, so rebuild them here.
17822   case Expr::ImplicitCastExprClass: {
17823     auto *ICE = cast<ImplicitCastExpr>(E);
17824     // Only step through the narrow set of cast kinds we expect to encounter.
17825     // Anything else suggests we've left the region in which potential results
17826     // can be found.
17827     switch (ICE->getCastKind()) {
17828     case CK_NoOp:
17829     case CK_DerivedToBase:
17830     case CK_UncheckedDerivedToBase: {
17831       ExprResult Sub = Rebuild(ICE->getSubExpr());
17832       if (!Sub.isUsable())
17833         return Sub;
17834       CXXCastPath Path(ICE->path());
17835       return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(),
17836                                  ICE->getValueKind(), &Path);
17837     }
17838 
17839     default:
17840       break;
17841     }
17842     break;
17843   }
17844 
17845   default:
17846     break;
17847   }
17848 
17849   // Can't traverse through this node. Nothing to do.
17850   return ExprEmpty();
17851 }
17852 
17853 ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) {
17854   // Check whether the operand is or contains an object of non-trivial C union
17855   // type.
17856   if (E->getType().isVolatileQualified() &&
17857       (E->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
17858        E->getType().hasNonTrivialToPrimitiveCopyCUnion()))
17859     checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
17860                           Sema::NTCUC_LValueToRValueVolatile,
17861                           NTCUK_Destruct|NTCUK_Copy);
17862 
17863   // C++2a [basic.def.odr]p4:
17864   //   [...] an expression of non-volatile-qualified non-class type to which
17865   //   the lvalue-to-rvalue conversion is applied [...]
17866   if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>())
17867     return E;
17868 
17869   ExprResult Result =
17870       rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant);
17871   if (Result.isInvalid())
17872     return ExprError();
17873   return Result.get() ? Result : E;
17874 }
17875 
17876 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
17877   Res = CorrectDelayedTyposInExpr(Res);
17878 
17879   if (!Res.isUsable())
17880     return Res;
17881 
17882   // If a constant-expression is a reference to a variable where we delay
17883   // deciding whether it is an odr-use, just assume we will apply the
17884   // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
17885   // (a non-type template argument), we have special handling anyway.
17886   return CheckLValueToRValueConversionOperand(Res.get());
17887 }
17888 
17889 void Sema::CleanupVarDeclMarking() {
17890   // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
17891   // call.
17892   MaybeODRUseExprSet LocalMaybeODRUseExprs;
17893   std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs);
17894 
17895   for (Expr *E : LocalMaybeODRUseExprs) {
17896     if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
17897       MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()),
17898                          DRE->getLocation(), *this);
17899     } else if (auto *ME = dyn_cast<MemberExpr>(E)) {
17900       MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(),
17901                          *this);
17902     } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) {
17903       for (VarDecl *VD : *FP)
17904         MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this);
17905     } else {
17906       llvm_unreachable("Unexpected expression");
17907     }
17908   }
17909 
17910   assert(MaybeODRUseExprs.empty() &&
17911          "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?");
17912 }
17913 
17914 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
17915                                     VarDecl *Var, Expr *E) {
17916   assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||
17917           isa<FunctionParmPackExpr>(E)) &&
17918          "Invalid Expr argument to DoMarkVarDeclReferenced");
17919   Var->setReferenced();
17920 
17921   if (Var->isInvalidDecl())
17922     return;
17923 
17924   // Record a CUDA/HIP static device/constant variable if it is referenced
17925   // by host code. This is done conservatively, when the variable is referenced
17926   // in any of the following contexts:
17927   //   - a non-function context
17928   //   - a host function
17929   //   - a host device function
17930   // This also requires the reference of the static device/constant variable by
17931   // host code to be visible in the device compilation for the compiler to be
17932   // able to externalize the static device/constant variable.
17933   if (SemaRef.getASTContext().mayExternalizeStaticVar(Var)) {
17934     auto *CurContext = SemaRef.CurContext;
17935     if (!CurContext || !isa<FunctionDecl>(CurContext) ||
17936         cast<FunctionDecl>(CurContext)->hasAttr<CUDAHostAttr>() ||
17937         (!cast<FunctionDecl>(CurContext)->hasAttr<CUDADeviceAttr>() &&
17938          !cast<FunctionDecl>(CurContext)->hasAttr<CUDAGlobalAttr>()))
17939       SemaRef.getASTContext().CUDAStaticDeviceVarReferencedByHost.insert(Var);
17940   }
17941 
17942   auto *MSI = Var->getMemberSpecializationInfo();
17943   TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind()
17944                                        : Var->getTemplateSpecializationKind();
17945 
17946   OdrUseContext OdrUse = isOdrUseContext(SemaRef);
17947   bool UsableInConstantExpr =
17948       Var->mightBeUsableInConstantExpressions(SemaRef.Context);
17949 
17950   // C++20 [expr.const]p12:
17951   //   A variable [...] is needed for constant evaluation if it is [...] a
17952   //   variable whose name appears as a potentially constant evaluated
17953   //   expression that is either a contexpr variable or is of non-volatile
17954   //   const-qualified integral type or of reference type
17955   bool NeededForConstantEvaluation =
17956       isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr;
17957 
17958   bool NeedDefinition =
17959       OdrUse == OdrUseContext::Used || NeededForConstantEvaluation;
17960 
17961   assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
17962          "Can't instantiate a partial template specialization.");
17963 
17964   // If this might be a member specialization of a static data member, check
17965   // the specialization is visible. We already did the checks for variable
17966   // template specializations when we created them.
17967   if (NeedDefinition && TSK != TSK_Undeclared &&
17968       !isa<VarTemplateSpecializationDecl>(Var))
17969     SemaRef.checkSpecializationVisibility(Loc, Var);
17970 
17971   // Perform implicit instantiation of static data members, static data member
17972   // templates of class templates, and variable template specializations. Delay
17973   // instantiations of variable templates, except for those that could be used
17974   // in a constant expression.
17975   if (NeedDefinition && isTemplateInstantiation(TSK)) {
17976     // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
17977     // instantiation declaration if a variable is usable in a constant
17978     // expression (among other cases).
17979     bool TryInstantiating =
17980         TSK == TSK_ImplicitInstantiation ||
17981         (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
17982 
17983     if (TryInstantiating) {
17984       SourceLocation PointOfInstantiation =
17985           MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation();
17986       bool FirstInstantiation = PointOfInstantiation.isInvalid();
17987       if (FirstInstantiation) {
17988         PointOfInstantiation = Loc;
17989         if (MSI)
17990           MSI->setPointOfInstantiation(PointOfInstantiation);
17991         else
17992           Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
17993       }
17994 
17995       if (UsableInConstantExpr) {
17996         // Do not defer instantiations of variables that could be used in a
17997         // constant expression.
17998         SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] {
17999           SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
18000         });
18001       } else if (FirstInstantiation ||
18002                  isa<VarTemplateSpecializationDecl>(Var)) {
18003         // FIXME: For a specialization of a variable template, we don't
18004         // distinguish between "declaration and type implicitly instantiated"
18005         // and "implicit instantiation of definition requested", so we have
18006         // no direct way to avoid enqueueing the pending instantiation
18007         // multiple times.
18008         SemaRef.PendingInstantiations
18009             .push_back(std::make_pair(Var, PointOfInstantiation));
18010       }
18011     }
18012   }
18013 
18014   // C++2a [basic.def.odr]p4:
18015   //   A variable x whose name appears as a potentially-evaluated expression e
18016   //   is odr-used by e unless
18017   //   -- x is a reference that is usable in constant expressions
18018   //   -- x is a variable of non-reference type that is usable in constant
18019   //      expressions and has no mutable subobjects [FIXME], and e is an
18020   //      element of the set of potential results of an expression of
18021   //      non-volatile-qualified non-class type to which the lvalue-to-rvalue
18022   //      conversion is applied
18023   //   -- x is a variable of non-reference type, and e is an element of the set
18024   //      of potential results of a discarded-value expression to which the
18025   //      lvalue-to-rvalue conversion is not applied [FIXME]
18026   //
18027   // We check the first part of the second bullet here, and
18028   // Sema::CheckLValueToRValueConversionOperand deals with the second part.
18029   // FIXME: To get the third bullet right, we need to delay this even for
18030   // variables that are not usable in constant expressions.
18031 
18032   // If we already know this isn't an odr-use, there's nothing more to do.
18033   if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E))
18034     if (DRE->isNonOdrUse())
18035       return;
18036   if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E))
18037     if (ME->isNonOdrUse())
18038       return;
18039 
18040   switch (OdrUse) {
18041   case OdrUseContext::None:
18042     assert((!E || isa<FunctionParmPackExpr>(E)) &&
18043            "missing non-odr-use marking for unevaluated decl ref");
18044     break;
18045 
18046   case OdrUseContext::FormallyOdrUsed:
18047     // FIXME: Ignoring formal odr-uses results in incorrect lambda capture
18048     // behavior.
18049     break;
18050 
18051   case OdrUseContext::Used:
18052     // If we might later find that this expression isn't actually an odr-use,
18053     // delay the marking.
18054     if (E && Var->isUsableInConstantExpressions(SemaRef.Context))
18055       SemaRef.MaybeODRUseExprs.insert(E);
18056     else
18057       MarkVarDeclODRUsed(Var, Loc, SemaRef);
18058     break;
18059 
18060   case OdrUseContext::Dependent:
18061     // If this is a dependent context, we don't need to mark variables as
18062     // odr-used, but we may still need to track them for lambda capture.
18063     // FIXME: Do we also need to do this inside dependent typeid expressions
18064     // (which are modeled as unevaluated at this point)?
18065     const bool RefersToEnclosingScope =
18066         (SemaRef.CurContext != Var->getDeclContext() &&
18067          Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
18068     if (RefersToEnclosingScope) {
18069       LambdaScopeInfo *const LSI =
18070           SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
18071       if (LSI && (!LSI->CallOperator ||
18072                   !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
18073         // If a variable could potentially be odr-used, defer marking it so
18074         // until we finish analyzing the full expression for any
18075         // lvalue-to-rvalue
18076         // or discarded value conversions that would obviate odr-use.
18077         // Add it to the list of potential captures that will be analyzed
18078         // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
18079         // unless the variable is a reference that was initialized by a constant
18080         // expression (this will never need to be captured or odr-used).
18081         //
18082         // FIXME: We can simplify this a lot after implementing P0588R1.
18083         assert(E && "Capture variable should be used in an expression.");
18084         if (!Var->getType()->isReferenceType() ||
18085             !Var->isUsableInConstantExpressions(SemaRef.Context))
18086           LSI->addPotentialCapture(E->IgnoreParens());
18087       }
18088     }
18089     break;
18090   }
18091 }
18092 
18093 /// Mark a variable referenced, and check whether it is odr-used
18094 /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
18095 /// used directly for normal expressions referring to VarDecl.
18096 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
18097   DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
18098 }
18099 
18100 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
18101                                Decl *D, Expr *E, bool MightBeOdrUse) {
18102   if (SemaRef.isInOpenMPDeclareTargetContext())
18103     SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
18104 
18105   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
18106     DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
18107     return;
18108   }
18109 
18110   SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
18111 
18112   // If this is a call to a method via a cast, also mark the method in the
18113   // derived class used in case codegen can devirtualize the call.
18114   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
18115   if (!ME)
18116     return;
18117   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
18118   if (!MD)
18119     return;
18120   // Only attempt to devirtualize if this is truly a virtual call.
18121   bool IsVirtualCall = MD->isVirtual() &&
18122                           ME->performsVirtualDispatch(SemaRef.getLangOpts());
18123   if (!IsVirtualCall)
18124     return;
18125 
18126   // If it's possible to devirtualize the call, mark the called function
18127   // referenced.
18128   CXXMethodDecl *DM = MD->getDevirtualizedMethod(
18129       ME->getBase(), SemaRef.getLangOpts().AppleKext);
18130   if (DM)
18131     SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
18132 }
18133 
18134 /// Perform reference-marking and odr-use handling for a DeclRefExpr.
18135 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) {
18136   // TODO: update this with DR# once a defect report is filed.
18137   // C++11 defect. The address of a pure member should not be an ODR use, even
18138   // if it's a qualified reference.
18139   bool OdrUse = true;
18140   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
18141     if (Method->isVirtual() &&
18142         !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
18143       OdrUse = false;
18144 
18145   if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl()))
18146     if (!isConstantEvaluated() && FD->isConsteval() &&
18147         !RebuildingImmediateInvocation)
18148       ExprEvalContexts.back().ReferenceToConsteval.insert(E);
18149   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
18150 }
18151 
18152 /// Perform reference-marking and odr-use handling for a MemberExpr.
18153 void Sema::MarkMemberReferenced(MemberExpr *E) {
18154   // C++11 [basic.def.odr]p2:
18155   //   A non-overloaded function whose name appears as a potentially-evaluated
18156   //   expression or a member of a set of candidate functions, if selected by
18157   //   overload resolution when referred to from a potentially-evaluated
18158   //   expression, is odr-used, unless it is a pure virtual function and its
18159   //   name is not explicitly qualified.
18160   bool MightBeOdrUse = true;
18161   if (E->performsVirtualDispatch(getLangOpts())) {
18162     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
18163       if (Method->isPure())
18164         MightBeOdrUse = false;
18165   }
18166   SourceLocation Loc =
18167       E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
18168   MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse);
18169 }
18170 
18171 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr.
18172 void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) {
18173   for (VarDecl *VD : *E)
18174     MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true);
18175 }
18176 
18177 /// Perform marking for a reference to an arbitrary declaration.  It
18178 /// marks the declaration referenced, and performs odr-use checking for
18179 /// functions and variables. This method should not be used when building a
18180 /// normal expression which refers to a variable.
18181 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
18182                                  bool MightBeOdrUse) {
18183   if (MightBeOdrUse) {
18184     if (auto *VD = dyn_cast<VarDecl>(D)) {
18185       MarkVariableReferenced(Loc, VD);
18186       return;
18187     }
18188   }
18189   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
18190     MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
18191     return;
18192   }
18193   D->setReferenced();
18194 }
18195 
18196 namespace {
18197   // Mark all of the declarations used by a type as referenced.
18198   // FIXME: Not fully implemented yet! We need to have a better understanding
18199   // of when we're entering a context we should not recurse into.
18200   // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
18201   // TreeTransforms rebuilding the type in a new context. Rather than
18202   // duplicating the TreeTransform logic, we should consider reusing it here.
18203   // Currently that causes problems when rebuilding LambdaExprs.
18204   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
18205     Sema &S;
18206     SourceLocation Loc;
18207 
18208   public:
18209     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
18210 
18211     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
18212 
18213     bool TraverseTemplateArgument(const TemplateArgument &Arg);
18214   };
18215 }
18216 
18217 bool MarkReferencedDecls::TraverseTemplateArgument(
18218     const TemplateArgument &Arg) {
18219   {
18220     // A non-type template argument is a constant-evaluated context.
18221     EnterExpressionEvaluationContext Evaluated(
18222         S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
18223     if (Arg.getKind() == TemplateArgument::Declaration) {
18224       if (Decl *D = Arg.getAsDecl())
18225         S.MarkAnyDeclReferenced(Loc, D, true);
18226     } else if (Arg.getKind() == TemplateArgument::Expression) {
18227       S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false);
18228     }
18229   }
18230 
18231   return Inherited::TraverseTemplateArgument(Arg);
18232 }
18233 
18234 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
18235   MarkReferencedDecls Marker(*this, Loc);
18236   Marker.TraverseType(T);
18237 }
18238 
18239 namespace {
18240 /// Helper class that marks all of the declarations referenced by
18241 /// potentially-evaluated subexpressions as "referenced".
18242 class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> {
18243 public:
18244   typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited;
18245   bool SkipLocalVariables;
18246 
18247   EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
18248       : Inherited(S), SkipLocalVariables(SkipLocalVariables) {}
18249 
18250   void visitUsedDecl(SourceLocation Loc, Decl *D) {
18251     S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D));
18252   }
18253 
18254   void VisitDeclRefExpr(DeclRefExpr *E) {
18255     // If we were asked not to visit local variables, don't.
18256     if (SkipLocalVariables) {
18257       if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
18258         if (VD->hasLocalStorage())
18259           return;
18260     }
18261     S.MarkDeclRefReferenced(E);
18262   }
18263 
18264   void VisitMemberExpr(MemberExpr *E) {
18265     S.MarkMemberReferenced(E);
18266     Visit(E->getBase());
18267   }
18268 };
18269 } // namespace
18270 
18271 /// Mark any declarations that appear within this expression or any
18272 /// potentially-evaluated subexpressions as "referenced".
18273 ///
18274 /// \param SkipLocalVariables If true, don't mark local variables as
18275 /// 'referenced'.
18276 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
18277                                             bool SkipLocalVariables) {
18278   EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
18279 }
18280 
18281 /// Emit a diagnostic that describes an effect on the run-time behavior
18282 /// of the program being compiled.
18283 ///
18284 /// This routine emits the given diagnostic when the code currently being
18285 /// type-checked is "potentially evaluated", meaning that there is a
18286 /// possibility that the code will actually be executable. Code in sizeof()
18287 /// expressions, code used only during overload resolution, etc., are not
18288 /// potentially evaluated. This routine will suppress such diagnostics or,
18289 /// in the absolutely nutty case of potentially potentially evaluated
18290 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
18291 /// later.
18292 ///
18293 /// This routine should be used for all diagnostics that describe the run-time
18294 /// behavior of a program, such as passing a non-POD value through an ellipsis.
18295 /// Failure to do so will likely result in spurious diagnostics or failures
18296 /// during overload resolution or within sizeof/alignof/typeof/typeid.
18297 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts,
18298                                const PartialDiagnostic &PD) {
18299   switch (ExprEvalContexts.back().Context) {
18300   case ExpressionEvaluationContext::Unevaluated:
18301   case ExpressionEvaluationContext::UnevaluatedList:
18302   case ExpressionEvaluationContext::UnevaluatedAbstract:
18303   case ExpressionEvaluationContext::DiscardedStatement:
18304     // The argument will never be evaluated, so don't complain.
18305     break;
18306 
18307   case ExpressionEvaluationContext::ConstantEvaluated:
18308     // Relevant diagnostics should be produced by constant evaluation.
18309     break;
18310 
18311   case ExpressionEvaluationContext::PotentiallyEvaluated:
18312   case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
18313     if (!Stmts.empty() && getCurFunctionOrMethodDecl()) {
18314       FunctionScopes.back()->PossiblyUnreachableDiags.
18315         push_back(sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
18316       return true;
18317     }
18318 
18319     // The initializer of a constexpr variable or of the first declaration of a
18320     // static data member is not syntactically a constant evaluated constant,
18321     // but nonetheless is always required to be a constant expression, so we
18322     // can skip diagnosing.
18323     // FIXME: Using the mangling context here is a hack.
18324     if (auto *VD = dyn_cast_or_null<VarDecl>(
18325             ExprEvalContexts.back().ManglingContextDecl)) {
18326       if (VD->isConstexpr() ||
18327           (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline()))
18328         break;
18329       // FIXME: For any other kind of variable, we should build a CFG for its
18330       // initializer and check whether the context in question is reachable.
18331     }
18332 
18333     Diag(Loc, PD);
18334     return true;
18335   }
18336 
18337   return false;
18338 }
18339 
18340 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
18341                                const PartialDiagnostic &PD) {
18342   return DiagRuntimeBehavior(
18343       Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD);
18344 }
18345 
18346 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
18347                                CallExpr *CE, FunctionDecl *FD) {
18348   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
18349     return false;
18350 
18351   // If we're inside a decltype's expression, don't check for a valid return
18352   // type or construct temporaries until we know whether this is the last call.
18353   if (ExprEvalContexts.back().ExprContext ==
18354       ExpressionEvaluationContextRecord::EK_Decltype) {
18355     ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
18356     return false;
18357   }
18358 
18359   class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
18360     FunctionDecl *FD;
18361     CallExpr *CE;
18362 
18363   public:
18364     CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
18365       : FD(FD), CE(CE) { }
18366 
18367     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
18368       if (!FD) {
18369         S.Diag(Loc, diag::err_call_incomplete_return)
18370           << T << CE->getSourceRange();
18371         return;
18372       }
18373 
18374       S.Diag(Loc, diag::err_call_function_incomplete_return)
18375           << CE->getSourceRange() << FD << T;
18376       S.Diag(FD->getLocation(), diag::note_entity_declared_at)
18377           << FD->getDeclName();
18378     }
18379   } Diagnoser(FD, CE);
18380 
18381   if (RequireCompleteType(Loc, ReturnType, Diagnoser))
18382     return true;
18383 
18384   return false;
18385 }
18386 
18387 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
18388 // will prevent this condition from triggering, which is what we want.
18389 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
18390   SourceLocation Loc;
18391 
18392   unsigned diagnostic = diag::warn_condition_is_assignment;
18393   bool IsOrAssign = false;
18394 
18395   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
18396     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
18397       return;
18398 
18399     IsOrAssign = Op->getOpcode() == BO_OrAssign;
18400 
18401     // Greylist some idioms by putting them into a warning subcategory.
18402     if (ObjCMessageExpr *ME
18403           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
18404       Selector Sel = ME->getSelector();
18405 
18406       // self = [<foo> init...]
18407       if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
18408         diagnostic = diag::warn_condition_is_idiomatic_assignment;
18409 
18410       // <foo> = [<bar> nextObject]
18411       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
18412         diagnostic = diag::warn_condition_is_idiomatic_assignment;
18413     }
18414 
18415     Loc = Op->getOperatorLoc();
18416   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
18417     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
18418       return;
18419 
18420     IsOrAssign = Op->getOperator() == OO_PipeEqual;
18421     Loc = Op->getOperatorLoc();
18422   } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
18423     return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
18424   else {
18425     // Not an assignment.
18426     return;
18427   }
18428 
18429   Diag(Loc, diagnostic) << E->getSourceRange();
18430 
18431   SourceLocation Open = E->getBeginLoc();
18432   SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
18433   Diag(Loc, diag::note_condition_assign_silence)
18434         << FixItHint::CreateInsertion(Open, "(")
18435         << FixItHint::CreateInsertion(Close, ")");
18436 
18437   if (IsOrAssign)
18438     Diag(Loc, diag::note_condition_or_assign_to_comparison)
18439       << FixItHint::CreateReplacement(Loc, "!=");
18440   else
18441     Diag(Loc, diag::note_condition_assign_to_comparison)
18442       << FixItHint::CreateReplacement(Loc, "==");
18443 }
18444 
18445 /// Redundant parentheses over an equality comparison can indicate
18446 /// that the user intended an assignment used as condition.
18447 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
18448   // Don't warn if the parens came from a macro.
18449   SourceLocation parenLoc = ParenE->getBeginLoc();
18450   if (parenLoc.isInvalid() || parenLoc.isMacroID())
18451     return;
18452   // Don't warn for dependent expressions.
18453   if (ParenE->isTypeDependent())
18454     return;
18455 
18456   Expr *E = ParenE->IgnoreParens();
18457 
18458   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
18459     if (opE->getOpcode() == BO_EQ &&
18460         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
18461                                                            == Expr::MLV_Valid) {
18462       SourceLocation Loc = opE->getOperatorLoc();
18463 
18464       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
18465       SourceRange ParenERange = ParenE->getSourceRange();
18466       Diag(Loc, diag::note_equality_comparison_silence)
18467         << FixItHint::CreateRemoval(ParenERange.getBegin())
18468         << FixItHint::CreateRemoval(ParenERange.getEnd());
18469       Diag(Loc, diag::note_equality_comparison_to_assign)
18470         << FixItHint::CreateReplacement(Loc, "=");
18471     }
18472 }
18473 
18474 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
18475                                        bool IsConstexpr) {
18476   DiagnoseAssignmentAsCondition(E);
18477   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
18478     DiagnoseEqualityWithExtraParens(parenE);
18479 
18480   ExprResult result = CheckPlaceholderExpr(E);
18481   if (result.isInvalid()) return ExprError();
18482   E = result.get();
18483 
18484   if (!E->isTypeDependent()) {
18485     if (getLangOpts().CPlusPlus)
18486       return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
18487 
18488     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
18489     if (ERes.isInvalid())
18490       return ExprError();
18491     E = ERes.get();
18492 
18493     QualType T = E->getType();
18494     if (!T->isScalarType()) { // C99 6.8.4.1p1
18495       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
18496         << T << E->getSourceRange();
18497       return ExprError();
18498     }
18499     CheckBoolLikeConversion(E, Loc);
18500   }
18501 
18502   return E;
18503 }
18504 
18505 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
18506                                            Expr *SubExpr, ConditionKind CK) {
18507   // Empty conditions are valid in for-statements.
18508   if (!SubExpr)
18509     return ConditionResult();
18510 
18511   ExprResult Cond;
18512   switch (CK) {
18513   case ConditionKind::Boolean:
18514     Cond = CheckBooleanCondition(Loc, SubExpr);
18515     break;
18516 
18517   case ConditionKind::ConstexprIf:
18518     Cond = CheckBooleanCondition(Loc, SubExpr, true);
18519     break;
18520 
18521   case ConditionKind::Switch:
18522     Cond = CheckSwitchCondition(Loc, SubExpr);
18523     break;
18524   }
18525   if (Cond.isInvalid()) {
18526     Cond = CreateRecoveryExpr(SubExpr->getBeginLoc(), SubExpr->getEndLoc(),
18527                               {SubExpr});
18528     if (!Cond.get())
18529       return ConditionError();
18530   }
18531   // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
18532   FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
18533   if (!FullExpr.get())
18534     return ConditionError();
18535 
18536   return ConditionResult(*this, nullptr, FullExpr,
18537                          CK == ConditionKind::ConstexprIf);
18538 }
18539 
18540 namespace {
18541   /// A visitor for rebuilding a call to an __unknown_any expression
18542   /// to have an appropriate type.
18543   struct RebuildUnknownAnyFunction
18544     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
18545 
18546     Sema &S;
18547 
18548     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
18549 
18550     ExprResult VisitStmt(Stmt *S) {
18551       llvm_unreachable("unexpected statement!");
18552     }
18553 
18554     ExprResult VisitExpr(Expr *E) {
18555       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
18556         << E->getSourceRange();
18557       return ExprError();
18558     }
18559 
18560     /// Rebuild an expression which simply semantically wraps another
18561     /// expression which it shares the type and value kind of.
18562     template <class T> ExprResult rebuildSugarExpr(T *E) {
18563       ExprResult SubResult = Visit(E->getSubExpr());
18564       if (SubResult.isInvalid()) return ExprError();
18565 
18566       Expr *SubExpr = SubResult.get();
18567       E->setSubExpr(SubExpr);
18568       E->setType(SubExpr->getType());
18569       E->setValueKind(SubExpr->getValueKind());
18570       assert(E->getObjectKind() == OK_Ordinary);
18571       return E;
18572     }
18573 
18574     ExprResult VisitParenExpr(ParenExpr *E) {
18575       return rebuildSugarExpr(E);
18576     }
18577 
18578     ExprResult VisitUnaryExtension(UnaryOperator *E) {
18579       return rebuildSugarExpr(E);
18580     }
18581 
18582     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
18583       ExprResult SubResult = Visit(E->getSubExpr());
18584       if (SubResult.isInvalid()) return ExprError();
18585 
18586       Expr *SubExpr = SubResult.get();
18587       E->setSubExpr(SubExpr);
18588       E->setType(S.Context.getPointerType(SubExpr->getType()));
18589       assert(E->getValueKind() == VK_RValue);
18590       assert(E->getObjectKind() == OK_Ordinary);
18591       return E;
18592     }
18593 
18594     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
18595       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
18596 
18597       E->setType(VD->getType());
18598 
18599       assert(E->getValueKind() == VK_RValue);
18600       if (S.getLangOpts().CPlusPlus &&
18601           !(isa<CXXMethodDecl>(VD) &&
18602             cast<CXXMethodDecl>(VD)->isInstance()))
18603         E->setValueKind(VK_LValue);
18604 
18605       return E;
18606     }
18607 
18608     ExprResult VisitMemberExpr(MemberExpr *E) {
18609       return resolveDecl(E, E->getMemberDecl());
18610     }
18611 
18612     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
18613       return resolveDecl(E, E->getDecl());
18614     }
18615   };
18616 }
18617 
18618 /// Given a function expression of unknown-any type, try to rebuild it
18619 /// to have a function type.
18620 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
18621   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
18622   if (Result.isInvalid()) return ExprError();
18623   return S.DefaultFunctionArrayConversion(Result.get());
18624 }
18625 
18626 namespace {
18627   /// A visitor for rebuilding an expression of type __unknown_anytype
18628   /// into one which resolves the type directly on the referring
18629   /// expression.  Strict preservation of the original source
18630   /// structure is not a goal.
18631   struct RebuildUnknownAnyExpr
18632     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
18633 
18634     Sema &S;
18635 
18636     /// The current destination type.
18637     QualType DestType;
18638 
18639     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
18640       : S(S), DestType(CastType) {}
18641 
18642     ExprResult VisitStmt(Stmt *S) {
18643       llvm_unreachable("unexpected statement!");
18644     }
18645 
18646     ExprResult VisitExpr(Expr *E) {
18647       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
18648         << E->getSourceRange();
18649       return ExprError();
18650     }
18651 
18652     ExprResult VisitCallExpr(CallExpr *E);
18653     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
18654 
18655     /// Rebuild an expression which simply semantically wraps another
18656     /// expression which it shares the type and value kind of.
18657     template <class T> ExprResult rebuildSugarExpr(T *E) {
18658       ExprResult SubResult = Visit(E->getSubExpr());
18659       if (SubResult.isInvalid()) return ExprError();
18660       Expr *SubExpr = SubResult.get();
18661       E->setSubExpr(SubExpr);
18662       E->setType(SubExpr->getType());
18663       E->setValueKind(SubExpr->getValueKind());
18664       assert(E->getObjectKind() == OK_Ordinary);
18665       return E;
18666     }
18667 
18668     ExprResult VisitParenExpr(ParenExpr *E) {
18669       return rebuildSugarExpr(E);
18670     }
18671 
18672     ExprResult VisitUnaryExtension(UnaryOperator *E) {
18673       return rebuildSugarExpr(E);
18674     }
18675 
18676     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
18677       const PointerType *Ptr = DestType->getAs<PointerType>();
18678       if (!Ptr) {
18679         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
18680           << E->getSourceRange();
18681         return ExprError();
18682       }
18683 
18684       if (isa<CallExpr>(E->getSubExpr())) {
18685         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
18686           << E->getSourceRange();
18687         return ExprError();
18688       }
18689 
18690       assert(E->getValueKind() == VK_RValue);
18691       assert(E->getObjectKind() == OK_Ordinary);
18692       E->setType(DestType);
18693 
18694       // Build the sub-expression as if it were an object of the pointee type.
18695       DestType = Ptr->getPointeeType();
18696       ExprResult SubResult = Visit(E->getSubExpr());
18697       if (SubResult.isInvalid()) return ExprError();
18698       E->setSubExpr(SubResult.get());
18699       return E;
18700     }
18701 
18702     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
18703 
18704     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
18705 
18706     ExprResult VisitMemberExpr(MemberExpr *E) {
18707       return resolveDecl(E, E->getMemberDecl());
18708     }
18709 
18710     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
18711       return resolveDecl(E, E->getDecl());
18712     }
18713   };
18714 }
18715 
18716 /// Rebuilds a call expression which yielded __unknown_anytype.
18717 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
18718   Expr *CalleeExpr = E->getCallee();
18719 
18720   enum FnKind {
18721     FK_MemberFunction,
18722     FK_FunctionPointer,
18723     FK_BlockPointer
18724   };
18725 
18726   FnKind Kind;
18727   QualType CalleeType = CalleeExpr->getType();
18728   if (CalleeType == S.Context.BoundMemberTy) {
18729     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
18730     Kind = FK_MemberFunction;
18731     CalleeType = Expr::findBoundMemberType(CalleeExpr);
18732   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
18733     CalleeType = Ptr->getPointeeType();
18734     Kind = FK_FunctionPointer;
18735   } else {
18736     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
18737     Kind = FK_BlockPointer;
18738   }
18739   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
18740 
18741   // Verify that this is a legal result type of a function.
18742   if (DestType->isArrayType() || DestType->isFunctionType()) {
18743     unsigned diagID = diag::err_func_returning_array_function;
18744     if (Kind == FK_BlockPointer)
18745       diagID = diag::err_block_returning_array_function;
18746 
18747     S.Diag(E->getExprLoc(), diagID)
18748       << DestType->isFunctionType() << DestType;
18749     return ExprError();
18750   }
18751 
18752   // Otherwise, go ahead and set DestType as the call's result.
18753   E->setType(DestType.getNonLValueExprType(S.Context));
18754   E->setValueKind(Expr::getValueKindForType(DestType));
18755   assert(E->getObjectKind() == OK_Ordinary);
18756 
18757   // Rebuild the function type, replacing the result type with DestType.
18758   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
18759   if (Proto) {
18760     // __unknown_anytype(...) is a special case used by the debugger when
18761     // it has no idea what a function's signature is.
18762     //
18763     // We want to build this call essentially under the K&R
18764     // unprototyped rules, but making a FunctionNoProtoType in C++
18765     // would foul up all sorts of assumptions.  However, we cannot
18766     // simply pass all arguments as variadic arguments, nor can we
18767     // portably just call the function under a non-variadic type; see
18768     // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
18769     // However, it turns out that in practice it is generally safe to
18770     // call a function declared as "A foo(B,C,D);" under the prototype
18771     // "A foo(B,C,D,...);".  The only known exception is with the
18772     // Windows ABI, where any variadic function is implicitly cdecl
18773     // regardless of its normal CC.  Therefore we change the parameter
18774     // types to match the types of the arguments.
18775     //
18776     // This is a hack, but it is far superior to moving the
18777     // corresponding target-specific code from IR-gen to Sema/AST.
18778 
18779     ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
18780     SmallVector<QualType, 8> ArgTypes;
18781     if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
18782       ArgTypes.reserve(E->getNumArgs());
18783       for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
18784         Expr *Arg = E->getArg(i);
18785         QualType ArgType = Arg->getType();
18786         if (E->isLValue()) {
18787           ArgType = S.Context.getLValueReferenceType(ArgType);
18788         } else if (E->isXValue()) {
18789           ArgType = S.Context.getRValueReferenceType(ArgType);
18790         }
18791         ArgTypes.push_back(ArgType);
18792       }
18793       ParamTypes = ArgTypes;
18794     }
18795     DestType = S.Context.getFunctionType(DestType, ParamTypes,
18796                                          Proto->getExtProtoInfo());
18797   } else {
18798     DestType = S.Context.getFunctionNoProtoType(DestType,
18799                                                 FnType->getExtInfo());
18800   }
18801 
18802   // Rebuild the appropriate pointer-to-function type.
18803   switch (Kind) {
18804   case FK_MemberFunction:
18805     // Nothing to do.
18806     break;
18807 
18808   case FK_FunctionPointer:
18809     DestType = S.Context.getPointerType(DestType);
18810     break;
18811 
18812   case FK_BlockPointer:
18813     DestType = S.Context.getBlockPointerType(DestType);
18814     break;
18815   }
18816 
18817   // Finally, we can recurse.
18818   ExprResult CalleeResult = Visit(CalleeExpr);
18819   if (!CalleeResult.isUsable()) return ExprError();
18820   E->setCallee(CalleeResult.get());
18821 
18822   // Bind a temporary if necessary.
18823   return S.MaybeBindToTemporary(E);
18824 }
18825 
18826 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
18827   // Verify that this is a legal result type of a call.
18828   if (DestType->isArrayType() || DestType->isFunctionType()) {
18829     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
18830       << DestType->isFunctionType() << DestType;
18831     return ExprError();
18832   }
18833 
18834   // Rewrite the method result type if available.
18835   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
18836     assert(Method->getReturnType() == S.Context.UnknownAnyTy);
18837     Method->setReturnType(DestType);
18838   }
18839 
18840   // Change the type of the message.
18841   E->setType(DestType.getNonReferenceType());
18842   E->setValueKind(Expr::getValueKindForType(DestType));
18843 
18844   return S.MaybeBindToTemporary(E);
18845 }
18846 
18847 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
18848   // The only case we should ever see here is a function-to-pointer decay.
18849   if (E->getCastKind() == CK_FunctionToPointerDecay) {
18850     assert(E->getValueKind() == VK_RValue);
18851     assert(E->getObjectKind() == OK_Ordinary);
18852 
18853     E->setType(DestType);
18854 
18855     // Rebuild the sub-expression as the pointee (function) type.
18856     DestType = DestType->castAs<PointerType>()->getPointeeType();
18857 
18858     ExprResult Result = Visit(E->getSubExpr());
18859     if (!Result.isUsable()) return ExprError();
18860 
18861     E->setSubExpr(Result.get());
18862     return E;
18863   } else if (E->getCastKind() == CK_LValueToRValue) {
18864     assert(E->getValueKind() == VK_RValue);
18865     assert(E->getObjectKind() == OK_Ordinary);
18866 
18867     assert(isa<BlockPointerType>(E->getType()));
18868 
18869     E->setType(DestType);
18870 
18871     // The sub-expression has to be a lvalue reference, so rebuild it as such.
18872     DestType = S.Context.getLValueReferenceType(DestType);
18873 
18874     ExprResult Result = Visit(E->getSubExpr());
18875     if (!Result.isUsable()) return ExprError();
18876 
18877     E->setSubExpr(Result.get());
18878     return E;
18879   } else {
18880     llvm_unreachable("Unhandled cast type!");
18881   }
18882 }
18883 
18884 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
18885   ExprValueKind ValueKind = VK_LValue;
18886   QualType Type = DestType;
18887 
18888   // We know how to make this work for certain kinds of decls:
18889 
18890   //  - functions
18891   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
18892     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
18893       DestType = Ptr->getPointeeType();
18894       ExprResult Result = resolveDecl(E, VD);
18895       if (Result.isInvalid()) return ExprError();
18896       return S.ImpCastExprToType(Result.get(), Type,
18897                                  CK_FunctionToPointerDecay, VK_RValue);
18898     }
18899 
18900     if (!Type->isFunctionType()) {
18901       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
18902         << VD << E->getSourceRange();
18903       return ExprError();
18904     }
18905     if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
18906       // We must match the FunctionDecl's type to the hack introduced in
18907       // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
18908       // type. See the lengthy commentary in that routine.
18909       QualType FDT = FD->getType();
18910       const FunctionType *FnType = FDT->castAs<FunctionType>();
18911       const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
18912       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
18913       if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
18914         SourceLocation Loc = FD->getLocation();
18915         FunctionDecl *NewFD = FunctionDecl::Create(
18916             S.Context, FD->getDeclContext(), Loc, Loc,
18917             FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(),
18918             SC_None, false /*isInlineSpecified*/, FD->hasPrototype(),
18919             /*ConstexprKind*/ CSK_unspecified);
18920 
18921         if (FD->getQualifier())
18922           NewFD->setQualifierInfo(FD->getQualifierLoc());
18923 
18924         SmallVector<ParmVarDecl*, 16> Params;
18925         for (const auto &AI : FT->param_types()) {
18926           ParmVarDecl *Param =
18927             S.BuildParmVarDeclForTypedef(FD, Loc, AI);
18928           Param->setScopeInfo(0, Params.size());
18929           Params.push_back(Param);
18930         }
18931         NewFD->setParams(Params);
18932         DRE->setDecl(NewFD);
18933         VD = DRE->getDecl();
18934       }
18935     }
18936 
18937     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
18938       if (MD->isInstance()) {
18939         ValueKind = VK_RValue;
18940         Type = S.Context.BoundMemberTy;
18941       }
18942 
18943     // Function references aren't l-values in C.
18944     if (!S.getLangOpts().CPlusPlus)
18945       ValueKind = VK_RValue;
18946 
18947   //  - variables
18948   } else if (isa<VarDecl>(VD)) {
18949     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
18950       Type = RefTy->getPointeeType();
18951     } else if (Type->isFunctionType()) {
18952       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
18953         << VD << E->getSourceRange();
18954       return ExprError();
18955     }
18956 
18957   //  - nothing else
18958   } else {
18959     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
18960       << VD << E->getSourceRange();
18961     return ExprError();
18962   }
18963 
18964   // Modifying the declaration like this is friendly to IR-gen but
18965   // also really dangerous.
18966   VD->setType(DestType);
18967   E->setType(Type);
18968   E->setValueKind(ValueKind);
18969   return E;
18970 }
18971 
18972 /// Check a cast of an unknown-any type.  We intentionally only
18973 /// trigger this for C-style casts.
18974 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
18975                                      Expr *CastExpr, CastKind &CastKind,
18976                                      ExprValueKind &VK, CXXCastPath &Path) {
18977   // The type we're casting to must be either void or complete.
18978   if (!CastType->isVoidType() &&
18979       RequireCompleteType(TypeRange.getBegin(), CastType,
18980                           diag::err_typecheck_cast_to_incomplete))
18981     return ExprError();
18982 
18983   // Rewrite the casted expression from scratch.
18984   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
18985   if (!result.isUsable()) return ExprError();
18986 
18987   CastExpr = result.get();
18988   VK = CastExpr->getValueKind();
18989   CastKind = CK_NoOp;
18990 
18991   return CastExpr;
18992 }
18993 
18994 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
18995   return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
18996 }
18997 
18998 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
18999                                     Expr *arg, QualType &paramType) {
19000   // If the syntactic form of the argument is not an explicit cast of
19001   // any sort, just do default argument promotion.
19002   ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
19003   if (!castArg) {
19004     ExprResult result = DefaultArgumentPromotion(arg);
19005     if (result.isInvalid()) return ExprError();
19006     paramType = result.get()->getType();
19007     return result;
19008   }
19009 
19010   // Otherwise, use the type that was written in the explicit cast.
19011   assert(!arg->hasPlaceholderType());
19012   paramType = castArg->getTypeAsWritten();
19013 
19014   // Copy-initialize a parameter of that type.
19015   InitializedEntity entity =
19016     InitializedEntity::InitializeParameter(Context, paramType,
19017                                            /*consumed*/ false);
19018   return PerformCopyInitialization(entity, callLoc, arg);
19019 }
19020 
19021 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
19022   Expr *orig = E;
19023   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
19024   while (true) {
19025     E = E->IgnoreParenImpCasts();
19026     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
19027       E = call->getCallee();
19028       diagID = diag::err_uncasted_call_of_unknown_any;
19029     } else {
19030       break;
19031     }
19032   }
19033 
19034   SourceLocation loc;
19035   NamedDecl *d;
19036   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
19037     loc = ref->getLocation();
19038     d = ref->getDecl();
19039   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
19040     loc = mem->getMemberLoc();
19041     d = mem->getMemberDecl();
19042   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
19043     diagID = diag::err_uncasted_call_of_unknown_any;
19044     loc = msg->getSelectorStartLoc();
19045     d = msg->getMethodDecl();
19046     if (!d) {
19047       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
19048         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
19049         << orig->getSourceRange();
19050       return ExprError();
19051     }
19052   } else {
19053     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
19054       << E->getSourceRange();
19055     return ExprError();
19056   }
19057 
19058   S.Diag(loc, diagID) << d << orig->getSourceRange();
19059 
19060   // Never recoverable.
19061   return ExprError();
19062 }
19063 
19064 /// Check for operands with placeholder types and complain if found.
19065 /// Returns ExprError() if there was an error and no recovery was possible.
19066 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
19067   if (!getLangOpts().CPlusPlus) {
19068     // C cannot handle TypoExpr nodes on either side of a binop because it
19069     // doesn't handle dependent types properly, so make sure any TypoExprs have
19070     // been dealt with before checking the operands.
19071     ExprResult Result = CorrectDelayedTyposInExpr(E);
19072     if (!Result.isUsable()) return ExprError();
19073     E = Result.get();
19074   }
19075 
19076   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
19077   if (!placeholderType) return E;
19078 
19079   switch (placeholderType->getKind()) {
19080 
19081   // Overloaded expressions.
19082   case BuiltinType::Overload: {
19083     // Try to resolve a single function template specialization.
19084     // This is obligatory.
19085     ExprResult Result = E;
19086     if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
19087       return Result;
19088 
19089     // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
19090     // leaves Result unchanged on failure.
19091     Result = E;
19092     if (resolveAndFixAddressOfSingleOverloadCandidate(Result))
19093       return Result;
19094 
19095     // If that failed, try to recover with a call.
19096     tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
19097                          /*complain*/ true);
19098     return Result;
19099   }
19100 
19101   // Bound member functions.
19102   case BuiltinType::BoundMember: {
19103     ExprResult result = E;
19104     const Expr *BME = E->IgnoreParens();
19105     PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
19106     // Try to give a nicer diagnostic if it is a bound member that we recognize.
19107     if (isa<CXXPseudoDestructorExpr>(BME)) {
19108       PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
19109     } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
19110       if (ME->getMemberNameInfo().getName().getNameKind() ==
19111           DeclarationName::CXXDestructorName)
19112         PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
19113     }
19114     tryToRecoverWithCall(result, PD,
19115                          /*complain*/ true);
19116     return result;
19117   }
19118 
19119   // ARC unbridged casts.
19120   case BuiltinType::ARCUnbridgedCast: {
19121     Expr *realCast = stripARCUnbridgedCast(E);
19122     diagnoseARCUnbridgedCast(realCast);
19123     return realCast;
19124   }
19125 
19126   // Expressions of unknown type.
19127   case BuiltinType::UnknownAny:
19128     return diagnoseUnknownAnyExpr(*this, E);
19129 
19130   // Pseudo-objects.
19131   case BuiltinType::PseudoObject:
19132     return checkPseudoObjectRValue(E);
19133 
19134   case BuiltinType::BuiltinFn: {
19135     // Accept __noop without parens by implicitly converting it to a call expr.
19136     auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
19137     if (DRE) {
19138       auto *FD = cast<FunctionDecl>(DRE->getDecl());
19139       if (FD->getBuiltinID() == Builtin::BI__noop) {
19140         E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
19141                               CK_BuiltinFnToFnPtr)
19142                 .get();
19143         return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy,
19144                                 VK_RValue, SourceLocation(),
19145                                 FPOptionsOverride());
19146       }
19147     }
19148 
19149     Diag(E->getBeginLoc(), diag::err_builtin_fn_use);
19150     return ExprError();
19151   }
19152 
19153   case BuiltinType::IncompleteMatrixIdx:
19154     Diag(cast<MatrixSubscriptExpr>(E->IgnoreParens())
19155              ->getRowIdx()
19156              ->getBeginLoc(),
19157          diag::err_matrix_incomplete_index);
19158     return ExprError();
19159 
19160   // Expressions of unknown type.
19161   case BuiltinType::OMPArraySection:
19162     Diag(E->getBeginLoc(), diag::err_omp_array_section_use);
19163     return ExprError();
19164 
19165   // Expressions of unknown type.
19166   case BuiltinType::OMPArrayShaping:
19167     return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use));
19168 
19169   case BuiltinType::OMPIterator:
19170     return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use));
19171 
19172   // Everything else should be impossible.
19173 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
19174   case BuiltinType::Id:
19175 #include "clang/Basic/OpenCLImageTypes.def"
19176 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
19177   case BuiltinType::Id:
19178 #include "clang/Basic/OpenCLExtensionTypes.def"
19179 #define SVE_TYPE(Name, Id, SingletonId) \
19180   case BuiltinType::Id:
19181 #include "clang/Basic/AArch64SVEACLETypes.def"
19182 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
19183 #define PLACEHOLDER_TYPE(Id, SingletonId)
19184 #include "clang/AST/BuiltinTypes.def"
19185     break;
19186   }
19187 
19188   llvm_unreachable("invalid placeholder type!");
19189 }
19190 
19191 bool Sema::CheckCaseExpression(Expr *E) {
19192   if (E->isTypeDependent())
19193     return true;
19194   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
19195     return E->getType()->isIntegralOrEnumerationType();
19196   return false;
19197 }
19198 
19199 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
19200 ExprResult
19201 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
19202   assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
19203          "Unknown Objective-C Boolean value!");
19204   QualType BoolT = Context.ObjCBuiltinBoolTy;
19205   if (!Context.getBOOLDecl()) {
19206     LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
19207                         Sema::LookupOrdinaryName);
19208     if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
19209       NamedDecl *ND = Result.getFoundDecl();
19210       if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
19211         Context.setBOOLDecl(TD);
19212     }
19213   }
19214   if (Context.getBOOLDecl())
19215     BoolT = Context.getBOOLType();
19216   return new (Context)
19217       ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
19218 }
19219 
19220 ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
19221     llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
19222     SourceLocation RParen) {
19223 
19224   StringRef Platform = getASTContext().getTargetInfo().getPlatformName();
19225 
19226   auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) {
19227     return Spec.getPlatform() == Platform;
19228   });
19229 
19230   VersionTuple Version;
19231   if (Spec != AvailSpecs.end())
19232     Version = Spec->getVersion();
19233 
19234   // The use of `@available` in the enclosing function should be analyzed to
19235   // warn when it's used inappropriately (i.e. not if(@available)).
19236   if (getCurFunctionOrMethodDecl())
19237     getEnclosingFunction()->HasPotentialAvailabilityViolations = true;
19238   else if (getCurBlock() || getCurLambda())
19239     getCurFunction()->HasPotentialAvailabilityViolations = true;
19240 
19241   return new (Context)
19242       ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
19243 }
19244 
19245 ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End,
19246                                     ArrayRef<Expr *> SubExprs, QualType T) {
19247   if (!Context.getLangOpts().RecoveryAST)
19248     return ExprError();
19249 
19250   if (isSFINAEContext())
19251     return ExprError();
19252 
19253   if (T.isNull() || !Context.getLangOpts().RecoveryASTType)
19254     // We don't know the concrete type, fallback to dependent type.
19255     T = Context.DependentTy;
19256   return RecoveryExpr::Create(Context, T, Begin, End, SubExprs);
19257 }
19258