1 //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file implements semantic analysis for expressions.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "TreeTransform.h"
14 #include "UsedDeclVisitor.h"
15 #include "clang/AST/ASTConsumer.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/ASTLambda.h"
18 #include "clang/AST/ASTMutationListener.h"
19 #include "clang/AST/CXXInheritance.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "clang/AST/DeclTemplate.h"
22 #include "clang/AST/EvaluatedExprVisitor.h"
23 #include "clang/AST/Expr.h"
24 #include "clang/AST/ExprCXX.h"
25 #include "clang/AST/ExprObjC.h"
26 #include "clang/AST/ExprOpenMP.h"
27 #include "clang/AST/RecursiveASTVisitor.h"
28 #include "clang/AST/TypeLoc.h"
29 #include "clang/Basic/Builtins.h"
30 #include "clang/Basic/FixedPoint.h"
31 #include "clang/Basic/PartialDiagnostic.h"
32 #include "clang/Basic/SourceManager.h"
33 #include "clang/Basic/TargetInfo.h"
34 #include "clang/Lex/LiteralSupport.h"
35 #include "clang/Lex/Preprocessor.h"
36 #include "clang/Sema/AnalysisBasedWarnings.h"
37 #include "clang/Sema/DeclSpec.h"
38 #include "clang/Sema/DelayedDiagnostic.h"
39 #include "clang/Sema/Designator.h"
40 #include "clang/Sema/Initialization.h"
41 #include "clang/Sema/Lookup.h"
42 #include "clang/Sema/Overload.h"
43 #include "clang/Sema/ParsedTemplate.h"
44 #include "clang/Sema/Scope.h"
45 #include "clang/Sema/ScopeInfo.h"
46 #include "clang/Sema/SemaFixItUtils.h"
47 #include "clang/Sema/SemaInternal.h"
48 #include "clang/Sema/Template.h"
49 #include "llvm/Support/ConvertUTF.h"
50 #include "llvm/Support/SaveAndRestore.h"
51 using namespace clang;
52 using namespace sema;
53 
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->getDeclName();
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 
297   if (auto *MD = dyn_cast<CXXMethodDecl>(D)) {
298     // Lambdas are only default-constructible or assignable in C++2a onwards.
299     if (MD->getParent()->isLambda() &&
300         ((isa<CXXConstructorDecl>(MD) &&
301           cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) ||
302          MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) {
303       Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign)
304         << !isa<CXXConstructorDecl>(MD);
305     }
306   }
307 
308   auto getReferencedObjCProp = [](const NamedDecl *D) ->
309                                       const ObjCPropertyDecl * {
310     if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
311       return MD->findPropertyDecl();
312     return nullptr;
313   };
314   if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
315     if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc))
316       return true;
317   } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) {
318       return true;
319   }
320 
321   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
322   // Only the variables omp_in and omp_out are allowed in the combiner.
323   // Only the variables omp_priv and omp_orig are allowed in the
324   // initializer-clause.
325   auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
326   if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
327       isa<VarDecl>(D)) {
328     Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
329         << getCurFunction()->HasOMPDeclareReductionCombiner;
330     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
331     return true;
332   }
333 
334   // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions
335   //  List-items in map clauses on this construct may only refer to the declared
336   //  variable var and entities that could be referenced by a procedure defined
337   //  at the same location
338   auto *DMD = dyn_cast<OMPDeclareMapperDecl>(CurContext);
339   if (LangOpts.OpenMP && DMD && !CurContext->containsDecl(D) &&
340       isa<VarDecl>(D)) {
341     Diag(Loc, diag::err_omp_declare_mapper_wrong_var)
342         << DMD->getVarName().getAsString();
343     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
344     return true;
345   }
346 
347   DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,
348                              AvoidPartialAvailabilityChecks, ClassReceiver);
349 
350   DiagnoseUnusedOfDecl(*this, D, Loc);
351 
352   diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
353 
354   if (isa<ParmVarDecl>(D) && isa<RequiresExprBodyDecl>(D->getDeclContext()) &&
355       !isUnevaluatedContext()) {
356     // C++ [expr.prim.req.nested] p3
357     //   A local parameter shall only appear as an unevaluated operand
358     //   (Clause 8) within the constraint-expression.
359     Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context)
360         << D;
361     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
362     return true;
363   }
364 
365   return false;
366 }
367 
368 /// DiagnoseSentinelCalls - This routine checks whether a call or
369 /// message-send is to a declaration with the sentinel attribute, and
370 /// if so, it checks that the requirements of the sentinel are
371 /// satisfied.
372 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
373                                  ArrayRef<Expr *> Args) {
374   const SentinelAttr *attr = D->getAttr<SentinelAttr>();
375   if (!attr)
376     return;
377 
378   // The number of formal parameters of the declaration.
379   unsigned numFormalParams;
380 
381   // The kind of declaration.  This is also an index into a %select in
382   // the diagnostic.
383   enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
384 
385   if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
386     numFormalParams = MD->param_size();
387     calleeType = CT_Method;
388   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
389     numFormalParams = FD->param_size();
390     calleeType = CT_Function;
391   } else if (isa<VarDecl>(D)) {
392     QualType type = cast<ValueDecl>(D)->getType();
393     const FunctionType *fn = nullptr;
394     if (const PointerType *ptr = type->getAs<PointerType>()) {
395       fn = ptr->getPointeeType()->getAs<FunctionType>();
396       if (!fn) return;
397       calleeType = CT_Function;
398     } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
399       fn = ptr->getPointeeType()->castAs<FunctionType>();
400       calleeType = CT_Block;
401     } else {
402       return;
403     }
404 
405     if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
406       numFormalParams = proto->getNumParams();
407     } else {
408       numFormalParams = 0;
409     }
410   } else {
411     return;
412   }
413 
414   // "nullPos" is the number of formal parameters at the end which
415   // effectively count as part of the variadic arguments.  This is
416   // useful if you would prefer to not have *any* formal parameters,
417   // but the language forces you to have at least one.
418   unsigned nullPos = attr->getNullPos();
419   assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
420   numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
421 
422   // The number of arguments which should follow the sentinel.
423   unsigned numArgsAfterSentinel = attr->getSentinel();
424 
425   // If there aren't enough arguments for all the formal parameters,
426   // the sentinel, and the args after the sentinel, complain.
427   if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
428     Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
429     Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
430     return;
431   }
432 
433   // Otherwise, find the sentinel expression.
434   Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
435   if (!sentinelExpr) return;
436   if (sentinelExpr->isValueDependent()) return;
437   if (Context.isSentinelNullExpr(sentinelExpr)) return;
438 
439   // Pick a reasonable string to insert.  Optimistically use 'nil', 'nullptr',
440   // or 'NULL' if those are actually defined in the context.  Only use
441   // 'nil' for ObjC methods, where it's much more likely that the
442   // variadic arguments form a list of object pointers.
443   SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc());
444   std::string NullValue;
445   if (calleeType == CT_Method && PP.isMacroDefined("nil"))
446     NullValue = "nil";
447   else if (getLangOpts().CPlusPlus11)
448     NullValue = "nullptr";
449   else if (PP.isMacroDefined("NULL"))
450     NullValue = "NULL";
451   else
452     NullValue = "(void*) 0";
453 
454   if (MissingNilLoc.isInvalid())
455     Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
456   else
457     Diag(MissingNilLoc, diag::warn_missing_sentinel)
458       << int(calleeType)
459       << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
460   Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
461 }
462 
463 SourceRange Sema::getExprRange(Expr *E) const {
464   return E ? E->getSourceRange() : SourceRange();
465 }
466 
467 //===----------------------------------------------------------------------===//
468 //  Standard Promotions and Conversions
469 //===----------------------------------------------------------------------===//
470 
471 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
472 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
473   // Handle any placeholder expressions which made it here.
474   if (E->getType()->isPlaceholderType()) {
475     ExprResult result = CheckPlaceholderExpr(E);
476     if (result.isInvalid()) return ExprError();
477     E = result.get();
478   }
479 
480   QualType Ty = E->getType();
481   assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
482 
483   if (Ty->isFunctionType()) {
484     if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
485       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
486         if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
487           return ExprError();
488 
489     E = ImpCastExprToType(E, Context.getPointerType(Ty),
490                           CK_FunctionToPointerDecay).get();
491   } else if (Ty->isArrayType()) {
492     // In C90 mode, arrays only promote to pointers if the array expression is
493     // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
494     // type 'array of type' is converted to an expression that has type 'pointer
495     // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
496     // that has type 'array of type' ...".  The relevant change is "an lvalue"
497     // (C90) to "an expression" (C99).
498     //
499     // C++ 4.2p1:
500     // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
501     // T" can be converted to an rvalue of type "pointer to T".
502     //
503     if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
504       E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
505                             CK_ArrayToPointerDecay).get();
506   }
507   return E;
508 }
509 
510 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
511   // Check to see if we are dereferencing a null pointer.  If so,
512   // and if not volatile-qualified, this is undefined behavior that the
513   // optimizer will delete, so warn about it.  People sometimes try to use this
514   // to get a deterministic trap and are surprised by clang's behavior.  This
515   // only handles the pattern "*null", which is a very syntactic check.
516   const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts());
517   if (UO && UO->getOpcode() == UO_Deref &&
518       UO->getSubExpr()->getType()->isPointerType()) {
519     const LangAS AS =
520         UO->getSubExpr()->getType()->getPointeeType().getAddressSpace();
521     if ((!isTargetAddressSpace(AS) ||
522          (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) &&
523         UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant(
524             S.Context, Expr::NPC_ValueDependentIsNotNull) &&
525         !UO->getType().isVolatileQualified()) {
526       S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
527                             S.PDiag(diag::warn_indirection_through_null)
528                                 << UO->getSubExpr()->getSourceRange());
529       S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
530                             S.PDiag(diag::note_indirection_through_null));
531     }
532   }
533 }
534 
535 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
536                                     SourceLocation AssignLoc,
537                                     const Expr* RHS) {
538   const ObjCIvarDecl *IV = OIRE->getDecl();
539   if (!IV)
540     return;
541 
542   DeclarationName MemberName = IV->getDeclName();
543   IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
544   if (!Member || !Member->isStr("isa"))
545     return;
546 
547   const Expr *Base = OIRE->getBase();
548   QualType BaseType = Base->getType();
549   if (OIRE->isArrow())
550     BaseType = BaseType->getPointeeType();
551   if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
552     if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
553       ObjCInterfaceDecl *ClassDeclared = nullptr;
554       ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
555       if (!ClassDeclared->getSuperClass()
556           && (*ClassDeclared->ivar_begin()) == IV) {
557         if (RHS) {
558           NamedDecl *ObjectSetClass =
559             S.LookupSingleName(S.TUScope,
560                                &S.Context.Idents.get("object_setClass"),
561                                SourceLocation(), S.LookupOrdinaryName);
562           if (ObjectSetClass) {
563             SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc());
564             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign)
565                 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
566                                               "object_setClass(")
567                 << FixItHint::CreateReplacement(
568                        SourceRange(OIRE->getOpLoc(), AssignLoc), ",")
569                 << FixItHint::CreateInsertion(RHSLocEnd, ")");
570           }
571           else
572             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
573         } else {
574           NamedDecl *ObjectGetClass =
575             S.LookupSingleName(S.TUScope,
576                                &S.Context.Idents.get("object_getClass"),
577                                SourceLocation(), S.LookupOrdinaryName);
578           if (ObjectGetClass)
579             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use)
580                 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
581                                               "object_getClass(")
582                 << FixItHint::CreateReplacement(
583                        SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")");
584           else
585             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
586         }
587         S.Diag(IV->getLocation(), diag::note_ivar_decl);
588       }
589     }
590 }
591 
592 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
593   // Handle any placeholder expressions which made it here.
594   if (E->getType()->isPlaceholderType()) {
595     ExprResult result = CheckPlaceholderExpr(E);
596     if (result.isInvalid()) return ExprError();
597     E = result.get();
598   }
599 
600   // C++ [conv.lval]p1:
601   //   A glvalue of a non-function, non-array type T can be
602   //   converted to a prvalue.
603   if (!E->isGLValue()) return E;
604 
605   QualType T = E->getType();
606   assert(!T.isNull() && "r-value conversion on typeless expression?");
607 
608   // We don't want to throw lvalue-to-rvalue casts on top of
609   // expressions of certain types in C++.
610   if (getLangOpts().CPlusPlus &&
611       (E->getType() == Context.OverloadTy ||
612        T->isDependentType() ||
613        T->isRecordType()))
614     return E;
615 
616   // The C standard is actually really unclear on this point, and
617   // DR106 tells us what the result should be but not why.  It's
618   // generally best to say that void types just doesn't undergo
619   // lvalue-to-rvalue at all.  Note that expressions of unqualified
620   // 'void' type are never l-values, but qualified void can be.
621   if (T->isVoidType())
622     return E;
623 
624   // OpenCL usually rejects direct accesses to values of 'half' type.
625   if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
626       T->isHalfType()) {
627     Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
628       << 0 << T;
629     return ExprError();
630   }
631 
632   CheckForNullPointerDereference(*this, E);
633   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
634     NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
635                                      &Context.Idents.get("object_getClass"),
636                                      SourceLocation(), LookupOrdinaryName);
637     if (ObjectGetClass)
638       Diag(E->getExprLoc(), diag::warn_objc_isa_use)
639           << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(")
640           << FixItHint::CreateReplacement(
641                  SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
642     else
643       Diag(E->getExprLoc(), diag::warn_objc_isa_use);
644   }
645   else if (const ObjCIvarRefExpr *OIRE =
646             dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
647     DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
648 
649   // C++ [conv.lval]p1:
650   //   [...] If T is a non-class type, the type of the prvalue is the
651   //   cv-unqualified version of T. Otherwise, the type of the
652   //   rvalue is T.
653   //
654   // C99 6.3.2.1p2:
655   //   If the lvalue has qualified type, the value has the unqualified
656   //   version of the type of the lvalue; otherwise, the value has the
657   //   type of the lvalue.
658   if (T.hasQualifiers())
659     T = T.getUnqualifiedType();
660 
661   // Under the MS ABI, lock down the inheritance model now.
662   if (T->isMemberPointerType() &&
663       Context.getTargetInfo().getCXXABI().isMicrosoft())
664     (void)isCompleteType(E->getExprLoc(), T);
665 
666   ExprResult Res = CheckLValueToRValueConversionOperand(E);
667   if (Res.isInvalid())
668     return Res;
669   E = Res.get();
670 
671   // Loading a __weak object implicitly retains the value, so we need a cleanup to
672   // balance that.
673   if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
674     Cleanup.setExprNeedsCleanups(true);
675 
676   if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
677     Cleanup.setExprNeedsCleanups(true);
678 
679   // C++ [conv.lval]p3:
680   //   If T is cv std::nullptr_t, the result is a null pointer constant.
681   CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue;
682   Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_RValue);
683 
684   // C11 6.3.2.1p2:
685   //   ... if the lvalue has atomic type, the value has the non-atomic version
686   //   of the type of the lvalue ...
687   if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
688     T = Atomic->getValueType().getUnqualifiedType();
689     Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
690                                    nullptr, VK_RValue);
691   }
692 
693   return Res;
694 }
695 
696 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
697   ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
698   if (Res.isInvalid())
699     return ExprError();
700   Res = DefaultLvalueConversion(Res.get());
701   if (Res.isInvalid())
702     return ExprError();
703   return Res;
704 }
705 
706 /// CallExprUnaryConversions - a special case of an unary conversion
707 /// performed on a function designator of a call expression.
708 ExprResult Sema::CallExprUnaryConversions(Expr *E) {
709   QualType Ty = E->getType();
710   ExprResult Res = E;
711   // Only do implicit cast for a function type, but not for a pointer
712   // to function type.
713   if (Ty->isFunctionType()) {
714     Res = ImpCastExprToType(E, Context.getPointerType(Ty),
715                             CK_FunctionToPointerDecay).get();
716     if (Res.isInvalid())
717       return ExprError();
718   }
719   Res = DefaultLvalueConversion(Res.get());
720   if (Res.isInvalid())
721     return ExprError();
722   return Res.get();
723 }
724 
725 /// UsualUnaryConversions - Performs various conversions that are common to most
726 /// operators (C99 6.3). The conversions of array and function types are
727 /// sometimes suppressed. For example, the array->pointer conversion doesn't
728 /// apply if the array is an argument to the sizeof or address (&) operators.
729 /// In these instances, this routine should *not* be called.
730 ExprResult Sema::UsualUnaryConversions(Expr *E) {
731   // First, convert to an r-value.
732   ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
733   if (Res.isInvalid())
734     return ExprError();
735   E = Res.get();
736 
737   QualType Ty = E->getType();
738   assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
739 
740   // Half FP have to be promoted to float unless it is natively supported
741   if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
742     return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
743 
744   // Try to perform integral promotions if the object has a theoretically
745   // promotable type.
746   if (Ty->isIntegralOrUnscopedEnumerationType()) {
747     // C99 6.3.1.1p2:
748     //
749     //   The following may be used in an expression wherever an int or
750     //   unsigned int may be used:
751     //     - an object or expression with an integer type whose integer
752     //       conversion rank is less than or equal to the rank of int
753     //       and unsigned int.
754     //     - A bit-field of type _Bool, int, signed int, or unsigned int.
755     //
756     //   If an int can represent all values of the original type, the
757     //   value is converted to an int; otherwise, it is converted to an
758     //   unsigned int. These are called the integer promotions. All
759     //   other types are unchanged by the integer promotions.
760 
761     QualType PTy = Context.isPromotableBitField(E);
762     if (!PTy.isNull()) {
763       E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
764       return E;
765     }
766     if (Ty->isPromotableIntegerType()) {
767       QualType PT = Context.getPromotedIntegerType(Ty);
768       E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
769       return E;
770     }
771   }
772   return E;
773 }
774 
775 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
776 /// do not have a prototype. Arguments that have type float or __fp16
777 /// are promoted to double. All other argument types are converted by
778 /// UsualUnaryConversions().
779 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
780   QualType Ty = E->getType();
781   assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
782 
783   ExprResult Res = UsualUnaryConversions(E);
784   if (Res.isInvalid())
785     return ExprError();
786   E = Res.get();
787 
788   // If this is a 'float'  or '__fp16' (CVR qualified or typedef)
789   // promote to double.
790   // Note that default argument promotion applies only to float (and
791   // half/fp16); it does not apply to _Float16.
792   const BuiltinType *BTy = Ty->getAs<BuiltinType>();
793   if (BTy && (BTy->getKind() == BuiltinType::Half ||
794               BTy->getKind() == BuiltinType::Float)) {
795     if (getLangOpts().OpenCL &&
796         !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
797         if (BTy->getKind() == BuiltinType::Half) {
798             E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
799         }
800     } else {
801       E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
802     }
803   }
804 
805   // C++ performs lvalue-to-rvalue conversion as a default argument
806   // promotion, even on class types, but note:
807   //   C++11 [conv.lval]p2:
808   //     When an lvalue-to-rvalue conversion occurs in an unevaluated
809   //     operand or a subexpression thereof the value contained in the
810   //     referenced object is not accessed. Otherwise, if the glvalue
811   //     has a class type, the conversion copy-initializes a temporary
812   //     of type T from the glvalue and the result of the conversion
813   //     is a prvalue for the temporary.
814   // FIXME: add some way to gate this entire thing for correctness in
815   // potentially potentially evaluated contexts.
816   if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
817     ExprResult Temp = PerformCopyInitialization(
818                        InitializedEntity::InitializeTemporary(E->getType()),
819                                                 E->getExprLoc(), E);
820     if (Temp.isInvalid())
821       return ExprError();
822     E = Temp.get();
823   }
824 
825   return E;
826 }
827 
828 /// Determine the degree of POD-ness for an expression.
829 /// Incomplete types are considered POD, since this check can be performed
830 /// when we're in an unevaluated context.
831 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
832   if (Ty->isIncompleteType()) {
833     // C++11 [expr.call]p7:
834     //   After these conversions, if the argument does not have arithmetic,
835     //   enumeration, pointer, pointer to member, or class type, the program
836     //   is ill-formed.
837     //
838     // Since we've already performed array-to-pointer and function-to-pointer
839     // decay, the only such type in C++ is cv void. This also handles
840     // initializer lists as variadic arguments.
841     if (Ty->isVoidType())
842       return VAK_Invalid;
843 
844     if (Ty->isObjCObjectType())
845       return VAK_Invalid;
846     return VAK_Valid;
847   }
848 
849   if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
850     return VAK_Invalid;
851 
852   if (Ty.isCXX98PODType(Context))
853     return VAK_Valid;
854 
855   // C++11 [expr.call]p7:
856   //   Passing a potentially-evaluated argument of class type (Clause 9)
857   //   having a non-trivial copy constructor, a non-trivial move constructor,
858   //   or a non-trivial destructor, with no corresponding parameter,
859   //   is conditionally-supported with implementation-defined semantics.
860   if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
861     if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
862       if (!Record->hasNonTrivialCopyConstructor() &&
863           !Record->hasNonTrivialMoveConstructor() &&
864           !Record->hasNonTrivialDestructor())
865         return VAK_ValidInCXX11;
866 
867   if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
868     return VAK_Valid;
869 
870   if (Ty->isObjCObjectType())
871     return VAK_Invalid;
872 
873   if (getLangOpts().MSVCCompat)
874     return VAK_MSVCUndefined;
875 
876   // FIXME: In C++11, these cases are conditionally-supported, meaning we're
877   // permitted to reject them. We should consider doing so.
878   return VAK_Undefined;
879 }
880 
881 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
882   // Don't allow one to pass an Objective-C interface to a vararg.
883   const QualType &Ty = E->getType();
884   VarArgKind VAK = isValidVarArgType(Ty);
885 
886   // Complain about passing non-POD types through varargs.
887   switch (VAK) {
888   case VAK_ValidInCXX11:
889     DiagRuntimeBehavior(
890         E->getBeginLoc(), nullptr,
891         PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT);
892     LLVM_FALLTHROUGH;
893   case VAK_Valid:
894     if (Ty->isRecordType()) {
895       // This is unlikely to be what the user intended. If the class has a
896       // 'c_str' member function, the user probably meant to call that.
897       DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
898                           PDiag(diag::warn_pass_class_arg_to_vararg)
899                               << Ty << CT << hasCStrMethod(E) << ".c_str()");
900     }
901     break;
902 
903   case VAK_Undefined:
904   case VAK_MSVCUndefined:
905     DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
906                         PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
907                             << getLangOpts().CPlusPlus11 << Ty << CT);
908     break;
909 
910   case VAK_Invalid:
911     if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
912       Diag(E->getBeginLoc(),
913            diag::err_cannot_pass_non_trivial_c_struct_to_vararg)
914           << Ty << CT;
915     else if (Ty->isObjCObjectType())
916       DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
917                           PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
918                               << Ty << CT);
919     else
920       Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg)
921           << isa<InitListExpr>(E) << Ty << CT;
922     break;
923   }
924 }
925 
926 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
927 /// will create a trap if the resulting type is not a POD type.
928 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
929                                                   FunctionDecl *FDecl) {
930   if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
931     // Strip the unbridged-cast placeholder expression off, if applicable.
932     if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
933         (CT == VariadicMethod ||
934          (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
935       E = stripARCUnbridgedCast(E);
936 
937     // Otherwise, do normal placeholder checking.
938     } else {
939       ExprResult ExprRes = CheckPlaceholderExpr(E);
940       if (ExprRes.isInvalid())
941         return ExprError();
942       E = ExprRes.get();
943     }
944   }
945 
946   ExprResult ExprRes = DefaultArgumentPromotion(E);
947   if (ExprRes.isInvalid())
948     return ExprError();
949   E = ExprRes.get();
950 
951   // Diagnostics regarding non-POD argument types are
952   // emitted along with format string checking in Sema::CheckFunctionCall().
953   if (isValidVarArgType(E->getType()) == VAK_Undefined) {
954     // Turn this into a trap.
955     CXXScopeSpec SS;
956     SourceLocation TemplateKWLoc;
957     UnqualifiedId Name;
958     Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
959                        E->getBeginLoc());
960     ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name,
961                                           /*HasTrailingLParen=*/true,
962                                           /*IsAddressOfOperand=*/false);
963     if (TrapFn.isInvalid())
964       return ExprError();
965 
966     ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(),
967                                     None, E->getEndLoc());
968     if (Call.isInvalid())
969       return ExprError();
970 
971     ExprResult Comma =
972         ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E);
973     if (Comma.isInvalid())
974       return ExprError();
975     return Comma.get();
976   }
977 
978   if (!getLangOpts().CPlusPlus &&
979       RequireCompleteType(E->getExprLoc(), E->getType(),
980                           diag::err_call_incomplete_argument))
981     return ExprError();
982 
983   return E;
984 }
985 
986 /// Converts an integer to complex float type.  Helper function of
987 /// UsualArithmeticConversions()
988 ///
989 /// \return false if the integer expression is an integer type and is
990 /// successfully converted to the complex type.
991 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
992                                                   ExprResult &ComplexExpr,
993                                                   QualType IntTy,
994                                                   QualType ComplexTy,
995                                                   bool SkipCast) {
996   if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
997   if (SkipCast) return false;
998   if (IntTy->isIntegerType()) {
999     QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
1000     IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
1001     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1002                                   CK_FloatingRealToComplex);
1003   } else {
1004     assert(IntTy->isComplexIntegerType());
1005     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1006                                   CK_IntegralComplexToFloatingComplex);
1007   }
1008   return false;
1009 }
1010 
1011 /// Handle arithmetic conversion with complex types.  Helper function of
1012 /// UsualArithmeticConversions()
1013 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
1014                                              ExprResult &RHS, QualType LHSType,
1015                                              QualType RHSType,
1016                                              bool IsCompAssign) {
1017   // if we have an integer operand, the result is the complex type.
1018   if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
1019                                              /*skipCast*/false))
1020     return LHSType;
1021   if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
1022                                              /*skipCast*/IsCompAssign))
1023     return RHSType;
1024 
1025   // This handles complex/complex, complex/float, or float/complex.
1026   // When both operands are complex, the shorter operand is converted to the
1027   // type of the longer, and that is the type of the result. This corresponds
1028   // to what is done when combining two real floating-point operands.
1029   // The fun begins when size promotion occur across type domains.
1030   // From H&S 6.3.4: When one operand is complex and the other is a real
1031   // floating-point type, the less precise type is converted, within it's
1032   // real or complex domain, to the precision of the other type. For example,
1033   // when combining a "long double" with a "double _Complex", the
1034   // "double _Complex" is promoted to "long double _Complex".
1035 
1036   // Compute the rank of the two types, regardless of whether they are complex.
1037   int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1038 
1039   auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
1040   auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
1041   QualType LHSElementType =
1042       LHSComplexType ? LHSComplexType->getElementType() : LHSType;
1043   QualType RHSElementType =
1044       RHSComplexType ? RHSComplexType->getElementType() : RHSType;
1045 
1046   QualType ResultType = S.Context.getComplexType(LHSElementType);
1047   if (Order < 0) {
1048     // Promote the precision of the LHS if not an assignment.
1049     ResultType = S.Context.getComplexType(RHSElementType);
1050     if (!IsCompAssign) {
1051       if (LHSComplexType)
1052         LHS =
1053             S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
1054       else
1055         LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
1056     }
1057   } else if (Order > 0) {
1058     // Promote the precision of the RHS.
1059     if (RHSComplexType)
1060       RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
1061     else
1062       RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
1063   }
1064   return ResultType;
1065 }
1066 
1067 /// Handle arithmetic conversion from integer to float.  Helper function
1068 /// of UsualArithmeticConversions()
1069 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1070                                            ExprResult &IntExpr,
1071                                            QualType FloatTy, QualType IntTy,
1072                                            bool ConvertFloat, bool ConvertInt) {
1073   if (IntTy->isIntegerType()) {
1074     if (ConvertInt)
1075       // Convert intExpr to the lhs floating point type.
1076       IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1077                                     CK_IntegralToFloating);
1078     return FloatTy;
1079   }
1080 
1081   // Convert both sides to the appropriate complex float.
1082   assert(IntTy->isComplexIntegerType());
1083   QualType result = S.Context.getComplexType(FloatTy);
1084 
1085   // _Complex int -> _Complex float
1086   if (ConvertInt)
1087     IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1088                                   CK_IntegralComplexToFloatingComplex);
1089 
1090   // float -> _Complex float
1091   if (ConvertFloat)
1092     FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1093                                     CK_FloatingRealToComplex);
1094 
1095   return result;
1096 }
1097 
1098 /// Handle arithmethic conversion with floating point types.  Helper
1099 /// function of UsualArithmeticConversions()
1100 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1101                                       ExprResult &RHS, QualType LHSType,
1102                                       QualType RHSType, bool IsCompAssign) {
1103   bool LHSFloat = LHSType->isRealFloatingType();
1104   bool RHSFloat = RHSType->isRealFloatingType();
1105 
1106   // If we have two real floating types, convert the smaller operand
1107   // to the bigger result.
1108   if (LHSFloat && RHSFloat) {
1109     int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1110     if (order > 0) {
1111       RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1112       return LHSType;
1113     }
1114 
1115     assert(order < 0 && "illegal float comparison");
1116     if (!IsCompAssign)
1117       LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1118     return RHSType;
1119   }
1120 
1121   if (LHSFloat) {
1122     // Half FP has to be promoted to float unless it is natively supported
1123     if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1124       LHSType = S.Context.FloatTy;
1125 
1126     return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1127                                       /*ConvertFloat=*/!IsCompAssign,
1128                                       /*ConvertInt=*/ true);
1129   }
1130   assert(RHSFloat);
1131   return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1132                                     /*convertInt=*/ true,
1133                                     /*convertFloat=*/!IsCompAssign);
1134 }
1135 
1136 /// Diagnose attempts to convert between __float128 and long double if
1137 /// there is no support for such conversion. Helper function of
1138 /// UsualArithmeticConversions().
1139 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1140                                       QualType RHSType) {
1141   /*  No issue converting if at least one of the types is not a floating point
1142       type or the two types have the same rank.
1143   */
1144   if (!LHSType->isFloatingType() || !RHSType->isFloatingType() ||
1145       S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0)
1146     return false;
1147 
1148   assert(LHSType->isFloatingType() && RHSType->isFloatingType() &&
1149          "The remaining types must be floating point types.");
1150 
1151   auto *LHSComplex = LHSType->getAs<ComplexType>();
1152   auto *RHSComplex = RHSType->getAs<ComplexType>();
1153 
1154   QualType LHSElemType = LHSComplex ?
1155     LHSComplex->getElementType() : LHSType;
1156   QualType RHSElemType = RHSComplex ?
1157     RHSComplex->getElementType() : RHSType;
1158 
1159   // No issue if the two types have the same representation
1160   if (&S.Context.getFloatTypeSemantics(LHSElemType) ==
1161       &S.Context.getFloatTypeSemantics(RHSElemType))
1162     return false;
1163 
1164   bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty &&
1165                                 RHSElemType == S.Context.LongDoubleTy);
1166   Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy &&
1167                             RHSElemType == S.Context.Float128Ty);
1168 
1169   // We've handled the situation where __float128 and long double have the same
1170   // representation. We allow all conversions for all possible long double types
1171   // except PPC's double double.
1172   return Float128AndLongDouble &&
1173     (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) ==
1174      &llvm::APFloat::PPCDoubleDouble());
1175 }
1176 
1177 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1178 
1179 namespace {
1180 /// These helper callbacks are placed in an anonymous namespace to
1181 /// permit their use as function template parameters.
1182 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1183   return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1184 }
1185 
1186 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1187   return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1188                              CK_IntegralComplexCast);
1189 }
1190 }
1191 
1192 /// Handle integer arithmetic conversions.  Helper function of
1193 /// UsualArithmeticConversions()
1194 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1195 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1196                                         ExprResult &RHS, QualType LHSType,
1197                                         QualType RHSType, bool IsCompAssign) {
1198   // The rules for this case are in C99 6.3.1.8
1199   int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1200   bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1201   bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1202   if (LHSSigned == RHSSigned) {
1203     // Same signedness; use the higher-ranked type
1204     if (order >= 0) {
1205       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1206       return LHSType;
1207     } else if (!IsCompAssign)
1208       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1209     return RHSType;
1210   } else if (order != (LHSSigned ? 1 : -1)) {
1211     // The unsigned type has greater than or equal rank to the
1212     // signed type, so use the unsigned type
1213     if (RHSSigned) {
1214       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1215       return LHSType;
1216     } else if (!IsCompAssign)
1217       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1218     return RHSType;
1219   } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1220     // The two types are different widths; if we are here, that
1221     // means the signed type is larger than the unsigned type, so
1222     // use the signed type.
1223     if (LHSSigned) {
1224       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1225       return LHSType;
1226     } else if (!IsCompAssign)
1227       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1228     return RHSType;
1229   } else {
1230     // The signed type is higher-ranked than the unsigned type,
1231     // but isn't actually any bigger (like unsigned int and long
1232     // on most 32-bit systems).  Use the unsigned type corresponding
1233     // to the signed type.
1234     QualType result =
1235       S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1236     RHS = (*doRHSCast)(S, RHS.get(), result);
1237     if (!IsCompAssign)
1238       LHS = (*doLHSCast)(S, LHS.get(), result);
1239     return result;
1240   }
1241 }
1242 
1243 /// Handle conversions with GCC complex int extension.  Helper function
1244 /// of UsualArithmeticConversions()
1245 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1246                                            ExprResult &RHS, QualType LHSType,
1247                                            QualType RHSType,
1248                                            bool IsCompAssign) {
1249   const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1250   const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1251 
1252   if (LHSComplexInt && RHSComplexInt) {
1253     QualType LHSEltType = LHSComplexInt->getElementType();
1254     QualType RHSEltType = RHSComplexInt->getElementType();
1255     QualType ScalarType =
1256       handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1257         (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1258 
1259     return S.Context.getComplexType(ScalarType);
1260   }
1261 
1262   if (LHSComplexInt) {
1263     QualType LHSEltType = LHSComplexInt->getElementType();
1264     QualType ScalarType =
1265       handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1266         (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1267     QualType ComplexType = S.Context.getComplexType(ScalarType);
1268     RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1269                               CK_IntegralRealToComplex);
1270 
1271     return ComplexType;
1272   }
1273 
1274   assert(RHSComplexInt);
1275 
1276   QualType RHSEltType = RHSComplexInt->getElementType();
1277   QualType ScalarType =
1278     handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1279       (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1280   QualType ComplexType = S.Context.getComplexType(ScalarType);
1281 
1282   if (!IsCompAssign)
1283     LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1284                               CK_IntegralRealToComplex);
1285   return ComplexType;
1286 }
1287 
1288 /// Return the rank of a given fixed point or integer type. The value itself
1289 /// doesn't matter, but the values must be increasing with proper increasing
1290 /// rank as described in N1169 4.1.1.
1291 static unsigned GetFixedPointRank(QualType Ty) {
1292   const auto *BTy = Ty->getAs<BuiltinType>();
1293   assert(BTy && "Expected a builtin type.");
1294 
1295   switch (BTy->getKind()) {
1296   case BuiltinType::ShortFract:
1297   case BuiltinType::UShortFract:
1298   case BuiltinType::SatShortFract:
1299   case BuiltinType::SatUShortFract:
1300     return 1;
1301   case BuiltinType::Fract:
1302   case BuiltinType::UFract:
1303   case BuiltinType::SatFract:
1304   case BuiltinType::SatUFract:
1305     return 2;
1306   case BuiltinType::LongFract:
1307   case BuiltinType::ULongFract:
1308   case BuiltinType::SatLongFract:
1309   case BuiltinType::SatULongFract:
1310     return 3;
1311   case BuiltinType::ShortAccum:
1312   case BuiltinType::UShortAccum:
1313   case BuiltinType::SatShortAccum:
1314   case BuiltinType::SatUShortAccum:
1315     return 4;
1316   case BuiltinType::Accum:
1317   case BuiltinType::UAccum:
1318   case BuiltinType::SatAccum:
1319   case BuiltinType::SatUAccum:
1320     return 5;
1321   case BuiltinType::LongAccum:
1322   case BuiltinType::ULongAccum:
1323   case BuiltinType::SatLongAccum:
1324   case BuiltinType::SatULongAccum:
1325     return 6;
1326   default:
1327     if (BTy->isInteger())
1328       return 0;
1329     llvm_unreachable("Unexpected fixed point or integer type");
1330   }
1331 }
1332 
1333 /// handleFixedPointConversion - Fixed point operations between fixed
1334 /// point types and integers or other fixed point types do not fall under
1335 /// usual arithmetic conversion since these conversions could result in loss
1336 /// of precsision (N1169 4.1.4). These operations should be calculated with
1337 /// the full precision of their result type (N1169 4.1.6.2.1).
1338 static QualType handleFixedPointConversion(Sema &S, QualType LHSTy,
1339                                            QualType RHSTy) {
1340   assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) &&
1341          "Expected at least one of the operands to be a fixed point type");
1342   assert((LHSTy->isFixedPointOrIntegerType() ||
1343           RHSTy->isFixedPointOrIntegerType()) &&
1344          "Special fixed point arithmetic operation conversions are only "
1345          "applied to ints or other fixed point types");
1346 
1347   // If one operand has signed fixed-point type and the other operand has
1348   // unsigned fixed-point type, then the unsigned fixed-point operand is
1349   // converted to its corresponding signed fixed-point type and the resulting
1350   // type is the type of the converted operand.
1351   if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType())
1352     LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy);
1353   else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType())
1354     RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy);
1355 
1356   // The result type is the type with the highest rank, whereby a fixed-point
1357   // conversion rank is always greater than an integer conversion rank; if the
1358   // type of either of the operands is a saturating fixedpoint type, the result
1359   // type shall be the saturating fixed-point type corresponding to the type
1360   // with the highest rank; the resulting value is converted (taking into
1361   // account rounding and overflow) to the precision of the resulting type.
1362   // Same ranks between signed and unsigned types are resolved earlier, so both
1363   // types are either signed or both unsigned at this point.
1364   unsigned LHSTyRank = GetFixedPointRank(LHSTy);
1365   unsigned RHSTyRank = GetFixedPointRank(RHSTy);
1366 
1367   QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy;
1368 
1369   if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType())
1370     ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy);
1371 
1372   return ResultTy;
1373 }
1374 
1375 /// Check that the usual arithmetic conversions can be performed on this pair of
1376 /// expressions that might be of enumeration type.
1377 static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS,
1378                                            SourceLocation Loc,
1379                                            Sema::ArithConvKind ACK) {
1380   // C++2a [expr.arith.conv]p1:
1381   //   If one operand is of enumeration type and the other operand is of a
1382   //   different enumeration type or a floating-point type, this behavior is
1383   //   deprecated ([depr.arith.conv.enum]).
1384   //
1385   // Warn on this in all language modes. Produce a deprecation warning in C++20.
1386   // Eventually we will presumably reject these cases (in C++23 onwards?).
1387   QualType L = LHS->getType(), R = RHS->getType();
1388   bool LEnum = L->isUnscopedEnumerationType(),
1389        REnum = R->isUnscopedEnumerationType();
1390   bool IsCompAssign = ACK == Sema::ACK_CompAssign;
1391   if ((!IsCompAssign && LEnum && R->isFloatingType()) ||
1392       (REnum && L->isFloatingType())) {
1393     S.Diag(Loc, S.getLangOpts().CPlusPlus2a
1394                     ? diag::warn_arith_conv_enum_float_cxx2a
1395                     : diag::warn_arith_conv_enum_float)
1396         << LHS->getSourceRange() << RHS->getSourceRange()
1397         << (int)ACK << LEnum << L << R;
1398   } else if (!IsCompAssign && LEnum && REnum &&
1399              !S.Context.hasSameUnqualifiedType(L, R)) {
1400     unsigned DiagID;
1401     if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() ||
1402         !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) {
1403       // If either enumeration type is unnamed, it's less likely that the
1404       // user cares about this, but this situation is still deprecated in
1405       // C++2a. Use a different warning group.
1406       DiagID = S.getLangOpts().CPlusPlus2a
1407                     ? diag::warn_arith_conv_mixed_anon_enum_types_cxx2a
1408                     : diag::warn_arith_conv_mixed_anon_enum_types;
1409     } else if (ACK == Sema::ACK_Conditional) {
1410       // Conditional expressions are separated out because they have
1411       // historically had a different warning flag.
1412       DiagID = S.getLangOpts().CPlusPlus2a
1413                    ? diag::warn_conditional_mixed_enum_types_cxx2a
1414                    : diag::warn_conditional_mixed_enum_types;
1415     } else if (ACK == Sema::ACK_Comparison) {
1416       // Comparison expressions are separated out because they have
1417       // historically had a different warning flag.
1418       DiagID = S.getLangOpts().CPlusPlus2a
1419                    ? diag::warn_comparison_mixed_enum_types_cxx2a
1420                    : diag::warn_comparison_mixed_enum_types;
1421     } else {
1422       DiagID = S.getLangOpts().CPlusPlus2a
1423                    ? diag::warn_arith_conv_mixed_enum_types_cxx2a
1424                    : diag::warn_arith_conv_mixed_enum_types;
1425     }
1426     S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
1427                         << (int)ACK << L << R;
1428   }
1429 }
1430 
1431 /// UsualArithmeticConversions - Performs various conversions that are common to
1432 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1433 /// routine returns the first non-arithmetic type found. The client is
1434 /// responsible for emitting appropriate error diagnostics.
1435 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1436                                           SourceLocation Loc,
1437                                           ArithConvKind ACK) {
1438   checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK);
1439 
1440   if (ACK != ACK_CompAssign) {
1441     LHS = UsualUnaryConversions(LHS.get());
1442     if (LHS.isInvalid())
1443       return QualType();
1444   }
1445 
1446   RHS = UsualUnaryConversions(RHS.get());
1447   if (RHS.isInvalid())
1448     return QualType();
1449 
1450   // For conversion purposes, we ignore any qualifiers.
1451   // For example, "const float" and "float" are equivalent.
1452   QualType LHSType =
1453     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1454   QualType RHSType =
1455     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1456 
1457   // For conversion purposes, we ignore any atomic qualifier on the LHS.
1458   if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1459     LHSType = AtomicLHS->getValueType();
1460 
1461   // If both types are identical, no conversion is needed.
1462   if (LHSType == RHSType)
1463     return LHSType;
1464 
1465   // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1466   // The caller can deal with this (e.g. pointer + int).
1467   if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1468     return QualType();
1469 
1470   // Apply unary and bitfield promotions to the LHS's type.
1471   QualType LHSUnpromotedType = LHSType;
1472   if (LHSType->isPromotableIntegerType())
1473     LHSType = Context.getPromotedIntegerType(LHSType);
1474   QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1475   if (!LHSBitfieldPromoteTy.isNull())
1476     LHSType = LHSBitfieldPromoteTy;
1477   if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign)
1478     LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1479 
1480   // If both types are identical, no conversion is needed.
1481   if (LHSType == RHSType)
1482     return LHSType;
1483 
1484   // At this point, we have two different arithmetic types.
1485 
1486   // Diagnose attempts to convert between __float128 and long double where
1487   // such conversions currently can't be handled.
1488   if (unsupportedTypeConversion(*this, LHSType, RHSType))
1489     return QualType();
1490 
1491   // Handle complex types first (C99 6.3.1.8p1).
1492   if (LHSType->isComplexType() || RHSType->isComplexType())
1493     return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1494                                         ACK == ACK_CompAssign);
1495 
1496   // Now handle "real" floating types (i.e. float, double, long double).
1497   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1498     return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1499                                  ACK == ACK_CompAssign);
1500 
1501   // Handle GCC complex int extension.
1502   if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1503     return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1504                                       ACK == ACK_CompAssign);
1505 
1506   if (LHSType->isFixedPointType() || RHSType->isFixedPointType())
1507     return handleFixedPointConversion(*this, LHSType, RHSType);
1508 
1509   // Finally, we have two differing integer types.
1510   return handleIntegerConversion<doIntegralCast, doIntegralCast>
1511            (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign);
1512 }
1513 
1514 //===----------------------------------------------------------------------===//
1515 //  Semantic Analysis for various Expression Types
1516 //===----------------------------------------------------------------------===//
1517 
1518 
1519 ExprResult
1520 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1521                                 SourceLocation DefaultLoc,
1522                                 SourceLocation RParenLoc,
1523                                 Expr *ControllingExpr,
1524                                 ArrayRef<ParsedType> ArgTypes,
1525                                 ArrayRef<Expr *> ArgExprs) {
1526   unsigned NumAssocs = ArgTypes.size();
1527   assert(NumAssocs == ArgExprs.size());
1528 
1529   TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1530   for (unsigned i = 0; i < NumAssocs; ++i) {
1531     if (ArgTypes[i])
1532       (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1533     else
1534       Types[i] = nullptr;
1535   }
1536 
1537   ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1538                                              ControllingExpr,
1539                                              llvm::makeArrayRef(Types, NumAssocs),
1540                                              ArgExprs);
1541   delete [] Types;
1542   return ER;
1543 }
1544 
1545 ExprResult
1546 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1547                                  SourceLocation DefaultLoc,
1548                                  SourceLocation RParenLoc,
1549                                  Expr *ControllingExpr,
1550                                  ArrayRef<TypeSourceInfo *> Types,
1551                                  ArrayRef<Expr *> Exprs) {
1552   unsigned NumAssocs = Types.size();
1553   assert(NumAssocs == Exprs.size());
1554 
1555   // Decay and strip qualifiers for the controlling expression type, and handle
1556   // placeholder type replacement. See committee discussion from WG14 DR423.
1557   {
1558     EnterExpressionEvaluationContext Unevaluated(
1559         *this, Sema::ExpressionEvaluationContext::Unevaluated);
1560     ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
1561     if (R.isInvalid())
1562       return ExprError();
1563     ControllingExpr = R.get();
1564   }
1565 
1566   // The controlling expression is an unevaluated operand, so side effects are
1567   // likely unintended.
1568   if (!inTemplateInstantiation() &&
1569       ControllingExpr->HasSideEffects(Context, false))
1570     Diag(ControllingExpr->getExprLoc(),
1571          diag::warn_side_effects_unevaluated_context);
1572 
1573   bool TypeErrorFound = false,
1574        IsResultDependent = ControllingExpr->isTypeDependent(),
1575        ContainsUnexpandedParameterPack
1576          = ControllingExpr->containsUnexpandedParameterPack();
1577 
1578   for (unsigned i = 0; i < NumAssocs; ++i) {
1579     if (Exprs[i]->containsUnexpandedParameterPack())
1580       ContainsUnexpandedParameterPack = true;
1581 
1582     if (Types[i]) {
1583       if (Types[i]->getType()->containsUnexpandedParameterPack())
1584         ContainsUnexpandedParameterPack = true;
1585 
1586       if (Types[i]->getType()->isDependentType()) {
1587         IsResultDependent = true;
1588       } else {
1589         // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1590         // complete object type other than a variably modified type."
1591         unsigned D = 0;
1592         if (Types[i]->getType()->isIncompleteType())
1593           D = diag::err_assoc_type_incomplete;
1594         else if (!Types[i]->getType()->isObjectType())
1595           D = diag::err_assoc_type_nonobject;
1596         else if (Types[i]->getType()->isVariablyModifiedType())
1597           D = diag::err_assoc_type_variably_modified;
1598 
1599         if (D != 0) {
1600           Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1601             << Types[i]->getTypeLoc().getSourceRange()
1602             << Types[i]->getType();
1603           TypeErrorFound = true;
1604         }
1605 
1606         // C11 6.5.1.1p2 "No two generic associations in the same generic
1607         // selection shall specify compatible types."
1608         for (unsigned j = i+1; j < NumAssocs; ++j)
1609           if (Types[j] && !Types[j]->getType()->isDependentType() &&
1610               Context.typesAreCompatible(Types[i]->getType(),
1611                                          Types[j]->getType())) {
1612             Diag(Types[j]->getTypeLoc().getBeginLoc(),
1613                  diag::err_assoc_compatible_types)
1614               << Types[j]->getTypeLoc().getSourceRange()
1615               << Types[j]->getType()
1616               << Types[i]->getType();
1617             Diag(Types[i]->getTypeLoc().getBeginLoc(),
1618                  diag::note_compat_assoc)
1619               << Types[i]->getTypeLoc().getSourceRange()
1620               << Types[i]->getType();
1621             TypeErrorFound = true;
1622           }
1623       }
1624     }
1625   }
1626   if (TypeErrorFound)
1627     return ExprError();
1628 
1629   // If we determined that the generic selection is result-dependent, don't
1630   // try to compute the result expression.
1631   if (IsResultDependent)
1632     return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types,
1633                                         Exprs, DefaultLoc, RParenLoc,
1634                                         ContainsUnexpandedParameterPack);
1635 
1636   SmallVector<unsigned, 1> CompatIndices;
1637   unsigned DefaultIndex = -1U;
1638   for (unsigned i = 0; i < NumAssocs; ++i) {
1639     if (!Types[i])
1640       DefaultIndex = i;
1641     else if (Context.typesAreCompatible(ControllingExpr->getType(),
1642                                         Types[i]->getType()))
1643       CompatIndices.push_back(i);
1644   }
1645 
1646   // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1647   // type compatible with at most one of the types named in its generic
1648   // association list."
1649   if (CompatIndices.size() > 1) {
1650     // We strip parens here because the controlling expression is typically
1651     // parenthesized in macro definitions.
1652     ControllingExpr = ControllingExpr->IgnoreParens();
1653     Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match)
1654         << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1655         << (unsigned)CompatIndices.size();
1656     for (unsigned I : CompatIndices) {
1657       Diag(Types[I]->getTypeLoc().getBeginLoc(),
1658            diag::note_compat_assoc)
1659         << Types[I]->getTypeLoc().getSourceRange()
1660         << Types[I]->getType();
1661     }
1662     return ExprError();
1663   }
1664 
1665   // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1666   // its controlling expression shall have type compatible with exactly one of
1667   // the types named in its generic association list."
1668   if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1669     // We strip parens here because the controlling expression is typically
1670     // parenthesized in macro definitions.
1671     ControllingExpr = ControllingExpr->IgnoreParens();
1672     Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match)
1673         << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1674     return ExprError();
1675   }
1676 
1677   // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1678   // type name that is compatible with the type of the controlling expression,
1679   // then the result expression of the generic selection is the expression
1680   // in that generic association. Otherwise, the result expression of the
1681   // generic selection is the expression in the default generic association."
1682   unsigned ResultIndex =
1683     CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1684 
1685   return GenericSelectionExpr::Create(
1686       Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1687       ContainsUnexpandedParameterPack, ResultIndex);
1688 }
1689 
1690 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1691 /// location of the token and the offset of the ud-suffix within it.
1692 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1693                                      unsigned Offset) {
1694   return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1695                                         S.getLangOpts());
1696 }
1697 
1698 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1699 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
1700 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1701                                                  IdentifierInfo *UDSuffix,
1702                                                  SourceLocation UDSuffixLoc,
1703                                                  ArrayRef<Expr*> Args,
1704                                                  SourceLocation LitEndLoc) {
1705   assert(Args.size() <= 2 && "too many arguments for literal operator");
1706 
1707   QualType ArgTy[2];
1708   for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1709     ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1710     if (ArgTy[ArgIdx]->isArrayType())
1711       ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1712   }
1713 
1714   DeclarationName OpName =
1715     S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1716   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1717   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1718 
1719   LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1720   if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1721                               /*AllowRaw*/ false, /*AllowTemplate*/ false,
1722                               /*AllowStringTemplate*/ false,
1723                               /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
1724     return ExprError();
1725 
1726   return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1727 }
1728 
1729 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1730 /// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
1731 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1732 /// multiple tokens.  However, the common case is that StringToks points to one
1733 /// string.
1734 ///
1735 ExprResult
1736 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
1737   assert(!StringToks.empty() && "Must have at least one string!");
1738 
1739   StringLiteralParser Literal(StringToks, PP);
1740   if (Literal.hadError)
1741     return ExprError();
1742 
1743   SmallVector<SourceLocation, 4> StringTokLocs;
1744   for (const Token &Tok : StringToks)
1745     StringTokLocs.push_back(Tok.getLocation());
1746 
1747   QualType CharTy = Context.CharTy;
1748   StringLiteral::StringKind Kind = StringLiteral::Ascii;
1749   if (Literal.isWide()) {
1750     CharTy = Context.getWideCharType();
1751     Kind = StringLiteral::Wide;
1752   } else if (Literal.isUTF8()) {
1753     if (getLangOpts().Char8)
1754       CharTy = Context.Char8Ty;
1755     Kind = StringLiteral::UTF8;
1756   } else if (Literal.isUTF16()) {
1757     CharTy = Context.Char16Ty;
1758     Kind = StringLiteral::UTF16;
1759   } else if (Literal.isUTF32()) {
1760     CharTy = Context.Char32Ty;
1761     Kind = StringLiteral::UTF32;
1762   } else if (Literal.isPascal()) {
1763     CharTy = Context.UnsignedCharTy;
1764   }
1765 
1766   // Warn on initializing an array of char from a u8 string literal; this
1767   // becomes ill-formed in C++2a.
1768   if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus2a &&
1769       !getLangOpts().Char8 && Kind == StringLiteral::UTF8) {
1770     Diag(StringTokLocs.front(), diag::warn_cxx2a_compat_utf8_string);
1771 
1772     // Create removals for all 'u8' prefixes in the string literal(s). This
1773     // ensures C++2a compatibility (but may change the program behavior when
1774     // built by non-Clang compilers for which the execution character set is
1775     // not always UTF-8).
1776     auto RemovalDiag = PDiag(diag::note_cxx2a_compat_utf8_string_remove_u8);
1777     SourceLocation RemovalDiagLoc;
1778     for (const Token &Tok : StringToks) {
1779       if (Tok.getKind() == tok::utf8_string_literal) {
1780         if (RemovalDiagLoc.isInvalid())
1781           RemovalDiagLoc = Tok.getLocation();
1782         RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange(
1783             Tok.getLocation(),
1784             Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2,
1785                                            getSourceManager(), getLangOpts())));
1786       }
1787     }
1788     Diag(RemovalDiagLoc, RemovalDiag);
1789   }
1790 
1791   QualType StrTy =
1792       Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars());
1793 
1794   // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1795   StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1796                                              Kind, Literal.Pascal, StrTy,
1797                                              &StringTokLocs[0],
1798                                              StringTokLocs.size());
1799   if (Literal.getUDSuffix().empty())
1800     return Lit;
1801 
1802   // We're building a user-defined literal.
1803   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1804   SourceLocation UDSuffixLoc =
1805     getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1806                    Literal.getUDSuffixOffset());
1807 
1808   // Make sure we're allowed user-defined literals here.
1809   if (!UDLScope)
1810     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1811 
1812   // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1813   //   operator "" X (str, len)
1814   QualType SizeType = Context.getSizeType();
1815 
1816   DeclarationName OpName =
1817     Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1818   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1819   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1820 
1821   QualType ArgTy[] = {
1822     Context.getArrayDecayedType(StrTy), SizeType
1823   };
1824 
1825   LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1826   switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1827                                 /*AllowRaw*/ false, /*AllowTemplate*/ false,
1828                                 /*AllowStringTemplate*/ true,
1829                                 /*DiagnoseMissing*/ true)) {
1830 
1831   case LOLR_Cooked: {
1832     llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1833     IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1834                                                     StringTokLocs[0]);
1835     Expr *Args[] = { Lit, LenArg };
1836 
1837     return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1838   }
1839 
1840   case LOLR_StringTemplate: {
1841     TemplateArgumentListInfo ExplicitArgs;
1842 
1843     unsigned CharBits = Context.getIntWidth(CharTy);
1844     bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1845     llvm::APSInt Value(CharBits, CharIsUnsigned);
1846 
1847     TemplateArgument TypeArg(CharTy);
1848     TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1849     ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1850 
1851     for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1852       Value = Lit->getCodeUnit(I);
1853       TemplateArgument Arg(Context, Value, CharTy);
1854       TemplateArgumentLocInfo ArgInfo;
1855       ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1856     }
1857     return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1858                                     &ExplicitArgs);
1859   }
1860   case LOLR_Raw:
1861   case LOLR_Template:
1862   case LOLR_ErrorNoDiagnostic:
1863     llvm_unreachable("unexpected literal operator lookup result");
1864   case LOLR_Error:
1865     return ExprError();
1866   }
1867   llvm_unreachable("unexpected literal operator lookup result");
1868 }
1869 
1870 DeclRefExpr *
1871 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1872                        SourceLocation Loc,
1873                        const CXXScopeSpec *SS) {
1874   DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1875   return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1876 }
1877 
1878 DeclRefExpr *
1879 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1880                        const DeclarationNameInfo &NameInfo,
1881                        const CXXScopeSpec *SS, NamedDecl *FoundD,
1882                        SourceLocation TemplateKWLoc,
1883                        const TemplateArgumentListInfo *TemplateArgs) {
1884   NestedNameSpecifierLoc NNS =
1885       SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc();
1886   return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc,
1887                           TemplateArgs);
1888 }
1889 
1890 NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) {
1891   // A declaration named in an unevaluated operand never constitutes an odr-use.
1892   if (isUnevaluatedContext())
1893     return NOUR_Unevaluated;
1894 
1895   // C++2a [basic.def.odr]p4:
1896   //   A variable x whose name appears as a potentially-evaluated expression e
1897   //   is odr-used by e unless [...] x is a reference that is usable in
1898   //   constant expressions.
1899   if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
1900     if (VD->getType()->isReferenceType() &&
1901         !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) &&
1902         VD->isUsableInConstantExpressions(Context))
1903       return NOUR_Constant;
1904   }
1905 
1906   // All remaining non-variable cases constitute an odr-use. For variables, we
1907   // need to wait and see how the expression is used.
1908   return NOUR_None;
1909 }
1910 
1911 /// BuildDeclRefExpr - Build an expression that references a
1912 /// declaration that does not require a closure capture.
1913 DeclRefExpr *
1914 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1915                        const DeclarationNameInfo &NameInfo,
1916                        NestedNameSpecifierLoc NNS, NamedDecl *FoundD,
1917                        SourceLocation TemplateKWLoc,
1918                        const TemplateArgumentListInfo *TemplateArgs) {
1919   bool RefersToCapturedVariable =
1920       isa<VarDecl>(D) &&
1921       NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
1922 
1923   DeclRefExpr *E = DeclRefExpr::Create(
1924       Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty,
1925       VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D));
1926   MarkDeclRefReferenced(E);
1927 
1928   // C++ [except.spec]p17:
1929   //   An exception-specification is considered to be needed when:
1930   //   - in an expression, the function is the unique lookup result or
1931   //     the selected member of a set of overloaded functions.
1932   //
1933   // We delay doing this until after we've built the function reference and
1934   // marked it as used so that:
1935   //  a) if the function is defaulted, we get errors from defining it before /
1936   //     instead of errors from computing its exception specification, and
1937   //  b) if the function is a defaulted comparison, we can use the body we
1938   //     build when defining it as input to the exception specification
1939   //     computation rather than computing a new body.
1940   if (auto *FPT = Ty->getAs<FunctionProtoType>()) {
1941     if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
1942       if (auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT))
1943         E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers()));
1944     }
1945   }
1946 
1947   if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
1948       Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() &&
1949       !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc()))
1950     getCurFunction()->recordUseOfWeak(E);
1951 
1952   FieldDecl *FD = dyn_cast<FieldDecl>(D);
1953   if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
1954     FD = IFD->getAnonField();
1955   if (FD) {
1956     UnusedPrivateFields.remove(FD);
1957     // Just in case we're building an illegal pointer-to-member.
1958     if (FD->isBitField())
1959       E->setObjectKind(OK_BitField);
1960   }
1961 
1962   // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
1963   // designates a bit-field.
1964   if (auto *BD = dyn_cast<BindingDecl>(D))
1965     if (auto *BE = BD->getBinding())
1966       E->setObjectKind(BE->getObjectKind());
1967 
1968   return E;
1969 }
1970 
1971 /// Decomposes the given name into a DeclarationNameInfo, its location, and
1972 /// possibly a list of template arguments.
1973 ///
1974 /// If this produces template arguments, it is permitted to call
1975 /// DecomposeTemplateName.
1976 ///
1977 /// This actually loses a lot of source location information for
1978 /// non-standard name kinds; we should consider preserving that in
1979 /// some way.
1980 void
1981 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1982                              TemplateArgumentListInfo &Buffer,
1983                              DeclarationNameInfo &NameInfo,
1984                              const TemplateArgumentListInfo *&TemplateArgs) {
1985   if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) {
1986     Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1987     Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1988 
1989     ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
1990                                        Id.TemplateId->NumArgs);
1991     translateTemplateArguments(TemplateArgsPtr, Buffer);
1992 
1993     TemplateName TName = Id.TemplateId->Template.get();
1994     SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1995     NameInfo = Context.getNameForTemplate(TName, TNameLoc);
1996     TemplateArgs = &Buffer;
1997   } else {
1998     NameInfo = GetNameFromUnqualifiedId(Id);
1999     TemplateArgs = nullptr;
2000   }
2001 }
2002 
2003 static void emitEmptyLookupTypoDiagnostic(
2004     const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
2005     DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
2006     unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
2007   DeclContext *Ctx =
2008       SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
2009   if (!TC) {
2010     // Emit a special diagnostic for failed member lookups.
2011     // FIXME: computing the declaration context might fail here (?)
2012     if (Ctx)
2013       SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
2014                                                  << SS.getRange();
2015     else
2016       SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
2017     return;
2018   }
2019 
2020   std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
2021   bool DroppedSpecifier =
2022       TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
2023   unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
2024                         ? diag::note_implicit_param_decl
2025                         : diag::note_previous_decl;
2026   if (!Ctx)
2027     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
2028                          SemaRef.PDiag(NoteID));
2029   else
2030     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
2031                                  << Typo << Ctx << DroppedSpecifier
2032                                  << SS.getRange(),
2033                          SemaRef.PDiag(NoteID));
2034 }
2035 
2036 /// Diagnose an empty lookup.
2037 ///
2038 /// \return false if new lookup candidates were found
2039 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
2040                                CorrectionCandidateCallback &CCC,
2041                                TemplateArgumentListInfo *ExplicitTemplateArgs,
2042                                ArrayRef<Expr *> Args, TypoExpr **Out) {
2043   DeclarationName Name = R.getLookupName();
2044 
2045   unsigned diagnostic = diag::err_undeclared_var_use;
2046   unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
2047   if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
2048       Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
2049       Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
2050     diagnostic = diag::err_undeclared_use;
2051     diagnostic_suggest = diag::err_undeclared_use_suggest;
2052   }
2053 
2054   // If the original lookup was an unqualified lookup, fake an
2055   // unqualified lookup.  This is useful when (for example) the
2056   // original lookup would not have found something because it was a
2057   // dependent name.
2058   DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
2059   while (DC) {
2060     if (isa<CXXRecordDecl>(DC)) {
2061       LookupQualifiedName(R, DC);
2062 
2063       if (!R.empty()) {
2064         // Don't give errors about ambiguities in this lookup.
2065         R.suppressDiagnostics();
2066 
2067         // During a default argument instantiation the CurContext points
2068         // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
2069         // function parameter list, hence add an explicit check.
2070         bool isDefaultArgument =
2071             !CodeSynthesisContexts.empty() &&
2072             CodeSynthesisContexts.back().Kind ==
2073                 CodeSynthesisContext::DefaultFunctionArgumentInstantiation;
2074         CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
2075         bool isInstance = CurMethod &&
2076                           CurMethod->isInstance() &&
2077                           DC == CurMethod->getParent() && !isDefaultArgument;
2078 
2079         // Give a code modification hint to insert 'this->'.
2080         // TODO: fixit for inserting 'Base<T>::' in the other cases.
2081         // Actually quite difficult!
2082         if (getLangOpts().MSVCCompat)
2083           diagnostic = diag::ext_found_via_dependent_bases_lookup;
2084         if (isInstance) {
2085           Diag(R.getNameLoc(), diagnostic) << Name
2086             << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
2087           CheckCXXThisCapture(R.getNameLoc());
2088         } else {
2089           Diag(R.getNameLoc(), diagnostic) << Name;
2090         }
2091 
2092         // Do we really want to note all of these?
2093         for (NamedDecl *D : R)
2094           Diag(D->getLocation(), diag::note_dependent_var_use);
2095 
2096         // Return true if we are inside a default argument instantiation
2097         // and the found name refers to an instance member function, otherwise
2098         // the function calling DiagnoseEmptyLookup will try to create an
2099         // implicit member call and this is wrong for default argument.
2100         if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
2101           Diag(R.getNameLoc(), diag::err_member_call_without_object);
2102           return true;
2103         }
2104 
2105         // Tell the callee to try to recover.
2106         return false;
2107       }
2108 
2109       R.clear();
2110     }
2111 
2112     DC = DC->getLookupParent();
2113   }
2114 
2115   // We didn't find anything, so try to correct for a typo.
2116   TypoCorrection Corrected;
2117   if (S && Out) {
2118     SourceLocation TypoLoc = R.getNameLoc();
2119     assert(!ExplicitTemplateArgs &&
2120            "Diagnosing an empty lookup with explicit template args!");
2121     *Out = CorrectTypoDelayed(
2122         R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
2123         [=](const TypoCorrection &TC) {
2124           emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
2125                                         diagnostic, diagnostic_suggest);
2126         },
2127         nullptr, CTK_ErrorRecovery);
2128     if (*Out)
2129       return true;
2130   } else if (S &&
2131              (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
2132                                       S, &SS, CCC, CTK_ErrorRecovery))) {
2133     std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
2134     bool DroppedSpecifier =
2135         Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
2136     R.setLookupName(Corrected.getCorrection());
2137 
2138     bool AcceptableWithRecovery = false;
2139     bool AcceptableWithoutRecovery = false;
2140     NamedDecl *ND = Corrected.getFoundDecl();
2141     if (ND) {
2142       if (Corrected.isOverloaded()) {
2143         OverloadCandidateSet OCS(R.getNameLoc(),
2144                                  OverloadCandidateSet::CSK_Normal);
2145         OverloadCandidateSet::iterator Best;
2146         for (NamedDecl *CD : Corrected) {
2147           if (FunctionTemplateDecl *FTD =
2148                    dyn_cast<FunctionTemplateDecl>(CD))
2149             AddTemplateOverloadCandidate(
2150                 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
2151                 Args, OCS);
2152           else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
2153             if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
2154               AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
2155                                    Args, OCS);
2156         }
2157         switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
2158         case OR_Success:
2159           ND = Best->FoundDecl;
2160           Corrected.setCorrectionDecl(ND);
2161           break;
2162         default:
2163           // FIXME: Arbitrarily pick the first declaration for the note.
2164           Corrected.setCorrectionDecl(ND);
2165           break;
2166         }
2167       }
2168       R.addDecl(ND);
2169       if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2170         CXXRecordDecl *Record = nullptr;
2171         if (Corrected.getCorrectionSpecifier()) {
2172           const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
2173           Record = Ty->getAsCXXRecordDecl();
2174         }
2175         if (!Record)
2176           Record = cast<CXXRecordDecl>(
2177               ND->getDeclContext()->getRedeclContext());
2178         R.setNamingClass(Record);
2179       }
2180 
2181       auto *UnderlyingND = ND->getUnderlyingDecl();
2182       AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2183                                isa<FunctionTemplateDecl>(UnderlyingND);
2184       // FIXME: If we ended up with a typo for a type name or
2185       // Objective-C class name, we're in trouble because the parser
2186       // is in the wrong place to recover. Suggest the typo
2187       // correction, but don't make it a fix-it since we're not going
2188       // to recover well anyway.
2189       AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) ||
2190                                   getAsTypeTemplateDecl(UnderlyingND) ||
2191                                   isa<ObjCInterfaceDecl>(UnderlyingND);
2192     } else {
2193       // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2194       // because we aren't able to recover.
2195       AcceptableWithoutRecovery = true;
2196     }
2197 
2198     if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2199       unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2200                             ? diag::note_implicit_param_decl
2201                             : diag::note_previous_decl;
2202       if (SS.isEmpty())
2203         diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
2204                      PDiag(NoteID), AcceptableWithRecovery);
2205       else
2206         diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
2207                                   << Name << computeDeclContext(SS, false)
2208                                   << DroppedSpecifier << SS.getRange(),
2209                      PDiag(NoteID), AcceptableWithRecovery);
2210 
2211       // Tell the callee whether to try to recover.
2212       return !AcceptableWithRecovery;
2213     }
2214   }
2215   R.clear();
2216 
2217   // Emit a special diagnostic for failed member lookups.
2218   // FIXME: computing the declaration context might fail here (?)
2219   if (!SS.isEmpty()) {
2220     Diag(R.getNameLoc(), diag::err_no_member)
2221       << Name << computeDeclContext(SS, false)
2222       << SS.getRange();
2223     return true;
2224   }
2225 
2226   // Give up, we can't recover.
2227   Diag(R.getNameLoc(), diagnostic) << Name;
2228   return true;
2229 }
2230 
2231 /// In Microsoft mode, if we are inside a template class whose parent class has
2232 /// dependent base classes, and we can't resolve an unqualified identifier, then
2233 /// assume the identifier is a member of a dependent base class.  We can only
2234 /// recover successfully in static methods, instance methods, and other contexts
2235 /// where 'this' is available.  This doesn't precisely match MSVC's
2236 /// instantiation model, but it's close enough.
2237 static Expr *
2238 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
2239                                DeclarationNameInfo &NameInfo,
2240                                SourceLocation TemplateKWLoc,
2241                                const TemplateArgumentListInfo *TemplateArgs) {
2242   // Only try to recover from lookup into dependent bases in static methods or
2243   // contexts where 'this' is available.
2244   QualType ThisType = S.getCurrentThisType();
2245   const CXXRecordDecl *RD = nullptr;
2246   if (!ThisType.isNull())
2247     RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2248   else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2249     RD = MD->getParent();
2250   if (!RD || !RD->hasAnyDependentBases())
2251     return nullptr;
2252 
2253   // Diagnose this as unqualified lookup into a dependent base class.  If 'this'
2254   // is available, suggest inserting 'this->' as a fixit.
2255   SourceLocation Loc = NameInfo.getLoc();
2256   auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2257   DB << NameInfo.getName() << RD;
2258 
2259   if (!ThisType.isNull()) {
2260     DB << FixItHint::CreateInsertion(Loc, "this->");
2261     return CXXDependentScopeMemberExpr::Create(
2262         Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2263         /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2264         /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
2265   }
2266 
2267   // Synthesize a fake NNS that points to the derived class.  This will
2268   // perform name lookup during template instantiation.
2269   CXXScopeSpec SS;
2270   auto *NNS =
2271       NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2272   SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2273   return DependentScopeDeclRefExpr::Create(
2274       Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2275       TemplateArgs);
2276 }
2277 
2278 ExprResult
2279 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2280                         SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2281                         bool HasTrailingLParen, bool IsAddressOfOperand,
2282                         CorrectionCandidateCallback *CCC,
2283                         bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2284   assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2285          "cannot be direct & operand and have a trailing lparen");
2286   if (SS.isInvalid())
2287     return ExprError();
2288 
2289   TemplateArgumentListInfo TemplateArgsBuffer;
2290 
2291   // Decompose the UnqualifiedId into the following data.
2292   DeclarationNameInfo NameInfo;
2293   const TemplateArgumentListInfo *TemplateArgs;
2294   DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2295 
2296   DeclarationName Name = NameInfo.getName();
2297   IdentifierInfo *II = Name.getAsIdentifierInfo();
2298   SourceLocation NameLoc = NameInfo.getLoc();
2299 
2300   if (II && II->isEditorPlaceholder()) {
2301     // FIXME: When typed placeholders are supported we can create a typed
2302     // placeholder expression node.
2303     return ExprError();
2304   }
2305 
2306   // C++ [temp.dep.expr]p3:
2307   //   An id-expression is type-dependent if it contains:
2308   //     -- an identifier that was declared with a dependent type,
2309   //        (note: handled after lookup)
2310   //     -- a template-id that is dependent,
2311   //        (note: handled in BuildTemplateIdExpr)
2312   //     -- a conversion-function-id that specifies a dependent type,
2313   //     -- a nested-name-specifier that contains a class-name that
2314   //        names a dependent type.
2315   // Determine whether this is a member of an unknown specialization;
2316   // we need to handle these differently.
2317   bool DependentID = false;
2318   if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2319       Name.getCXXNameType()->isDependentType()) {
2320     DependentID = true;
2321   } else if (SS.isSet()) {
2322     if (DeclContext *DC = computeDeclContext(SS, false)) {
2323       if (RequireCompleteDeclContext(SS, DC))
2324         return ExprError();
2325     } else {
2326       DependentID = true;
2327     }
2328   }
2329 
2330   if (DependentID)
2331     return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2332                                       IsAddressOfOperand, TemplateArgs);
2333 
2334   // Perform the required lookup.
2335   LookupResult R(*this, NameInfo,
2336                  (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam)
2337                      ? LookupObjCImplicitSelfParam
2338                      : LookupOrdinaryName);
2339   if (TemplateKWLoc.isValid() || TemplateArgs) {
2340     // Lookup the template name again to correctly establish the context in
2341     // which it was found. This is really unfortunate as we already did the
2342     // lookup to determine that it was a template name in the first place. If
2343     // this becomes a performance hit, we can work harder to preserve those
2344     // results until we get here but it's likely not worth it.
2345     bool MemberOfUnknownSpecialization;
2346     AssumedTemplateKind AssumedTemplate;
2347     if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2348                            MemberOfUnknownSpecialization, TemplateKWLoc,
2349                            &AssumedTemplate))
2350       return ExprError();
2351 
2352     if (MemberOfUnknownSpecialization ||
2353         (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2354       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2355                                         IsAddressOfOperand, TemplateArgs);
2356   } else {
2357     bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2358     LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2359 
2360     // If the result might be in a dependent base class, this is a dependent
2361     // id-expression.
2362     if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2363       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2364                                         IsAddressOfOperand, TemplateArgs);
2365 
2366     // If this reference is in an Objective-C method, then we need to do
2367     // some special Objective-C lookup, too.
2368     if (IvarLookupFollowUp) {
2369       ExprResult E(LookupInObjCMethod(R, S, II, true));
2370       if (E.isInvalid())
2371         return ExprError();
2372 
2373       if (Expr *Ex = E.getAs<Expr>())
2374         return Ex;
2375     }
2376   }
2377 
2378   if (R.isAmbiguous())
2379     return ExprError();
2380 
2381   // This could be an implicitly declared function reference (legal in C90,
2382   // extension in C99, forbidden in C++).
2383   if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2384     NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2385     if (D) R.addDecl(D);
2386   }
2387 
2388   // Determine whether this name might be a candidate for
2389   // argument-dependent lookup.
2390   bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2391 
2392   if (R.empty() && !ADL) {
2393     if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2394       if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2395                                                    TemplateKWLoc, TemplateArgs))
2396         return E;
2397     }
2398 
2399     // Don't diagnose an empty lookup for inline assembly.
2400     if (IsInlineAsmIdentifier)
2401       return ExprError();
2402 
2403     // If this name wasn't predeclared and if this is not a function
2404     // call, diagnose the problem.
2405     TypoExpr *TE = nullptr;
2406     DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep()
2407                                                        : nullptr);
2408     DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;
2409     assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2410            "Typo correction callback misconfigured");
2411     if (CCC) {
2412       // Make sure the callback knows what the typo being diagnosed is.
2413       CCC->setTypoName(II);
2414       if (SS.isValid())
2415         CCC->setTypoNNS(SS.getScopeRep());
2416     }
2417     // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2418     // a template name, but we happen to have always already looked up the name
2419     // before we get here if it must be a template name.
2420     if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr,
2421                             None, &TE)) {
2422       if (TE && KeywordReplacement) {
2423         auto &State = getTypoExprState(TE);
2424         auto BestTC = State.Consumer->getNextCorrection();
2425         if (BestTC.isKeyword()) {
2426           auto *II = BestTC.getCorrectionAsIdentifierInfo();
2427           if (State.DiagHandler)
2428             State.DiagHandler(BestTC);
2429           KeywordReplacement->startToken();
2430           KeywordReplacement->setKind(II->getTokenID());
2431           KeywordReplacement->setIdentifierInfo(II);
2432           KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2433           // Clean up the state associated with the TypoExpr, since it has
2434           // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2435           clearDelayedTypo(TE);
2436           // Signal that a correction to a keyword was performed by returning a
2437           // valid-but-null ExprResult.
2438           return (Expr*)nullptr;
2439         }
2440         State.Consumer->resetCorrectionStream();
2441       }
2442       return TE ? TE : ExprError();
2443     }
2444 
2445     assert(!R.empty() &&
2446            "DiagnoseEmptyLookup returned false but added no results");
2447 
2448     // If we found an Objective-C instance variable, let
2449     // LookupInObjCMethod build the appropriate expression to
2450     // reference the ivar.
2451     if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2452       R.clear();
2453       ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2454       // In a hopelessly buggy code, Objective-C instance variable
2455       // lookup fails and no expression will be built to reference it.
2456       if (!E.isInvalid() && !E.get())
2457         return ExprError();
2458       return E;
2459     }
2460   }
2461 
2462   // This is guaranteed from this point on.
2463   assert(!R.empty() || ADL);
2464 
2465   // Check whether this might be a C++ implicit instance member access.
2466   // C++ [class.mfct.non-static]p3:
2467   //   When an id-expression that is not part of a class member access
2468   //   syntax and not used to form a pointer to member is used in the
2469   //   body of a non-static member function of class X, if name lookup
2470   //   resolves the name in the id-expression to a non-static non-type
2471   //   member of some class C, the id-expression is transformed into a
2472   //   class member access expression using (*this) as the
2473   //   postfix-expression to the left of the . operator.
2474   //
2475   // But we don't actually need to do this for '&' operands if R
2476   // resolved to a function or overloaded function set, because the
2477   // expression is ill-formed if it actually works out to be a
2478   // non-static member function:
2479   //
2480   // C++ [expr.ref]p4:
2481   //   Otherwise, if E1.E2 refers to a non-static member function. . .
2482   //   [t]he expression can be used only as the left-hand operand of a
2483   //   member function call.
2484   //
2485   // There are other safeguards against such uses, but it's important
2486   // to get this right here so that we don't end up making a
2487   // spuriously dependent expression if we're inside a dependent
2488   // instance method.
2489   if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2490     bool MightBeImplicitMember;
2491     if (!IsAddressOfOperand)
2492       MightBeImplicitMember = true;
2493     else if (!SS.isEmpty())
2494       MightBeImplicitMember = false;
2495     else if (R.isOverloadedResult())
2496       MightBeImplicitMember = false;
2497     else if (R.isUnresolvableResult())
2498       MightBeImplicitMember = true;
2499     else
2500       MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2501                               isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2502                               isa<MSPropertyDecl>(R.getFoundDecl());
2503 
2504     if (MightBeImplicitMember)
2505       return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2506                                              R, TemplateArgs, S);
2507   }
2508 
2509   if (TemplateArgs || TemplateKWLoc.isValid()) {
2510 
2511     // In C++1y, if this is a variable template id, then check it
2512     // in BuildTemplateIdExpr().
2513     // The single lookup result must be a variable template declaration.
2514     if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId &&
2515         Id.TemplateId->Kind == TNK_Var_template) {
2516       assert(R.getAsSingle<VarTemplateDecl>() &&
2517              "There should only be one declaration found.");
2518     }
2519 
2520     return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2521   }
2522 
2523   return BuildDeclarationNameExpr(SS, R, ADL);
2524 }
2525 
2526 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2527 /// declaration name, generally during template instantiation.
2528 /// There's a large number of things which don't need to be done along
2529 /// this path.
2530 ExprResult Sema::BuildQualifiedDeclarationNameExpr(
2531     CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2532     bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2533   DeclContext *DC = computeDeclContext(SS, false);
2534   if (!DC)
2535     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2536                                      NameInfo, /*TemplateArgs=*/nullptr);
2537 
2538   if (RequireCompleteDeclContext(SS, DC))
2539     return ExprError();
2540 
2541   LookupResult R(*this, NameInfo, LookupOrdinaryName);
2542   LookupQualifiedName(R, DC);
2543 
2544   if (R.isAmbiguous())
2545     return ExprError();
2546 
2547   if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2548     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2549                                      NameInfo, /*TemplateArgs=*/nullptr);
2550 
2551   if (R.empty()) {
2552     Diag(NameInfo.getLoc(), diag::err_no_member)
2553       << NameInfo.getName() << DC << SS.getRange();
2554     return ExprError();
2555   }
2556 
2557   if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2558     // Diagnose a missing typename if this resolved unambiguously to a type in
2559     // a dependent context.  If we can recover with a type, downgrade this to
2560     // a warning in Microsoft compatibility mode.
2561     unsigned DiagID = diag::err_typename_missing;
2562     if (RecoveryTSI && getLangOpts().MSVCCompat)
2563       DiagID = diag::ext_typename_missing;
2564     SourceLocation Loc = SS.getBeginLoc();
2565     auto D = Diag(Loc, DiagID);
2566     D << SS.getScopeRep() << NameInfo.getName().getAsString()
2567       << SourceRange(Loc, NameInfo.getEndLoc());
2568 
2569     // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2570     // context.
2571     if (!RecoveryTSI)
2572       return ExprError();
2573 
2574     // Only issue the fixit if we're prepared to recover.
2575     D << FixItHint::CreateInsertion(Loc, "typename ");
2576 
2577     // Recover by pretending this was an elaborated type.
2578     QualType Ty = Context.getTypeDeclType(TD);
2579     TypeLocBuilder TLB;
2580     TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2581 
2582     QualType ET = getElaboratedType(ETK_None, SS, Ty);
2583     ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2584     QTL.setElaboratedKeywordLoc(SourceLocation());
2585     QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2586 
2587     *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2588 
2589     return ExprEmpty();
2590   }
2591 
2592   // Defend against this resolving to an implicit member access. We usually
2593   // won't get here if this might be a legitimate a class member (we end up in
2594   // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2595   // a pointer-to-member or in an unevaluated context in C++11.
2596   if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2597     return BuildPossibleImplicitMemberExpr(SS,
2598                                            /*TemplateKWLoc=*/SourceLocation(),
2599                                            R, /*TemplateArgs=*/nullptr, S);
2600 
2601   return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2602 }
2603 
2604 /// The parser has read a name in, and Sema has detected that we're currently
2605 /// inside an ObjC method. Perform some additional checks and determine if we
2606 /// should form a reference to an ivar.
2607 ///
2608 /// Ideally, most of this would be done by lookup, but there's
2609 /// actually quite a lot of extra work involved.
2610 DeclResult Sema::LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S,
2611                                         IdentifierInfo *II) {
2612   SourceLocation Loc = Lookup.getNameLoc();
2613   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2614 
2615   // Check for error condition which is already reported.
2616   if (!CurMethod)
2617     return DeclResult(true);
2618 
2619   // There are two cases to handle here.  1) scoped lookup could have failed,
2620   // in which case we should look for an ivar.  2) scoped lookup could have
2621   // found a decl, but that decl is outside the current instance method (i.e.
2622   // a global variable).  In these two cases, we do a lookup for an ivar with
2623   // this name, if the lookup sucedes, we replace it our current decl.
2624 
2625   // If we're in a class method, we don't normally want to look for
2626   // ivars.  But if we don't find anything else, and there's an
2627   // ivar, that's an error.
2628   bool IsClassMethod = CurMethod->isClassMethod();
2629 
2630   bool LookForIvars;
2631   if (Lookup.empty())
2632     LookForIvars = true;
2633   else if (IsClassMethod)
2634     LookForIvars = false;
2635   else
2636     LookForIvars = (Lookup.isSingleResult() &&
2637                     Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2638   ObjCInterfaceDecl *IFace = nullptr;
2639   if (LookForIvars) {
2640     IFace = CurMethod->getClassInterface();
2641     ObjCInterfaceDecl *ClassDeclared;
2642     ObjCIvarDecl *IV = nullptr;
2643     if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2644       // Diagnose using an ivar in a class method.
2645       if (IsClassMethod) {
2646         Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
2647         return DeclResult(true);
2648       }
2649 
2650       // Diagnose the use of an ivar outside of the declaring class.
2651       if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2652           !declaresSameEntity(ClassDeclared, IFace) &&
2653           !getLangOpts().DebuggerSupport)
2654         Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
2655 
2656       // Success.
2657       return IV;
2658     }
2659   } else if (CurMethod->isInstanceMethod()) {
2660     // We should warn if a local variable hides an ivar.
2661     if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2662       ObjCInterfaceDecl *ClassDeclared;
2663       if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2664         if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2665             declaresSameEntity(IFace, ClassDeclared))
2666           Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2667       }
2668     }
2669   } else if (Lookup.isSingleResult() &&
2670              Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2671     // If accessing a stand-alone ivar in a class method, this is an error.
2672     if (const ObjCIvarDecl *IV =
2673             dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) {
2674       Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
2675       return DeclResult(true);
2676     }
2677   }
2678 
2679   // Didn't encounter an error, didn't find an ivar.
2680   return DeclResult(false);
2681 }
2682 
2683 ExprResult Sema::BuildIvarRefExpr(Scope *S, SourceLocation Loc,
2684                                   ObjCIvarDecl *IV) {
2685   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2686   assert(CurMethod && CurMethod->isInstanceMethod() &&
2687          "should not reference ivar from this context");
2688 
2689   ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
2690   assert(IFace && "should not reference ivar from this context");
2691 
2692   // If we're referencing an invalid decl, just return this as a silent
2693   // error node.  The error diagnostic was already emitted on the decl.
2694   if (IV->isInvalidDecl())
2695     return ExprError();
2696 
2697   // Check if referencing a field with __attribute__((deprecated)).
2698   if (DiagnoseUseOfDecl(IV, Loc))
2699     return ExprError();
2700 
2701   // FIXME: This should use a new expr for a direct reference, don't
2702   // turn this into Self->ivar, just return a BareIVarExpr or something.
2703   IdentifierInfo &II = Context.Idents.get("self");
2704   UnqualifiedId SelfName;
2705   SelfName.setIdentifier(&II, SourceLocation());
2706   SelfName.setKind(UnqualifiedIdKind::IK_ImplicitSelfParam);
2707   CXXScopeSpec SelfScopeSpec;
2708   SourceLocation TemplateKWLoc;
2709   ExprResult SelfExpr =
2710       ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName,
2711                         /*HasTrailingLParen=*/false,
2712                         /*IsAddressOfOperand=*/false);
2713   if (SelfExpr.isInvalid())
2714     return ExprError();
2715 
2716   SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2717   if (SelfExpr.isInvalid())
2718     return ExprError();
2719 
2720   MarkAnyDeclReferenced(Loc, IV, true);
2721 
2722   ObjCMethodFamily MF = CurMethod->getMethodFamily();
2723   if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2724       !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2725     Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2726 
2727   ObjCIvarRefExpr *Result = new (Context)
2728       ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2729                       IV->getLocation(), SelfExpr.get(), true, true);
2730 
2731   if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2732     if (!isUnevaluatedContext() &&
2733         !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2734       getCurFunction()->recordUseOfWeak(Result);
2735   }
2736   if (getLangOpts().ObjCAutoRefCount)
2737     if (const BlockDecl *BD = CurContext->getInnermostBlockDecl())
2738       ImplicitlyRetainedSelfLocs.push_back({Loc, BD});
2739 
2740   return Result;
2741 }
2742 
2743 /// The parser has read a name in, and Sema has detected that we're currently
2744 /// inside an ObjC method. Perform some additional checks and determine if we
2745 /// should form a reference to an ivar. If so, build an expression referencing
2746 /// that ivar.
2747 ExprResult
2748 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2749                          IdentifierInfo *II, bool AllowBuiltinCreation) {
2750   // FIXME: Integrate this lookup step into LookupParsedName.
2751   DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II);
2752   if (Ivar.isInvalid())
2753     return ExprError();
2754   if (Ivar.isUsable())
2755     return BuildIvarRefExpr(S, Lookup.getNameLoc(),
2756                             cast<ObjCIvarDecl>(Ivar.get()));
2757 
2758   if (Lookup.empty() && II && AllowBuiltinCreation)
2759     LookupBuiltin(Lookup);
2760 
2761   // Sentinel value saying that we didn't do anything special.
2762   return ExprResult(false);
2763 }
2764 
2765 /// Cast a base object to a member's actual type.
2766 ///
2767 /// Logically this happens in three phases:
2768 ///
2769 /// * First we cast from the base type to the naming class.
2770 ///   The naming class is the class into which we were looking
2771 ///   when we found the member;  it's the qualifier type if a
2772 ///   qualifier was provided, and otherwise it's the base type.
2773 ///
2774 /// * Next we cast from the naming class to the declaring class.
2775 ///   If the member we found was brought into a class's scope by
2776 ///   a using declaration, this is that class;  otherwise it's
2777 ///   the class declaring the member.
2778 ///
2779 /// * Finally we cast from the declaring class to the "true"
2780 ///   declaring class of the member.  This conversion does not
2781 ///   obey access control.
2782 ExprResult
2783 Sema::PerformObjectMemberConversion(Expr *From,
2784                                     NestedNameSpecifier *Qualifier,
2785                                     NamedDecl *FoundDecl,
2786                                     NamedDecl *Member) {
2787   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2788   if (!RD)
2789     return From;
2790 
2791   QualType DestRecordType;
2792   QualType DestType;
2793   QualType FromRecordType;
2794   QualType FromType = From->getType();
2795   bool PointerConversions = false;
2796   if (isa<FieldDecl>(Member)) {
2797     DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2798     auto FromPtrType = FromType->getAs<PointerType>();
2799     DestRecordType = Context.getAddrSpaceQualType(
2800         DestRecordType, FromPtrType
2801                             ? FromType->getPointeeType().getAddressSpace()
2802                             : FromType.getAddressSpace());
2803 
2804     if (FromPtrType) {
2805       DestType = Context.getPointerType(DestRecordType);
2806       FromRecordType = FromPtrType->getPointeeType();
2807       PointerConversions = true;
2808     } else {
2809       DestType = DestRecordType;
2810       FromRecordType = FromType;
2811     }
2812   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2813     if (Method->isStatic())
2814       return From;
2815 
2816     DestType = Method->getThisType();
2817     DestRecordType = DestType->getPointeeType();
2818 
2819     if (FromType->getAs<PointerType>()) {
2820       FromRecordType = FromType->getPointeeType();
2821       PointerConversions = true;
2822     } else {
2823       FromRecordType = FromType;
2824       DestType = DestRecordType;
2825     }
2826 
2827     LangAS FromAS = FromRecordType.getAddressSpace();
2828     LangAS DestAS = DestRecordType.getAddressSpace();
2829     if (FromAS != DestAS) {
2830       QualType FromRecordTypeWithoutAS =
2831           Context.removeAddrSpaceQualType(FromRecordType);
2832       QualType FromTypeWithDestAS =
2833           Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS);
2834       if (PointerConversions)
2835         FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS);
2836       From = ImpCastExprToType(From, FromTypeWithDestAS,
2837                                CK_AddressSpaceConversion, From->getValueKind())
2838                  .get();
2839     }
2840   } else {
2841     // No conversion necessary.
2842     return From;
2843   }
2844 
2845   if (DestType->isDependentType() || FromType->isDependentType())
2846     return From;
2847 
2848   // If the unqualified types are the same, no conversion is necessary.
2849   if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2850     return From;
2851 
2852   SourceRange FromRange = From->getSourceRange();
2853   SourceLocation FromLoc = FromRange.getBegin();
2854 
2855   ExprValueKind VK = From->getValueKind();
2856 
2857   // C++ [class.member.lookup]p8:
2858   //   [...] Ambiguities can often be resolved by qualifying a name with its
2859   //   class name.
2860   //
2861   // If the member was a qualified name and the qualified referred to a
2862   // specific base subobject type, we'll cast to that intermediate type
2863   // first and then to the object in which the member is declared. That allows
2864   // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2865   //
2866   //   class Base { public: int x; };
2867   //   class Derived1 : public Base { };
2868   //   class Derived2 : public Base { };
2869   //   class VeryDerived : public Derived1, public Derived2 { void f(); };
2870   //
2871   //   void VeryDerived::f() {
2872   //     x = 17; // error: ambiguous base subobjects
2873   //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
2874   //   }
2875   if (Qualifier && Qualifier->getAsType()) {
2876     QualType QType = QualType(Qualifier->getAsType(), 0);
2877     assert(QType->isRecordType() && "lookup done with non-record type");
2878 
2879     QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2880 
2881     // In C++98, the qualifier type doesn't actually have to be a base
2882     // type of the object type, in which case we just ignore it.
2883     // Otherwise build the appropriate casts.
2884     if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
2885       CXXCastPath BasePath;
2886       if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2887                                        FromLoc, FromRange, &BasePath))
2888         return ExprError();
2889 
2890       if (PointerConversions)
2891         QType = Context.getPointerType(QType);
2892       From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2893                                VK, &BasePath).get();
2894 
2895       FromType = QType;
2896       FromRecordType = QRecordType;
2897 
2898       // If the qualifier type was the same as the destination type,
2899       // we're done.
2900       if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2901         return From;
2902     }
2903   }
2904 
2905   bool IgnoreAccess = false;
2906 
2907   // If we actually found the member through a using declaration, cast
2908   // down to the using declaration's type.
2909   //
2910   // Pointer equality is fine here because only one declaration of a
2911   // class ever has member declarations.
2912   if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2913     assert(isa<UsingShadowDecl>(FoundDecl));
2914     QualType URecordType = Context.getTypeDeclType(
2915                            cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2916 
2917     // We only need to do this if the naming-class to declaring-class
2918     // conversion is non-trivial.
2919     if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2920       assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType));
2921       CXXCastPath BasePath;
2922       if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2923                                        FromLoc, FromRange, &BasePath))
2924         return ExprError();
2925 
2926       QualType UType = URecordType;
2927       if (PointerConversions)
2928         UType = Context.getPointerType(UType);
2929       From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2930                                VK, &BasePath).get();
2931       FromType = UType;
2932       FromRecordType = URecordType;
2933     }
2934 
2935     // We don't do access control for the conversion from the
2936     // declaring class to the true declaring class.
2937     IgnoreAccess = true;
2938   }
2939 
2940   CXXCastPath BasePath;
2941   if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2942                                    FromLoc, FromRange, &BasePath,
2943                                    IgnoreAccess))
2944     return ExprError();
2945 
2946   return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2947                            VK, &BasePath);
2948 }
2949 
2950 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2951                                       const LookupResult &R,
2952                                       bool HasTrailingLParen) {
2953   // Only when used directly as the postfix-expression of a call.
2954   if (!HasTrailingLParen)
2955     return false;
2956 
2957   // Never if a scope specifier was provided.
2958   if (SS.isSet())
2959     return false;
2960 
2961   // Only in C++ or ObjC++.
2962   if (!getLangOpts().CPlusPlus)
2963     return false;
2964 
2965   // Turn off ADL when we find certain kinds of declarations during
2966   // normal lookup:
2967   for (NamedDecl *D : R) {
2968     // C++0x [basic.lookup.argdep]p3:
2969     //     -- a declaration of a class member
2970     // Since using decls preserve this property, we check this on the
2971     // original decl.
2972     if (D->isCXXClassMember())
2973       return false;
2974 
2975     // C++0x [basic.lookup.argdep]p3:
2976     //     -- a block-scope function declaration that is not a
2977     //        using-declaration
2978     // NOTE: we also trigger this for function templates (in fact, we
2979     // don't check the decl type at all, since all other decl types
2980     // turn off ADL anyway).
2981     if (isa<UsingShadowDecl>(D))
2982       D = cast<UsingShadowDecl>(D)->getTargetDecl();
2983     else if (D->getLexicalDeclContext()->isFunctionOrMethod())
2984       return false;
2985 
2986     // C++0x [basic.lookup.argdep]p3:
2987     //     -- a declaration that is neither a function or a function
2988     //        template
2989     // And also for builtin functions.
2990     if (isa<FunctionDecl>(D)) {
2991       FunctionDecl *FDecl = cast<FunctionDecl>(D);
2992 
2993       // But also builtin functions.
2994       if (FDecl->getBuiltinID() && FDecl->isImplicit())
2995         return false;
2996     } else if (!isa<FunctionTemplateDecl>(D))
2997       return false;
2998   }
2999 
3000   return true;
3001 }
3002 
3003 
3004 /// Diagnoses obvious problems with the use of the given declaration
3005 /// as an expression.  This is only actually called for lookups that
3006 /// were not overloaded, and it doesn't promise that the declaration
3007 /// will in fact be used.
3008 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
3009   if (D->isInvalidDecl())
3010     return true;
3011 
3012   if (isa<TypedefNameDecl>(D)) {
3013     S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
3014     return true;
3015   }
3016 
3017   if (isa<ObjCInterfaceDecl>(D)) {
3018     S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
3019     return true;
3020   }
3021 
3022   if (isa<NamespaceDecl>(D)) {
3023     S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
3024     return true;
3025   }
3026 
3027   return false;
3028 }
3029 
3030 // Certain multiversion types should be treated as overloaded even when there is
3031 // only one result.
3032 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) {
3033   assert(R.isSingleResult() && "Expected only a single result");
3034   const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
3035   return FD &&
3036          (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
3037 }
3038 
3039 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
3040                                           LookupResult &R, bool NeedsADL,
3041                                           bool AcceptInvalidDecl) {
3042   // If this is a single, fully-resolved result and we don't need ADL,
3043   // just build an ordinary singleton decl ref.
3044   if (!NeedsADL && R.isSingleResult() &&
3045       !R.getAsSingle<FunctionTemplateDecl>() &&
3046       !ShouldLookupResultBeMultiVersionOverload(R))
3047     return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
3048                                     R.getRepresentativeDecl(), nullptr,
3049                                     AcceptInvalidDecl);
3050 
3051   // We only need to check the declaration if there's exactly one
3052   // result, because in the overloaded case the results can only be
3053   // functions and function templates.
3054   if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) &&
3055       CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
3056     return ExprError();
3057 
3058   // Otherwise, just build an unresolved lookup expression.  Suppress
3059   // any lookup-related diagnostics; we'll hash these out later, when
3060   // we've picked a target.
3061   R.suppressDiagnostics();
3062 
3063   UnresolvedLookupExpr *ULE
3064     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
3065                                    SS.getWithLocInContext(Context),
3066                                    R.getLookupNameInfo(),
3067                                    NeedsADL, R.isOverloadedResult(),
3068                                    R.begin(), R.end());
3069 
3070   return ULE;
3071 }
3072 
3073 static void
3074 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
3075                                    ValueDecl *var, DeclContext *DC);
3076 
3077 /// Complete semantic analysis for a reference to the given declaration.
3078 ExprResult Sema::BuildDeclarationNameExpr(
3079     const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
3080     NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
3081     bool AcceptInvalidDecl) {
3082   assert(D && "Cannot refer to a NULL declaration");
3083   assert(!isa<FunctionTemplateDecl>(D) &&
3084          "Cannot refer unambiguously to a function template");
3085 
3086   SourceLocation Loc = NameInfo.getLoc();
3087   if (CheckDeclInExpr(*this, Loc, D))
3088     return ExprError();
3089 
3090   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
3091     // Specifically diagnose references to class templates that are missing
3092     // a template argument list.
3093     diagnoseMissingTemplateArguments(TemplateName(Template), Loc);
3094     return ExprError();
3095   }
3096 
3097   // Make sure that we're referring to a value.
3098   ValueDecl *VD = dyn_cast<ValueDecl>(D);
3099   if (!VD) {
3100     Diag(Loc, diag::err_ref_non_value)
3101       << D << SS.getRange();
3102     Diag(D->getLocation(), diag::note_declared_at);
3103     return ExprError();
3104   }
3105 
3106   // Check whether this declaration can be used. Note that we suppress
3107   // this check when we're going to perform argument-dependent lookup
3108   // on this function name, because this might not be the function
3109   // that overload resolution actually selects.
3110   if (DiagnoseUseOfDecl(VD, Loc))
3111     return ExprError();
3112 
3113   // Only create DeclRefExpr's for valid Decl's.
3114   if (VD->isInvalidDecl() && !AcceptInvalidDecl)
3115     return ExprError();
3116 
3117   // Handle members of anonymous structs and unions.  If we got here,
3118   // and the reference is to a class member indirect field, then this
3119   // must be the subject of a pointer-to-member expression.
3120   if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
3121     if (!indirectField->isCXXClassMember())
3122       return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
3123                                                       indirectField);
3124 
3125   {
3126     QualType type = VD->getType();
3127     if (type.isNull())
3128       return ExprError();
3129     ExprValueKind valueKind = VK_RValue;
3130 
3131     switch (D->getKind()) {
3132     // Ignore all the non-ValueDecl kinds.
3133 #define ABSTRACT_DECL(kind)
3134 #define VALUE(type, base)
3135 #define DECL(type, base) \
3136     case Decl::type:
3137 #include "clang/AST/DeclNodes.inc"
3138       llvm_unreachable("invalid value decl kind");
3139 
3140     // These shouldn't make it here.
3141     case Decl::ObjCAtDefsField:
3142       llvm_unreachable("forming non-member reference to ivar?");
3143 
3144     // Enum constants are always r-values and never references.
3145     // Unresolved using declarations are dependent.
3146     case Decl::EnumConstant:
3147     case Decl::UnresolvedUsingValue:
3148     case Decl::OMPDeclareReduction:
3149     case Decl::OMPDeclareMapper:
3150       valueKind = VK_RValue;
3151       break;
3152 
3153     // Fields and indirect fields that got here must be for
3154     // pointer-to-member expressions; we just call them l-values for
3155     // internal consistency, because this subexpression doesn't really
3156     // exist in the high-level semantics.
3157     case Decl::Field:
3158     case Decl::IndirectField:
3159     case Decl::ObjCIvar:
3160       assert(getLangOpts().CPlusPlus &&
3161              "building reference to field in C?");
3162 
3163       // These can't have reference type in well-formed programs, but
3164       // for internal consistency we do this anyway.
3165       type = type.getNonReferenceType();
3166       valueKind = VK_LValue;
3167       break;
3168 
3169     // Non-type template parameters are either l-values or r-values
3170     // depending on the type.
3171     case Decl::NonTypeTemplateParm: {
3172       if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
3173         type = reftype->getPointeeType();
3174         valueKind = VK_LValue; // even if the parameter is an r-value reference
3175         break;
3176       }
3177 
3178       // For non-references, we need to strip qualifiers just in case
3179       // the template parameter was declared as 'const int' or whatever.
3180       valueKind = VK_RValue;
3181       type = type.getUnqualifiedType();
3182       break;
3183     }
3184 
3185     case Decl::Var:
3186     case Decl::VarTemplateSpecialization:
3187     case Decl::VarTemplatePartialSpecialization:
3188     case Decl::Decomposition:
3189     case Decl::OMPCapturedExpr:
3190       // In C, "extern void blah;" is valid and is an r-value.
3191       if (!getLangOpts().CPlusPlus &&
3192           !type.hasQualifiers() &&
3193           type->isVoidType()) {
3194         valueKind = VK_RValue;
3195         break;
3196       }
3197       LLVM_FALLTHROUGH;
3198 
3199     case Decl::ImplicitParam:
3200     case Decl::ParmVar: {
3201       // These are always l-values.
3202       valueKind = VK_LValue;
3203       type = type.getNonReferenceType();
3204 
3205       // FIXME: Does the addition of const really only apply in
3206       // potentially-evaluated contexts? Since the variable isn't actually
3207       // captured in an unevaluated context, it seems that the answer is no.
3208       if (!isUnevaluatedContext()) {
3209         QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
3210         if (!CapturedType.isNull())
3211           type = CapturedType;
3212       }
3213 
3214       break;
3215     }
3216 
3217     case Decl::Binding: {
3218       // These are always lvalues.
3219       valueKind = VK_LValue;
3220       type = type.getNonReferenceType();
3221       // FIXME: Support lambda-capture of BindingDecls, once CWG actually
3222       // decides how that's supposed to work.
3223       auto *BD = cast<BindingDecl>(VD);
3224       if (BD->getDeclContext() != CurContext) {
3225         auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl());
3226         if (DD && DD->hasLocalStorage())
3227           diagnoseUncapturableValueReference(*this, Loc, BD, CurContext);
3228       }
3229       break;
3230     }
3231 
3232     case Decl::Function: {
3233       if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
3234         if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
3235           type = Context.BuiltinFnTy;
3236           valueKind = VK_RValue;
3237           break;
3238         }
3239       }
3240 
3241       const FunctionType *fty = type->castAs<FunctionType>();
3242 
3243       // If we're referring to a function with an __unknown_anytype
3244       // result type, make the entire expression __unknown_anytype.
3245       if (fty->getReturnType() == Context.UnknownAnyTy) {
3246         type = Context.UnknownAnyTy;
3247         valueKind = VK_RValue;
3248         break;
3249       }
3250 
3251       // Functions are l-values in C++.
3252       if (getLangOpts().CPlusPlus) {
3253         valueKind = VK_LValue;
3254         break;
3255       }
3256 
3257       // C99 DR 316 says that, if a function type comes from a
3258       // function definition (without a prototype), that type is only
3259       // used for checking compatibility. Therefore, when referencing
3260       // the function, we pretend that we don't have the full function
3261       // type.
3262       if (!cast<FunctionDecl>(VD)->hasPrototype() &&
3263           isa<FunctionProtoType>(fty))
3264         type = Context.getFunctionNoProtoType(fty->getReturnType(),
3265                                               fty->getExtInfo());
3266 
3267       // Functions are r-values in C.
3268       valueKind = VK_RValue;
3269       break;
3270     }
3271 
3272     case Decl::CXXDeductionGuide:
3273       llvm_unreachable("building reference to deduction guide");
3274 
3275     case Decl::MSProperty:
3276       valueKind = VK_LValue;
3277       break;
3278 
3279     case Decl::CXXMethod:
3280       // If we're referring to a method with an __unknown_anytype
3281       // result type, make the entire expression __unknown_anytype.
3282       // This should only be possible with a type written directly.
3283       if (const FunctionProtoType *proto
3284             = dyn_cast<FunctionProtoType>(VD->getType()))
3285         if (proto->getReturnType() == Context.UnknownAnyTy) {
3286           type = Context.UnknownAnyTy;
3287           valueKind = VK_RValue;
3288           break;
3289         }
3290 
3291       // C++ methods are l-values if static, r-values if non-static.
3292       if (cast<CXXMethodDecl>(VD)->isStatic()) {
3293         valueKind = VK_LValue;
3294         break;
3295       }
3296       LLVM_FALLTHROUGH;
3297 
3298     case Decl::CXXConversion:
3299     case Decl::CXXDestructor:
3300     case Decl::CXXConstructor:
3301       valueKind = VK_RValue;
3302       break;
3303     }
3304 
3305     return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3306                             /*FIXME: TemplateKWLoc*/ SourceLocation(),
3307                             TemplateArgs);
3308   }
3309 }
3310 
3311 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3312                                     SmallString<32> &Target) {
3313   Target.resize(CharByteWidth * (Source.size() + 1));
3314   char *ResultPtr = &Target[0];
3315   const llvm::UTF8 *ErrorPtr;
3316   bool success =
3317       llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3318   (void)success;
3319   assert(success);
3320   Target.resize(ResultPtr - &Target[0]);
3321 }
3322 
3323 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3324                                      PredefinedExpr::IdentKind IK) {
3325   // Pick the current block, lambda, captured statement or function.
3326   Decl *currentDecl = nullptr;
3327   if (const BlockScopeInfo *BSI = getCurBlock())
3328     currentDecl = BSI->TheDecl;
3329   else if (const LambdaScopeInfo *LSI = getCurLambda())
3330     currentDecl = LSI->CallOperator;
3331   else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3332     currentDecl = CSI->TheCapturedDecl;
3333   else
3334     currentDecl = getCurFunctionOrMethodDecl();
3335 
3336   if (!currentDecl) {
3337     Diag(Loc, diag::ext_predef_outside_function);
3338     currentDecl = Context.getTranslationUnitDecl();
3339   }
3340 
3341   QualType ResTy;
3342   StringLiteral *SL = nullptr;
3343   if (cast<DeclContext>(currentDecl)->isDependentContext())
3344     ResTy = Context.DependentTy;
3345   else {
3346     // Pre-defined identifiers are of type char[x], where x is the length of
3347     // the string.
3348     auto Str = PredefinedExpr::ComputeName(IK, currentDecl);
3349     unsigned Length = Str.length();
3350 
3351     llvm::APInt LengthI(32, Length + 1);
3352     if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) {
3353       ResTy =
3354           Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst());
3355       SmallString<32> RawChars;
3356       ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3357                               Str, RawChars);
3358       ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3359                                            ArrayType::Normal,
3360                                            /*IndexTypeQuals*/ 0);
3361       SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3362                                  /*Pascal*/ false, ResTy, Loc);
3363     } else {
3364       ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
3365       ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3366                                            ArrayType::Normal,
3367                                            /*IndexTypeQuals*/ 0);
3368       SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3369                                  /*Pascal*/ false, ResTy, Loc);
3370     }
3371   }
3372 
3373   return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL);
3374 }
3375 
3376 static std::pair<QualType, StringLiteral *>
3377 GetUniqueStableNameInfo(ASTContext &Context, QualType OpType,
3378                         SourceLocation OpLoc, PredefinedExpr::IdentKind K) {
3379   std::pair<QualType, StringLiteral*> Result{{}, nullptr};
3380 
3381   if (OpType->isDependentType()) {
3382       Result.first = Context.DependentTy;
3383       return Result;
3384   }
3385 
3386   std::string Str = PredefinedExpr::ComputeName(Context, K, OpType);
3387   llvm::APInt Length(32, Str.length() + 1);
3388   Result.first =
3389       Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
3390   Result.first = Context.getConstantArrayType(
3391       Result.first, Length, nullptr, ArrayType::Normal, /*IndexTypeQuals*/ 0);
3392   Result.second = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3393                                         /*Pascal*/ false, Result.first, OpLoc);
3394   return Result;
3395 }
3396 
3397 ExprResult Sema::BuildUniqueStableName(SourceLocation OpLoc,
3398                                        TypeSourceInfo *Operand) {
3399   QualType ResultTy;
3400   StringLiteral *SL;
3401   std::tie(ResultTy, SL) = GetUniqueStableNameInfo(
3402       Context, Operand->getType(), OpLoc, PredefinedExpr::UniqueStableNameType);
3403 
3404   return PredefinedExpr::Create(Context, OpLoc, ResultTy,
3405                                 PredefinedExpr::UniqueStableNameType, SL,
3406                                 Operand);
3407 }
3408 
3409 ExprResult Sema::BuildUniqueStableName(SourceLocation OpLoc,
3410                                        Expr *E) {
3411   QualType ResultTy;
3412   StringLiteral *SL;
3413   std::tie(ResultTy, SL) = GetUniqueStableNameInfo(
3414       Context, E->getType(), OpLoc, PredefinedExpr::UniqueStableNameExpr);
3415 
3416   return PredefinedExpr::Create(Context, OpLoc, ResultTy,
3417                                 PredefinedExpr::UniqueStableNameExpr, SL, E);
3418 }
3419 
3420 ExprResult Sema::ActOnUniqueStableNameExpr(SourceLocation OpLoc,
3421                                            SourceLocation L, SourceLocation R,
3422                                            ParsedType Ty) {
3423   TypeSourceInfo *TInfo = nullptr;
3424   QualType T = GetTypeFromParser(Ty, &TInfo);
3425 
3426   if (T.isNull())
3427     return ExprError();
3428   if (!TInfo)
3429     TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
3430 
3431   return BuildUniqueStableName(OpLoc, TInfo);
3432 }
3433 
3434 ExprResult Sema::ActOnUniqueStableNameExpr(SourceLocation OpLoc,
3435                                            SourceLocation L, SourceLocation R,
3436                                            Expr *E) {
3437   return BuildUniqueStableName(OpLoc, E);
3438 }
3439 
3440 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3441   PredefinedExpr::IdentKind IK;
3442 
3443   switch (Kind) {
3444   default: llvm_unreachable("Unknown simple primary expr!");
3445   case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3446   case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break;
3447   case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS]
3448   case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS]
3449   case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS]
3450   case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS]
3451   case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break;
3452   }
3453 
3454   return BuildPredefinedExpr(Loc, IK);
3455 }
3456 
3457 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3458   SmallString<16> CharBuffer;
3459   bool Invalid = false;
3460   StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3461   if (Invalid)
3462     return ExprError();
3463 
3464   CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3465                             PP, Tok.getKind());
3466   if (Literal.hadError())
3467     return ExprError();
3468 
3469   QualType Ty;
3470   if (Literal.isWide())
3471     Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3472   else if (Literal.isUTF8() && getLangOpts().Char8)
3473     Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3474   else if (Literal.isUTF16())
3475     Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3476   else if (Literal.isUTF32())
3477     Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3478   else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3479     Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
3480   else
3481     Ty = Context.CharTy;  // 'x' -> char in C++
3482 
3483   CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3484   if (Literal.isWide())
3485     Kind = CharacterLiteral::Wide;
3486   else if (Literal.isUTF16())
3487     Kind = CharacterLiteral::UTF16;
3488   else if (Literal.isUTF32())
3489     Kind = CharacterLiteral::UTF32;
3490   else if (Literal.isUTF8())
3491     Kind = CharacterLiteral::UTF8;
3492 
3493   Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3494                                              Tok.getLocation());
3495 
3496   if (Literal.getUDSuffix().empty())
3497     return Lit;
3498 
3499   // We're building a user-defined literal.
3500   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3501   SourceLocation UDSuffixLoc =
3502     getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3503 
3504   // Make sure we're allowed user-defined literals here.
3505   if (!UDLScope)
3506     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3507 
3508   // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3509   //   operator "" X (ch)
3510   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3511                                         Lit, Tok.getLocation());
3512 }
3513 
3514 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3515   unsigned IntSize = Context.getTargetInfo().getIntWidth();
3516   return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3517                                 Context.IntTy, Loc);
3518 }
3519 
3520 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3521                                   QualType Ty, SourceLocation Loc) {
3522   const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3523 
3524   using llvm::APFloat;
3525   APFloat Val(Format);
3526 
3527   APFloat::opStatus result = Literal.GetFloatValue(Val);
3528 
3529   // Overflow is always an error, but underflow is only an error if
3530   // we underflowed to zero (APFloat reports denormals as underflow).
3531   if ((result & APFloat::opOverflow) ||
3532       ((result & APFloat::opUnderflow) && Val.isZero())) {
3533     unsigned diagnostic;
3534     SmallString<20> buffer;
3535     if (result & APFloat::opOverflow) {
3536       diagnostic = diag::warn_float_overflow;
3537       APFloat::getLargest(Format).toString(buffer);
3538     } else {
3539       diagnostic = diag::warn_float_underflow;
3540       APFloat::getSmallest(Format).toString(buffer);
3541     }
3542 
3543     S.Diag(Loc, diagnostic)
3544       << Ty
3545       << StringRef(buffer.data(), buffer.size());
3546   }
3547 
3548   bool isExact = (result == APFloat::opOK);
3549   return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3550 }
3551 
3552 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3553   assert(E && "Invalid expression");
3554 
3555   if (E->isValueDependent())
3556     return false;
3557 
3558   QualType QT = E->getType();
3559   if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3560     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3561     return true;
3562   }
3563 
3564   llvm::APSInt ValueAPS;
3565   ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3566 
3567   if (R.isInvalid())
3568     return true;
3569 
3570   bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3571   if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3572     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3573         << ValueAPS.toString(10) << ValueIsPositive;
3574     return true;
3575   }
3576 
3577   return false;
3578 }
3579 
3580 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3581   // Fast path for a single digit (which is quite common).  A single digit
3582   // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3583   if (Tok.getLength() == 1) {
3584     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3585     return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3586   }
3587 
3588   SmallString<128> SpellingBuffer;
3589   // NumericLiteralParser wants to overread by one character.  Add padding to
3590   // the buffer in case the token is copied to the buffer.  If getSpelling()
3591   // returns a StringRef to the memory buffer, it should have a null char at
3592   // the EOF, so it is also safe.
3593   SpellingBuffer.resize(Tok.getLength() + 1);
3594 
3595   // Get the spelling of the token, which eliminates trigraphs, etc.
3596   bool Invalid = false;
3597   StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3598   if (Invalid)
3599     return ExprError();
3600 
3601   NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
3602   if (Literal.hadError)
3603     return ExprError();
3604 
3605   if (Literal.hasUDSuffix()) {
3606     // We're building a user-defined literal.
3607     IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3608     SourceLocation UDSuffixLoc =
3609       getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3610 
3611     // Make sure we're allowed user-defined literals here.
3612     if (!UDLScope)
3613       return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3614 
3615     QualType CookedTy;
3616     if (Literal.isFloatingLiteral()) {
3617       // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3618       // long double, the literal is treated as a call of the form
3619       //   operator "" X (f L)
3620       CookedTy = Context.LongDoubleTy;
3621     } else {
3622       // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3623       // unsigned long long, the literal is treated as a call of the form
3624       //   operator "" X (n ULL)
3625       CookedTy = Context.UnsignedLongLongTy;
3626     }
3627 
3628     DeclarationName OpName =
3629       Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3630     DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3631     OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3632 
3633     SourceLocation TokLoc = Tok.getLocation();
3634 
3635     // Perform literal operator lookup to determine if we're building a raw
3636     // literal or a cooked one.
3637     LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3638     switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3639                                   /*AllowRaw*/ true, /*AllowTemplate*/ true,
3640                                   /*AllowStringTemplate*/ false,
3641                                   /*DiagnoseMissing*/ !Literal.isImaginary)) {
3642     case LOLR_ErrorNoDiagnostic:
3643       // Lookup failure for imaginary constants isn't fatal, there's still the
3644       // GNU extension producing _Complex types.
3645       break;
3646     case LOLR_Error:
3647       return ExprError();
3648     case LOLR_Cooked: {
3649       Expr *Lit;
3650       if (Literal.isFloatingLiteral()) {
3651         Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3652       } else {
3653         llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3654         if (Literal.GetIntegerValue(ResultVal))
3655           Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3656               << /* Unsigned */ 1;
3657         Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3658                                      Tok.getLocation());
3659       }
3660       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3661     }
3662 
3663     case LOLR_Raw: {
3664       // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3665       // literal is treated as a call of the form
3666       //   operator "" X ("n")
3667       unsigned Length = Literal.getUDSuffixOffset();
3668       QualType StrTy = Context.getConstantArrayType(
3669           Context.adjustStringLiteralBaseType(Context.CharTy.withConst()),
3670           llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0);
3671       Expr *Lit = StringLiteral::Create(
3672           Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3673           /*Pascal*/false, StrTy, &TokLoc, 1);
3674       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3675     }
3676 
3677     case LOLR_Template: {
3678       // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3679       // template), L is treated as a call fo the form
3680       //   operator "" X <'c1', 'c2', ... 'ck'>()
3681       // where n is the source character sequence c1 c2 ... ck.
3682       TemplateArgumentListInfo ExplicitArgs;
3683       unsigned CharBits = Context.getIntWidth(Context.CharTy);
3684       bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3685       llvm::APSInt Value(CharBits, CharIsUnsigned);
3686       for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3687         Value = TokSpelling[I];
3688         TemplateArgument Arg(Context, Value, Context.CharTy);
3689         TemplateArgumentLocInfo ArgInfo;
3690         ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3691       }
3692       return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3693                                       &ExplicitArgs);
3694     }
3695     case LOLR_StringTemplate:
3696       llvm_unreachable("unexpected literal operator lookup result");
3697     }
3698   }
3699 
3700   Expr *Res;
3701 
3702   if (Literal.isFixedPointLiteral()) {
3703     QualType Ty;
3704 
3705     if (Literal.isAccum) {
3706       if (Literal.isHalf) {
3707         Ty = Context.ShortAccumTy;
3708       } else if (Literal.isLong) {
3709         Ty = Context.LongAccumTy;
3710       } else {
3711         Ty = Context.AccumTy;
3712       }
3713     } else if (Literal.isFract) {
3714       if (Literal.isHalf) {
3715         Ty = Context.ShortFractTy;
3716       } else if (Literal.isLong) {
3717         Ty = Context.LongFractTy;
3718       } else {
3719         Ty = Context.FractTy;
3720       }
3721     }
3722 
3723     if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
3724 
3725     bool isSigned = !Literal.isUnsigned;
3726     unsigned scale = Context.getFixedPointScale(Ty);
3727     unsigned bit_width = Context.getTypeInfo(Ty).Width;
3728 
3729     llvm::APInt Val(bit_width, 0, isSigned);
3730     bool Overflowed = Literal.GetFixedPointValue(Val, scale);
3731     bool ValIsZero = Val.isNullValue() && !Overflowed;
3732 
3733     auto MaxVal = Context.getFixedPointMax(Ty).getValue();
3734     if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
3735       // Clause 6.4.4 - The value of a constant shall be in the range of
3736       // representable values for its type, with exception for constants of a
3737       // fract type with a value of exactly 1; such a constant shall denote
3738       // the maximal value for the type.
3739       --Val;
3740     else if (Val.ugt(MaxVal) || Overflowed)
3741       Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
3742 
3743     Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty,
3744                                               Tok.getLocation(), scale);
3745   } else if (Literal.isFloatingLiteral()) {
3746     QualType Ty;
3747     if (Literal.isHalf){
3748       if (getOpenCLOptions().isEnabled("cl_khr_fp16"))
3749         Ty = Context.HalfTy;
3750       else {
3751         Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3752         return ExprError();
3753       }
3754     } else if (Literal.isFloat)
3755       Ty = Context.FloatTy;
3756     else if (Literal.isLong)
3757       Ty = Context.LongDoubleTy;
3758     else if (Literal.isFloat16)
3759       Ty = Context.Float16Ty;
3760     else if (Literal.isFloat128)
3761       Ty = Context.Float128Ty;
3762     else
3763       Ty = Context.DoubleTy;
3764 
3765     Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3766 
3767     if (Ty == Context.DoubleTy) {
3768       if (getLangOpts().SinglePrecisionConstants) {
3769         const BuiltinType *BTy = Ty->getAs<BuiltinType>();
3770         if (BTy->getKind() != BuiltinType::Float) {
3771           Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3772         }
3773       } else if (getLangOpts().OpenCL &&
3774                  !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
3775         // Impose single-precision float type when cl_khr_fp64 is not enabled.
3776         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
3777         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3778       }
3779     }
3780   } else if (!Literal.isIntegerLiteral()) {
3781     return ExprError();
3782   } else {
3783     QualType Ty;
3784 
3785     // 'long long' is a C99 or C++11 feature.
3786     if (!getLangOpts().C99 && Literal.isLongLong) {
3787       if (getLangOpts().CPlusPlus)
3788         Diag(Tok.getLocation(),
3789              getLangOpts().CPlusPlus11 ?
3790              diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3791       else
3792         Diag(Tok.getLocation(), diag::ext_c99_longlong);
3793     }
3794 
3795     // Get the value in the widest-possible width.
3796     unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3797     llvm::APInt ResultVal(MaxWidth, 0);
3798 
3799     if (Literal.GetIntegerValue(ResultVal)) {
3800       // If this value didn't fit into uintmax_t, error and force to ull.
3801       Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3802           << /* Unsigned */ 1;
3803       Ty = Context.UnsignedLongLongTy;
3804       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3805              "long long is not intmax_t?");
3806     } else {
3807       // If this value fits into a ULL, try to figure out what else it fits into
3808       // according to the rules of C99 6.4.4.1p5.
3809 
3810       // Octal, Hexadecimal, and integers with a U suffix are allowed to
3811       // be an unsigned int.
3812       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3813 
3814       // Check from smallest to largest, picking the smallest type we can.
3815       unsigned Width = 0;
3816 
3817       // Microsoft specific integer suffixes are explicitly sized.
3818       if (Literal.MicrosoftInteger) {
3819         if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3820           Width = 8;
3821           Ty = Context.CharTy;
3822         } else {
3823           Width = Literal.MicrosoftInteger;
3824           Ty = Context.getIntTypeForBitwidth(Width,
3825                                              /*Signed=*/!Literal.isUnsigned);
3826         }
3827       }
3828 
3829       if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
3830         // Are int/unsigned possibilities?
3831         unsigned IntSize = Context.getTargetInfo().getIntWidth();
3832 
3833         // Does it fit in a unsigned int?
3834         if (ResultVal.isIntN(IntSize)) {
3835           // Does it fit in a signed int?
3836           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3837             Ty = Context.IntTy;
3838           else if (AllowUnsigned)
3839             Ty = Context.UnsignedIntTy;
3840           Width = IntSize;
3841         }
3842       }
3843 
3844       // Are long/unsigned long possibilities?
3845       if (Ty.isNull() && !Literal.isLongLong) {
3846         unsigned LongSize = Context.getTargetInfo().getLongWidth();
3847 
3848         // Does it fit in a unsigned long?
3849         if (ResultVal.isIntN(LongSize)) {
3850           // Does it fit in a signed long?
3851           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3852             Ty = Context.LongTy;
3853           else if (AllowUnsigned)
3854             Ty = Context.UnsignedLongTy;
3855           // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
3856           // is compatible.
3857           else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
3858             const unsigned LongLongSize =
3859                 Context.getTargetInfo().getLongLongWidth();
3860             Diag(Tok.getLocation(),
3861                  getLangOpts().CPlusPlus
3862                      ? Literal.isLong
3863                            ? diag::warn_old_implicitly_unsigned_long_cxx
3864                            : /*C++98 UB*/ diag::
3865                                  ext_old_implicitly_unsigned_long_cxx
3866                      : diag::warn_old_implicitly_unsigned_long)
3867                 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
3868                                             : /*will be ill-formed*/ 1);
3869             Ty = Context.UnsignedLongTy;
3870           }
3871           Width = LongSize;
3872         }
3873       }
3874 
3875       // Check long long if needed.
3876       if (Ty.isNull()) {
3877         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3878 
3879         // Does it fit in a unsigned long long?
3880         if (ResultVal.isIntN(LongLongSize)) {
3881           // Does it fit in a signed long long?
3882           // To be compatible with MSVC, hex integer literals ending with the
3883           // LL or i64 suffix are always signed in Microsoft mode.
3884           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3885               (getLangOpts().MSVCCompat && Literal.isLongLong)))
3886             Ty = Context.LongLongTy;
3887           else if (AllowUnsigned)
3888             Ty = Context.UnsignedLongLongTy;
3889           Width = LongLongSize;
3890         }
3891       }
3892 
3893       // If we still couldn't decide a type, we probably have something that
3894       // does not fit in a signed long long, but has no U suffix.
3895       if (Ty.isNull()) {
3896         Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
3897         Ty = Context.UnsignedLongLongTy;
3898         Width = Context.getTargetInfo().getLongLongWidth();
3899       }
3900 
3901       if (ResultVal.getBitWidth() != Width)
3902         ResultVal = ResultVal.trunc(Width);
3903     }
3904     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3905   }
3906 
3907   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3908   if (Literal.isImaginary) {
3909     Res = new (Context) ImaginaryLiteral(Res,
3910                                         Context.getComplexType(Res->getType()));
3911 
3912     Diag(Tok.getLocation(), diag::ext_imaginary_constant);
3913   }
3914   return Res;
3915 }
3916 
3917 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
3918   assert(E && "ActOnParenExpr() missing expr");
3919   return new (Context) ParenExpr(L, R, E);
3920 }
3921 
3922 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3923                                          SourceLocation Loc,
3924                                          SourceRange ArgRange) {
3925   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3926   // scalar or vector data type argument..."
3927   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3928   // type (C99 6.2.5p18) or void.
3929   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3930     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3931       << T << ArgRange;
3932     return true;
3933   }
3934 
3935   assert((T->isVoidType() || !T->isIncompleteType()) &&
3936          "Scalar types should always be complete");
3937   return false;
3938 }
3939 
3940 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3941                                            SourceLocation Loc,
3942                                            SourceRange ArgRange,
3943                                            UnaryExprOrTypeTrait TraitKind) {
3944   // Invalid types must be hard errors for SFINAE in C++.
3945   if (S.LangOpts.CPlusPlus)
3946     return true;
3947 
3948   // C99 6.5.3.4p1:
3949   if (T->isFunctionType() &&
3950       (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
3951        TraitKind == UETT_PreferredAlignOf)) {
3952     // sizeof(function)/alignof(function) is allowed as an extension.
3953     S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3954       << TraitKind << ArgRange;
3955     return false;
3956   }
3957 
3958   // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
3959   // this is an error (OpenCL v1.1 s6.3.k)
3960   if (T->isVoidType()) {
3961     unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
3962                                         : diag::ext_sizeof_alignof_void_type;
3963     S.Diag(Loc, DiagID) << TraitKind << ArgRange;
3964     return false;
3965   }
3966 
3967   return true;
3968 }
3969 
3970 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
3971                                              SourceLocation Loc,
3972                                              SourceRange ArgRange,
3973                                              UnaryExprOrTypeTrait TraitKind) {
3974   // Reject sizeof(interface) and sizeof(interface<proto>) if the
3975   // runtime doesn't allow it.
3976   if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
3977     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3978       << T << (TraitKind == UETT_SizeOf)
3979       << ArgRange;
3980     return true;
3981   }
3982 
3983   return false;
3984 }
3985 
3986 /// Check whether E is a pointer from a decayed array type (the decayed
3987 /// pointer type is equal to T) and emit a warning if it is.
3988 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
3989                                      Expr *E) {
3990   // Don't warn if the operation changed the type.
3991   if (T != E->getType())
3992     return;
3993 
3994   // Now look for array decays.
3995   ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
3996   if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
3997     return;
3998 
3999   S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
4000                                              << ICE->getType()
4001                                              << ICE->getSubExpr()->getType();
4002 }
4003 
4004 /// Check the constraints on expression operands to unary type expression
4005 /// and type traits.
4006 ///
4007 /// Completes any types necessary and validates the constraints on the operand
4008 /// expression. The logic mostly mirrors the type-based overload, but may modify
4009 /// the expression as it completes the type for that expression through template
4010 /// instantiation, etc.
4011 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
4012                                             UnaryExprOrTypeTrait ExprKind) {
4013   QualType ExprTy = E->getType();
4014   assert(!ExprTy->isReferenceType());
4015 
4016   bool IsUnevaluatedOperand =
4017       (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf ||
4018        ExprKind == UETT_PreferredAlignOf);
4019   if (IsUnevaluatedOperand) {
4020     ExprResult Result = CheckUnevaluatedOperand(E);
4021     if (Result.isInvalid())
4022       return true;
4023     E = Result.get();
4024   }
4025 
4026   if (ExprKind == UETT_VecStep)
4027     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
4028                                         E->getSourceRange());
4029 
4030   // Whitelist some types as extensions
4031   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
4032                                       E->getSourceRange(), ExprKind))
4033     return false;
4034 
4035   // 'alignof' applied to an expression only requires the base element type of
4036   // the expression to be complete. 'sizeof' requires the expression's type to
4037   // be complete (and will attempt to complete it if it's an array of unknown
4038   // bound).
4039   if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4040     if (RequireCompleteSizedType(
4041             E->getExprLoc(), Context.getBaseElementType(E->getType()),
4042             diag::err_sizeof_alignof_incomplete_or_sizeless_type, ExprKind,
4043             E->getSourceRange()))
4044       return true;
4045   } else {
4046     if (RequireCompleteSizedExprType(
4047             E, diag::err_sizeof_alignof_incomplete_or_sizeless_type, ExprKind,
4048             E->getSourceRange()))
4049       return true;
4050   }
4051 
4052   // Completing the expression's type may have changed it.
4053   ExprTy = E->getType();
4054   assert(!ExprTy->isReferenceType());
4055 
4056   if (ExprTy->isFunctionType()) {
4057     Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
4058       << ExprKind << E->getSourceRange();
4059     return true;
4060   }
4061 
4062   // The operand for sizeof and alignof is in an unevaluated expression context,
4063   // so side effects could result in unintended consequences.
4064   if (IsUnevaluatedOperand && !inTemplateInstantiation() &&
4065       E->HasSideEffects(Context, false))
4066     Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
4067 
4068   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
4069                                        E->getSourceRange(), ExprKind))
4070     return true;
4071 
4072   if (ExprKind == UETT_SizeOf) {
4073     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
4074       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
4075         QualType OType = PVD->getOriginalType();
4076         QualType Type = PVD->getType();
4077         if (Type->isPointerType() && OType->isArrayType()) {
4078           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
4079             << Type << OType;
4080           Diag(PVD->getLocation(), diag::note_declared_at);
4081         }
4082       }
4083     }
4084 
4085     // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
4086     // decays into a pointer and returns an unintended result. This is most
4087     // likely a typo for "sizeof(array) op x".
4088     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
4089       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4090                                BO->getLHS());
4091       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4092                                BO->getRHS());
4093     }
4094   }
4095 
4096   return false;
4097 }
4098 
4099 /// Check the constraints on operands to unary expression and type
4100 /// traits.
4101 ///
4102 /// This will complete any types necessary, and validate the various constraints
4103 /// on those operands.
4104 ///
4105 /// The UsualUnaryConversions() function is *not* called by this routine.
4106 /// C99 6.3.2.1p[2-4] all state:
4107 ///   Except when it is the operand of the sizeof operator ...
4108 ///
4109 /// C++ [expr.sizeof]p4
4110 ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
4111 ///   standard conversions are not applied to the operand of sizeof.
4112 ///
4113 /// This policy is followed for all of the unary trait expressions.
4114 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
4115                                             SourceLocation OpLoc,
4116                                             SourceRange ExprRange,
4117                                             UnaryExprOrTypeTrait ExprKind) {
4118   if (ExprType->isDependentType())
4119     return false;
4120 
4121   // C++ [expr.sizeof]p2:
4122   //     When applied to a reference or a reference type, the result
4123   //     is the size of the referenced type.
4124   // C++11 [expr.alignof]p3:
4125   //     When alignof is applied to a reference type, the result
4126   //     shall be the alignment of the referenced type.
4127   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
4128     ExprType = Ref->getPointeeType();
4129 
4130   // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
4131   //   When alignof or _Alignof is applied to an array type, the result
4132   //   is the alignment of the element type.
4133   if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4134       ExprKind == UETT_OpenMPRequiredSimdAlign)
4135     ExprType = Context.getBaseElementType(ExprType);
4136 
4137   if (ExprKind == UETT_VecStep)
4138     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
4139 
4140   // Whitelist some types as extensions
4141   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
4142                                       ExprKind))
4143     return false;
4144 
4145   if (RequireCompleteSizedType(
4146           OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4147           ExprKind, ExprRange))
4148     return true;
4149 
4150   if (ExprType->isFunctionType()) {
4151     Diag(OpLoc, diag::err_sizeof_alignof_function_type)
4152       << ExprKind << ExprRange;
4153     return true;
4154   }
4155 
4156   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
4157                                        ExprKind))
4158     return true;
4159 
4160   return false;
4161 }
4162 
4163 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
4164   // Cannot know anything else if the expression is dependent.
4165   if (E->isTypeDependent())
4166     return false;
4167 
4168   if (E->getObjectKind() == OK_BitField) {
4169     S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
4170        << 1 << E->getSourceRange();
4171     return true;
4172   }
4173 
4174   ValueDecl *D = nullptr;
4175   Expr *Inner = E->IgnoreParens();
4176   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) {
4177     D = DRE->getDecl();
4178   } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) {
4179     D = ME->getMemberDecl();
4180   }
4181 
4182   // If it's a field, require the containing struct to have a
4183   // complete definition so that we can compute the layout.
4184   //
4185   // This can happen in C++11 onwards, either by naming the member
4186   // in a way that is not transformed into a member access expression
4187   // (in an unevaluated operand, for instance), or by naming the member
4188   // in a trailing-return-type.
4189   //
4190   // For the record, since __alignof__ on expressions is a GCC
4191   // extension, GCC seems to permit this but always gives the
4192   // nonsensical answer 0.
4193   //
4194   // We don't really need the layout here --- we could instead just
4195   // directly check for all the appropriate alignment-lowing
4196   // attributes --- but that would require duplicating a lot of
4197   // logic that just isn't worth duplicating for such a marginal
4198   // use-case.
4199   if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
4200     // Fast path this check, since we at least know the record has a
4201     // definition if we can find a member of it.
4202     if (!FD->getParent()->isCompleteDefinition()) {
4203       S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
4204         << E->getSourceRange();
4205       return true;
4206     }
4207 
4208     // Otherwise, if it's a field, and the field doesn't have
4209     // reference type, then it must have a complete type (or be a
4210     // flexible array member, which we explicitly want to
4211     // white-list anyway), which makes the following checks trivial.
4212     if (!FD->getType()->isReferenceType())
4213       return false;
4214   }
4215 
4216   return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4217 }
4218 
4219 bool Sema::CheckVecStepExpr(Expr *E) {
4220   E = E->IgnoreParens();
4221 
4222   // Cannot know anything else if the expression is dependent.
4223   if (E->isTypeDependent())
4224     return false;
4225 
4226   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
4227 }
4228 
4229 static void captureVariablyModifiedType(ASTContext &Context, QualType T,
4230                                         CapturingScopeInfo *CSI) {
4231   assert(T->isVariablyModifiedType());
4232   assert(CSI != nullptr);
4233 
4234   // We're going to walk down into the type and look for VLA expressions.
4235   do {
4236     const Type *Ty = T.getTypePtr();
4237     switch (Ty->getTypeClass()) {
4238 #define TYPE(Class, Base)
4239 #define ABSTRACT_TYPE(Class, Base)
4240 #define NON_CANONICAL_TYPE(Class, Base)
4241 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
4242 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4243 #include "clang/AST/TypeNodes.inc"
4244       T = QualType();
4245       break;
4246     // These types are never variably-modified.
4247     case Type::Builtin:
4248     case Type::Complex:
4249     case Type::Vector:
4250     case Type::ExtVector:
4251     case Type::Record:
4252     case Type::Enum:
4253     case Type::Elaborated:
4254     case Type::TemplateSpecialization:
4255     case Type::ObjCObject:
4256     case Type::ObjCInterface:
4257     case Type::ObjCObjectPointer:
4258     case Type::ObjCTypeParam:
4259     case Type::Pipe:
4260       llvm_unreachable("type class is never variably-modified!");
4261     case Type::Adjusted:
4262       T = cast<AdjustedType>(Ty)->getOriginalType();
4263       break;
4264     case Type::Decayed:
4265       T = cast<DecayedType>(Ty)->getPointeeType();
4266       break;
4267     case Type::Pointer:
4268       T = cast<PointerType>(Ty)->getPointeeType();
4269       break;
4270     case Type::BlockPointer:
4271       T = cast<BlockPointerType>(Ty)->getPointeeType();
4272       break;
4273     case Type::LValueReference:
4274     case Type::RValueReference:
4275       T = cast<ReferenceType>(Ty)->getPointeeType();
4276       break;
4277     case Type::MemberPointer:
4278       T = cast<MemberPointerType>(Ty)->getPointeeType();
4279       break;
4280     case Type::ConstantArray:
4281     case Type::IncompleteArray:
4282       // Losing element qualification here is fine.
4283       T = cast<ArrayType>(Ty)->getElementType();
4284       break;
4285     case Type::VariableArray: {
4286       // Losing element qualification here is fine.
4287       const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
4288 
4289       // Unknown size indication requires no size computation.
4290       // Otherwise, evaluate and record it.
4291       auto Size = VAT->getSizeExpr();
4292       if (Size && !CSI->isVLATypeCaptured(VAT) &&
4293           (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI)))
4294         CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType());
4295 
4296       T = VAT->getElementType();
4297       break;
4298     }
4299     case Type::FunctionProto:
4300     case Type::FunctionNoProto:
4301       T = cast<FunctionType>(Ty)->getReturnType();
4302       break;
4303     case Type::Paren:
4304     case Type::TypeOf:
4305     case Type::UnaryTransform:
4306     case Type::Attributed:
4307     case Type::SubstTemplateTypeParm:
4308     case Type::PackExpansion:
4309     case Type::MacroQualified:
4310       // Keep walking after single level desugaring.
4311       T = T.getSingleStepDesugaredType(Context);
4312       break;
4313     case Type::Typedef:
4314       T = cast<TypedefType>(Ty)->desugar();
4315       break;
4316     case Type::Decltype:
4317       T = cast<DecltypeType>(Ty)->desugar();
4318       break;
4319     case Type::Auto:
4320     case Type::DeducedTemplateSpecialization:
4321       T = cast<DeducedType>(Ty)->getDeducedType();
4322       break;
4323     case Type::TypeOfExpr:
4324       T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
4325       break;
4326     case Type::Atomic:
4327       T = cast<AtomicType>(Ty)->getValueType();
4328       break;
4329     }
4330   } while (!T.isNull() && T->isVariablyModifiedType());
4331 }
4332 
4333 /// Build a sizeof or alignof expression given a type operand.
4334 ExprResult
4335 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4336                                      SourceLocation OpLoc,
4337                                      UnaryExprOrTypeTrait ExprKind,
4338                                      SourceRange R) {
4339   if (!TInfo)
4340     return ExprError();
4341 
4342   QualType T = TInfo->getType();
4343 
4344   if (!T->isDependentType() &&
4345       CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
4346     return ExprError();
4347 
4348   if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4349     if (auto *TT = T->getAs<TypedefType>()) {
4350       for (auto I = FunctionScopes.rbegin(),
4351                 E = std::prev(FunctionScopes.rend());
4352            I != E; ++I) {
4353         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4354         if (CSI == nullptr)
4355           break;
4356         DeclContext *DC = nullptr;
4357         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4358           DC = LSI->CallOperator;
4359         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4360           DC = CRSI->TheCapturedDecl;
4361         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4362           DC = BSI->TheDecl;
4363         if (DC) {
4364           if (DC->containsDecl(TT->getDecl()))
4365             break;
4366           captureVariablyModifiedType(Context, T, CSI);
4367         }
4368       }
4369     }
4370   }
4371 
4372   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4373   return new (Context) UnaryExprOrTypeTraitExpr(
4374       ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4375 }
4376 
4377 /// Build a sizeof or alignof expression given an expression
4378 /// operand.
4379 ExprResult
4380 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4381                                      UnaryExprOrTypeTrait ExprKind) {
4382   ExprResult PE = CheckPlaceholderExpr(E);
4383   if (PE.isInvalid())
4384     return ExprError();
4385 
4386   E = PE.get();
4387 
4388   // Verify that the operand is valid.
4389   bool isInvalid = false;
4390   if (E->isTypeDependent()) {
4391     // Delay type-checking for type-dependent expressions.
4392   } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4393     isInvalid = CheckAlignOfExpr(*this, E, ExprKind);
4394   } else if (ExprKind == UETT_VecStep) {
4395     isInvalid = CheckVecStepExpr(E);
4396   } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4397       Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4398       isInvalid = true;
4399   } else if (E->refersToBitField()) {  // C99 6.5.3.4p1.
4400     Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4401     isInvalid = true;
4402   } else {
4403     isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
4404   }
4405 
4406   if (isInvalid)
4407     return ExprError();
4408 
4409   if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4410     PE = TransformToPotentiallyEvaluated(E);
4411     if (PE.isInvalid()) return ExprError();
4412     E = PE.get();
4413   }
4414 
4415   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4416   return new (Context) UnaryExprOrTypeTraitExpr(
4417       ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4418 }
4419 
4420 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4421 /// expr and the same for @c alignof and @c __alignof
4422 /// Note that the ArgRange is invalid if isType is false.
4423 ExprResult
4424 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4425                                     UnaryExprOrTypeTrait ExprKind, bool IsType,
4426                                     void *TyOrEx, SourceRange ArgRange) {
4427   // If error parsing type, ignore.
4428   if (!TyOrEx) return ExprError();
4429 
4430   if (IsType) {
4431     TypeSourceInfo *TInfo;
4432     (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4433     return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4434   }
4435 
4436   Expr *ArgEx = (Expr *)TyOrEx;
4437   ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4438   return Result;
4439 }
4440 
4441 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4442                                      bool IsReal) {
4443   if (V.get()->isTypeDependent())
4444     return S.Context.DependentTy;
4445 
4446   // _Real and _Imag are only l-values for normal l-values.
4447   if (V.get()->getObjectKind() != OK_Ordinary) {
4448     V = S.DefaultLvalueConversion(V.get());
4449     if (V.isInvalid())
4450       return QualType();
4451   }
4452 
4453   // These operators return the element type of a complex type.
4454   if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4455     return CT->getElementType();
4456 
4457   // Otherwise they pass through real integer and floating point types here.
4458   if (V.get()->getType()->isArithmeticType())
4459     return V.get()->getType();
4460 
4461   // Test for placeholders.
4462   ExprResult PR = S.CheckPlaceholderExpr(V.get());
4463   if (PR.isInvalid()) return QualType();
4464   if (PR.get() != V.get()) {
4465     V = PR;
4466     return CheckRealImagOperand(S, V, Loc, IsReal);
4467   }
4468 
4469   // Reject anything else.
4470   S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4471     << (IsReal ? "__real" : "__imag");
4472   return QualType();
4473 }
4474 
4475 
4476 
4477 ExprResult
4478 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4479                           tok::TokenKind Kind, Expr *Input) {
4480   UnaryOperatorKind Opc;
4481   switch (Kind) {
4482   default: llvm_unreachable("Unknown unary op!");
4483   case tok::plusplus:   Opc = UO_PostInc; break;
4484   case tok::minusminus: Opc = UO_PostDec; break;
4485   }
4486 
4487   // Since this might is a postfix expression, get rid of ParenListExprs.
4488   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4489   if (Result.isInvalid()) return ExprError();
4490   Input = Result.get();
4491 
4492   return BuildUnaryOp(S, OpLoc, Opc, Input);
4493 }
4494 
4495 /// Diagnose if arithmetic on the given ObjC pointer is illegal.
4496 ///
4497 /// \return true on error
4498 static bool checkArithmeticOnObjCPointer(Sema &S,
4499                                          SourceLocation opLoc,
4500                                          Expr *op) {
4501   assert(op->getType()->isObjCObjectPointerType());
4502   if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4503       !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4504     return false;
4505 
4506   S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4507     << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4508     << op->getSourceRange();
4509   return true;
4510 }
4511 
4512 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4513   auto *BaseNoParens = Base->IgnoreParens();
4514   if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4515     return MSProp->getPropertyDecl()->getType()->isArrayType();
4516   return isa<MSPropertySubscriptExpr>(BaseNoParens);
4517 }
4518 
4519 ExprResult
4520 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
4521                               Expr *idx, SourceLocation rbLoc) {
4522   if (base && !base->getType().isNull() &&
4523       base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection))
4524     return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
4525                                     /*Length=*/nullptr, rbLoc);
4526 
4527   // Since this might be a postfix expression, get rid of ParenListExprs.
4528   if (isa<ParenListExpr>(base)) {
4529     ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4530     if (result.isInvalid()) return ExprError();
4531     base = result.get();
4532   }
4533 
4534   // A comma-expression as the index is deprecated in C++2a onwards.
4535   if (getLangOpts().CPlusPlus2a &&
4536       ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) ||
4537        (isa<CXXOperatorCallExpr>(idx) &&
4538         cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma))) {
4539     Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript)
4540       << SourceRange(base->getBeginLoc(), rbLoc);
4541   }
4542 
4543   // Handle any non-overload placeholder types in the base and index
4544   // expressions.  We can't handle overloads here because the other
4545   // operand might be an overloadable type, in which case the overload
4546   // resolution for the operator overload should get the first crack
4547   // at the overload.
4548   bool IsMSPropertySubscript = false;
4549   if (base->getType()->isNonOverloadPlaceholderType()) {
4550     IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4551     if (!IsMSPropertySubscript) {
4552       ExprResult result = CheckPlaceholderExpr(base);
4553       if (result.isInvalid())
4554         return ExprError();
4555       base = result.get();
4556     }
4557   }
4558   if (idx->getType()->isNonOverloadPlaceholderType()) {
4559     ExprResult result = CheckPlaceholderExpr(idx);
4560     if (result.isInvalid()) return ExprError();
4561     idx = result.get();
4562   }
4563 
4564   // Build an unanalyzed expression if either operand is type-dependent.
4565   if (getLangOpts().CPlusPlus &&
4566       (base->isTypeDependent() || idx->isTypeDependent())) {
4567     return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
4568                                             VK_LValue, OK_Ordinary, rbLoc);
4569   }
4570 
4571   // MSDN, property (C++)
4572   // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4573   // This attribute can also be used in the declaration of an empty array in a
4574   // class or structure definition. For example:
4575   // __declspec(property(get=GetX, put=PutX)) int x[];
4576   // The above statement indicates that x[] can be used with one or more array
4577   // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4578   // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4579   if (IsMSPropertySubscript) {
4580     // Build MS property subscript expression if base is MS property reference
4581     // or MS property subscript.
4582     return new (Context) MSPropertySubscriptExpr(
4583         base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
4584   }
4585 
4586   // Use C++ overloaded-operator rules if either operand has record
4587   // type.  The spec says to do this if either type is *overloadable*,
4588   // but enum types can't declare subscript operators or conversion
4589   // operators, so there's nothing interesting for overload resolution
4590   // to do if there aren't any record types involved.
4591   //
4592   // ObjC pointers have their own subscripting logic that is not tied
4593   // to overload resolution and so should not take this path.
4594   if (getLangOpts().CPlusPlus &&
4595       (base->getType()->isRecordType() ||
4596        (!base->getType()->isObjCObjectPointerType() &&
4597         idx->getType()->isRecordType()))) {
4598     return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
4599   }
4600 
4601   ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
4602 
4603   if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get()))
4604     CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get()));
4605 
4606   return Res;
4607 }
4608 
4609 void Sema::CheckAddressOfNoDeref(const Expr *E) {
4610   ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4611   const Expr *StrippedExpr = E->IgnoreParenImpCasts();
4612 
4613   // For expressions like `&(*s).b`, the base is recorded and what should be
4614   // checked.
4615   const MemberExpr *Member = nullptr;
4616   while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow())
4617     StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
4618 
4619   LastRecord.PossibleDerefs.erase(StrippedExpr);
4620 }
4621 
4622 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
4623   QualType ResultTy = E->getType();
4624   ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4625 
4626   // Bail if the element is an array since it is not memory access.
4627   if (isa<ArrayType>(ResultTy))
4628     return;
4629 
4630   if (ResultTy->hasAttr(attr::NoDeref)) {
4631     LastRecord.PossibleDerefs.insert(E);
4632     return;
4633   }
4634 
4635   // Check if the base type is a pointer to a member access of a struct
4636   // marked with noderef.
4637   const Expr *Base = E->getBase();
4638   QualType BaseTy = Base->getType();
4639   if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy)))
4640     // Not a pointer access
4641     return;
4642 
4643   const MemberExpr *Member = nullptr;
4644   while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) &&
4645          Member->isArrow())
4646     Base = Member->getBase();
4647 
4648   if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) {
4649     if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))
4650       LastRecord.PossibleDerefs.insert(E);
4651   }
4652 }
4653 
4654 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4655                                           Expr *LowerBound,
4656                                           SourceLocation ColonLoc, Expr *Length,
4657                                           SourceLocation RBLoc) {
4658   if (Base->getType()->isPlaceholderType() &&
4659       !Base->getType()->isSpecificPlaceholderType(
4660           BuiltinType::OMPArraySection)) {
4661     ExprResult Result = CheckPlaceholderExpr(Base);
4662     if (Result.isInvalid())
4663       return ExprError();
4664     Base = Result.get();
4665   }
4666   if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
4667     ExprResult Result = CheckPlaceholderExpr(LowerBound);
4668     if (Result.isInvalid())
4669       return ExprError();
4670     Result = DefaultLvalueConversion(Result.get());
4671     if (Result.isInvalid())
4672       return ExprError();
4673     LowerBound = Result.get();
4674   }
4675   if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
4676     ExprResult Result = CheckPlaceholderExpr(Length);
4677     if (Result.isInvalid())
4678       return ExprError();
4679     Result = DefaultLvalueConversion(Result.get());
4680     if (Result.isInvalid())
4681       return ExprError();
4682     Length = Result.get();
4683   }
4684 
4685   // Build an unanalyzed expression if either operand is type-dependent.
4686   if (Base->isTypeDependent() ||
4687       (LowerBound &&
4688        (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
4689       (Length && (Length->isTypeDependent() || Length->isValueDependent()))) {
4690     return new (Context)
4691         OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy,
4692                             VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4693   }
4694 
4695   // Perform default conversions.
4696   QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
4697   QualType ResultTy;
4698   if (OriginalTy->isAnyPointerType()) {
4699     ResultTy = OriginalTy->getPointeeType();
4700   } else if (OriginalTy->isArrayType()) {
4701     ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
4702   } else {
4703     return ExprError(
4704         Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
4705         << Base->getSourceRange());
4706   }
4707   // C99 6.5.2.1p1
4708   if (LowerBound) {
4709     auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
4710                                                       LowerBound);
4711     if (Res.isInvalid())
4712       return ExprError(Diag(LowerBound->getExprLoc(),
4713                             diag::err_omp_typecheck_section_not_integer)
4714                        << 0 << LowerBound->getSourceRange());
4715     LowerBound = Res.get();
4716 
4717     if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4718         LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4719       Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
4720           << 0 << LowerBound->getSourceRange();
4721   }
4722   if (Length) {
4723     auto Res =
4724         PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
4725     if (Res.isInvalid())
4726       return ExprError(Diag(Length->getExprLoc(),
4727                             diag::err_omp_typecheck_section_not_integer)
4728                        << 1 << Length->getSourceRange());
4729     Length = Res.get();
4730 
4731     if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4732         Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4733       Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
4734           << 1 << Length->getSourceRange();
4735   }
4736 
4737   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4738   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4739   // type. Note that functions are not objects, and that (in C99 parlance)
4740   // incomplete types are not object types.
4741   if (ResultTy->isFunctionType()) {
4742     Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
4743         << ResultTy << Base->getSourceRange();
4744     return ExprError();
4745   }
4746 
4747   if (RequireCompleteType(Base->getExprLoc(), ResultTy,
4748                           diag::err_omp_section_incomplete_type, Base))
4749     return ExprError();
4750 
4751   if (LowerBound && !OriginalTy->isAnyPointerType()) {
4752     Expr::EvalResult Result;
4753     if (LowerBound->EvaluateAsInt(Result, Context)) {
4754       // OpenMP 4.5, [2.4 Array Sections]
4755       // The array section must be a subset of the original array.
4756       llvm::APSInt LowerBoundValue = Result.Val.getInt();
4757       if (LowerBoundValue.isNegative()) {
4758         Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
4759             << LowerBound->getSourceRange();
4760         return ExprError();
4761       }
4762     }
4763   }
4764 
4765   if (Length) {
4766     Expr::EvalResult Result;
4767     if (Length->EvaluateAsInt(Result, Context)) {
4768       // OpenMP 4.5, [2.4 Array Sections]
4769       // The length must evaluate to non-negative integers.
4770       llvm::APSInt LengthValue = Result.Val.getInt();
4771       if (LengthValue.isNegative()) {
4772         Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
4773             << LengthValue.toString(/*Radix=*/10, /*Signed=*/true)
4774             << Length->getSourceRange();
4775         return ExprError();
4776       }
4777     }
4778   } else if (ColonLoc.isValid() &&
4779              (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
4780                                       !OriginalTy->isVariableArrayType()))) {
4781     // OpenMP 4.5, [2.4 Array Sections]
4782     // When the size of the array dimension is not known, the length must be
4783     // specified explicitly.
4784     Diag(ColonLoc, diag::err_omp_section_length_undefined)
4785         << (!OriginalTy.isNull() && OriginalTy->isArrayType());
4786     return ExprError();
4787   }
4788 
4789   if (!Base->getType()->isSpecificPlaceholderType(
4790           BuiltinType::OMPArraySection)) {
4791     ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
4792     if (Result.isInvalid())
4793       return ExprError();
4794     Base = Result.get();
4795   }
4796   return new (Context)
4797       OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy,
4798                           VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4799 }
4800 
4801 ExprResult Sema::ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc,
4802                                           SourceLocation RParenLoc,
4803                                           ArrayRef<Expr *> Dims,
4804                                           ArrayRef<SourceRange> Brackets) {
4805   if (Base->getType()->isPlaceholderType()) {
4806     ExprResult Result = CheckPlaceholderExpr(Base);
4807     if (Result.isInvalid())
4808       return ExprError();
4809     Result = DefaultLvalueConversion(Result.get());
4810     if (Result.isInvalid())
4811       return ExprError();
4812     Base = Result.get();
4813   }
4814   QualType BaseTy = Base->getType();
4815   // Delay analysis of the types/expressions if instantiation/specialization is
4816   // required.
4817   if (!BaseTy->isPointerType() && Base->isTypeDependent())
4818     return OMPArrayShapingExpr::Create(Context, Context.DependentTy, Base,
4819                                        LParenLoc, RParenLoc, Dims, Brackets);
4820   if (!BaseTy->isPointerType() ||
4821       (!Base->isTypeDependent() &&
4822        BaseTy->getPointeeType()->isIncompleteType()))
4823     return ExprError(Diag(Base->getExprLoc(),
4824                           diag::err_omp_non_pointer_type_array_shaping_base)
4825                      << Base->getSourceRange());
4826 
4827   SmallVector<Expr *, 4> NewDims;
4828   bool ErrorFound = false;
4829   for (Expr *Dim : Dims) {
4830     if (Dim->getType()->isPlaceholderType()) {
4831       ExprResult Result = CheckPlaceholderExpr(Dim);
4832       if (Result.isInvalid()) {
4833         ErrorFound = true;
4834         continue;
4835       }
4836       Result = DefaultLvalueConversion(Result.get());
4837       if (Result.isInvalid()) {
4838         ErrorFound = true;
4839         continue;
4840       }
4841       Dim = Result.get();
4842     }
4843     if (!Dim->isTypeDependent()) {
4844       ExprResult Result =
4845           PerformOpenMPImplicitIntegerConversion(Dim->getExprLoc(), Dim);
4846       if (Result.isInvalid()) {
4847         ErrorFound = true;
4848         Diag(Dim->getExprLoc(), diag::err_omp_typecheck_shaping_not_integer)
4849             << Dim->getSourceRange();
4850         continue;
4851       }
4852       Dim = Result.get();
4853       Expr::EvalResult EvResult;
4854       if (!Dim->isValueDependent() && Dim->EvaluateAsInt(EvResult, Context)) {
4855         // OpenMP 5.0, [2.1.4 Array Shaping]
4856         // Each si is an integral type expression that must evaluate to a
4857         // positive integer.
4858         llvm::APSInt Value = EvResult.Val.getInt();
4859         if (!Value.isStrictlyPositive()) {
4860           Diag(Dim->getExprLoc(), diag::err_omp_shaping_dimension_not_positive)
4861               << Value.toString(/*Radix=*/10, /*Signed=*/true)
4862               << Dim->getSourceRange();
4863           ErrorFound = true;
4864           continue;
4865         }
4866       }
4867     }
4868     NewDims.push_back(Dim);
4869   }
4870   if (ErrorFound)
4871     return ExprError();
4872   return OMPArrayShapingExpr::Create(Context, Context.OMPArrayShapingTy, Base,
4873                                      LParenLoc, RParenLoc, NewDims, Brackets);
4874 }
4875 
4876 ExprResult Sema::ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc,
4877                                       SourceLocation LLoc, SourceLocation RLoc,
4878                                       ArrayRef<OMPIteratorData> Data) {
4879   SmallVector<OMPIteratorExpr::IteratorDefinition, 4> ID;
4880   bool IsCorrect = true;
4881   for (const OMPIteratorData &D : Data) {
4882     TypeSourceInfo *TInfo = nullptr;
4883     SourceLocation StartLoc;
4884     QualType DeclTy;
4885     if (!D.Type.getAsOpaquePtr()) {
4886       // OpenMP 5.0, 2.1.6 Iterators
4887       // In an iterator-specifier, if the iterator-type is not specified then
4888       // the type of that iterator is of int type.
4889       DeclTy = Context.IntTy;
4890       StartLoc = D.DeclIdentLoc;
4891     } else {
4892       DeclTy = GetTypeFromParser(D.Type, &TInfo);
4893       StartLoc = TInfo->getTypeLoc().getBeginLoc();
4894     }
4895 
4896     bool IsDeclTyDependent = DeclTy->isDependentType() ||
4897                              DeclTy->containsUnexpandedParameterPack() ||
4898                              DeclTy->isInstantiationDependentType();
4899     if (!IsDeclTyDependent) {
4900       if (!DeclTy->isIntegralType(Context) && !DeclTy->isAnyPointerType()) {
4901         // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++
4902         // The iterator-type must be an integral or pointer type.
4903         Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer)
4904             << DeclTy;
4905         IsCorrect = false;
4906         continue;
4907       }
4908       if (DeclTy.isConstant(Context)) {
4909         // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++
4910         // The iterator-type must not be const qualified.
4911         Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer)
4912             << DeclTy;
4913         IsCorrect = false;
4914         continue;
4915       }
4916     }
4917 
4918     // Iterator declaration.
4919     assert(D.DeclIdent && "Identifier expected.");
4920     // Always try to create iterator declarator to avoid extra error messages
4921     // about unknown declarations use.
4922     auto *VD = VarDecl::Create(Context, CurContext, StartLoc, D.DeclIdentLoc,
4923                                D.DeclIdent, DeclTy, TInfo, SC_None);
4924     VD->setImplicit();
4925     if (S) {
4926       // Check for conflicting previous declaration.
4927       DeclarationNameInfo NameInfo(VD->getDeclName(), D.DeclIdentLoc);
4928       LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
4929                             ForVisibleRedeclaration);
4930       Previous.suppressDiagnostics();
4931       LookupName(Previous, S);
4932 
4933       FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false,
4934                            /*AllowInlineNamespace=*/false);
4935       if (!Previous.empty()) {
4936         NamedDecl *Old = Previous.getRepresentativeDecl();
4937         Diag(D.DeclIdentLoc, diag::err_redefinition) << VD->getDeclName();
4938         Diag(Old->getLocation(), diag::note_previous_definition);
4939       } else {
4940         PushOnScopeChains(VD, S);
4941       }
4942     } else {
4943       CurContext->addDecl(VD);
4944     }
4945     Expr *Begin = D.Range.Begin;
4946     if (!IsDeclTyDependent && Begin && !Begin->isTypeDependent()) {
4947       ExprResult BeginRes =
4948           PerformImplicitConversion(Begin, DeclTy, AA_Converting);
4949       Begin = BeginRes.get();
4950     }
4951     Expr *End = D.Range.End;
4952     if (!IsDeclTyDependent && End && !End->isTypeDependent()) {
4953       ExprResult EndRes = PerformImplicitConversion(End, DeclTy, AA_Converting);
4954       End = EndRes.get();
4955     }
4956     Expr *Step = D.Range.Step;
4957     if (!IsDeclTyDependent && Step && !Step->isTypeDependent()) {
4958       if (!Step->getType()->isIntegralType(Context)) {
4959         Diag(Step->getExprLoc(), diag::err_omp_iterator_step_not_integral)
4960             << Step << Step->getSourceRange();
4961         IsCorrect = false;
4962         continue;
4963       }
4964       llvm::APSInt Result;
4965       bool IsConstant = Step->isIntegerConstantExpr(Result, Context);
4966       // OpenMP 5.0, 2.1.6 Iterators, Restrictions
4967       // If the step expression of a range-specification equals zero, the
4968       // behavior is unspecified.
4969       if (IsConstant && Result.isNullValue()) {
4970         Diag(Step->getExprLoc(), diag::err_omp_iterator_step_constant_zero)
4971             << Step << Step->getSourceRange();
4972         IsCorrect = false;
4973         continue;
4974       }
4975     }
4976     if (!Begin || !End || !IsCorrect) {
4977       IsCorrect = false;
4978       continue;
4979     }
4980     OMPIteratorExpr::IteratorDefinition &IDElem = ID.emplace_back();
4981     IDElem.IteratorDecl = VD;
4982     IDElem.AssignmentLoc = D.AssignLoc;
4983     IDElem.Range.Begin = Begin;
4984     IDElem.Range.End = End;
4985     IDElem.Range.Step = Step;
4986     IDElem.ColonLoc = D.ColonLoc;
4987     IDElem.SecondColonLoc = D.SecColonLoc;
4988   }
4989   if (!IsCorrect) {
4990     // Invalidate all created iterator declarations if error is found.
4991     for (const OMPIteratorExpr::IteratorDefinition &D : ID) {
4992       if (Decl *ID = D.IteratorDecl)
4993         ID->setInvalidDecl();
4994     }
4995     return ExprError();
4996   }
4997   return OMPIteratorExpr::Create(Context, Context.OMPIteratorTy, IteratorKwLoc,
4998                                  LLoc, RLoc, ID);
4999 }
5000 
5001 ExprResult
5002 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
5003                                       Expr *Idx, SourceLocation RLoc) {
5004   Expr *LHSExp = Base;
5005   Expr *RHSExp = Idx;
5006 
5007   ExprValueKind VK = VK_LValue;
5008   ExprObjectKind OK = OK_Ordinary;
5009 
5010   // Per C++ core issue 1213, the result is an xvalue if either operand is
5011   // a non-lvalue array, and an lvalue otherwise.
5012   if (getLangOpts().CPlusPlus11) {
5013     for (auto *Op : {LHSExp, RHSExp}) {
5014       Op = Op->IgnoreImplicit();
5015       if (Op->getType()->isArrayType() && !Op->isLValue())
5016         VK = VK_XValue;
5017     }
5018   }
5019 
5020   // Perform default conversions.
5021   if (!LHSExp->getType()->getAs<VectorType>()) {
5022     ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
5023     if (Result.isInvalid())
5024       return ExprError();
5025     LHSExp = Result.get();
5026   }
5027   ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
5028   if (Result.isInvalid())
5029     return ExprError();
5030   RHSExp = Result.get();
5031 
5032   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
5033 
5034   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
5035   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
5036   // in the subscript position. As a result, we need to derive the array base
5037   // and index from the expression types.
5038   Expr *BaseExpr, *IndexExpr;
5039   QualType ResultType;
5040   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
5041     BaseExpr = LHSExp;
5042     IndexExpr = RHSExp;
5043     ResultType = Context.DependentTy;
5044   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
5045     BaseExpr = LHSExp;
5046     IndexExpr = RHSExp;
5047     ResultType = PTy->getPointeeType();
5048   } else if (const ObjCObjectPointerType *PTy =
5049                LHSTy->getAs<ObjCObjectPointerType>()) {
5050     BaseExpr = LHSExp;
5051     IndexExpr = RHSExp;
5052 
5053     // Use custom logic if this should be the pseudo-object subscript
5054     // expression.
5055     if (!LangOpts.isSubscriptPointerArithmetic())
5056       return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
5057                                           nullptr);
5058 
5059     ResultType = PTy->getPointeeType();
5060   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
5061      // Handle the uncommon case of "123[Ptr]".
5062     BaseExpr = RHSExp;
5063     IndexExpr = LHSExp;
5064     ResultType = PTy->getPointeeType();
5065   } else if (const ObjCObjectPointerType *PTy =
5066                RHSTy->getAs<ObjCObjectPointerType>()) {
5067      // Handle the uncommon case of "123[Ptr]".
5068     BaseExpr = RHSExp;
5069     IndexExpr = LHSExp;
5070     ResultType = PTy->getPointeeType();
5071     if (!LangOpts.isSubscriptPointerArithmetic()) {
5072       Diag(LLoc, diag::err_subscript_nonfragile_interface)
5073         << ResultType << BaseExpr->getSourceRange();
5074       return ExprError();
5075     }
5076   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
5077     BaseExpr = LHSExp;    // vectors: V[123]
5078     IndexExpr = RHSExp;
5079     // We apply C++ DR1213 to vector subscripting too.
5080     if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_RValue) {
5081       ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
5082       if (Materialized.isInvalid())
5083         return ExprError();
5084       LHSExp = Materialized.get();
5085     }
5086     VK = LHSExp->getValueKind();
5087     if (VK != VK_RValue)
5088       OK = OK_VectorComponent;
5089 
5090     ResultType = VTy->getElementType();
5091     QualType BaseType = BaseExpr->getType();
5092     Qualifiers BaseQuals = BaseType.getQualifiers();
5093     Qualifiers MemberQuals = ResultType.getQualifiers();
5094     Qualifiers Combined = BaseQuals + MemberQuals;
5095     if (Combined != MemberQuals)
5096       ResultType = Context.getQualifiedType(ResultType, Combined);
5097   } else if (LHSTy->isArrayType()) {
5098     // If we see an array that wasn't promoted by
5099     // DefaultFunctionArrayLvalueConversion, it must be an array that
5100     // wasn't promoted because of the C90 rule that doesn't
5101     // allow promoting non-lvalue arrays.  Warn, then
5102     // force the promotion here.
5103     Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5104         << LHSExp->getSourceRange();
5105     LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
5106                                CK_ArrayToPointerDecay).get();
5107     LHSTy = LHSExp->getType();
5108 
5109     BaseExpr = LHSExp;
5110     IndexExpr = RHSExp;
5111     ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
5112   } else if (RHSTy->isArrayType()) {
5113     // Same as previous, except for 123[f().a] case
5114     Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5115         << RHSExp->getSourceRange();
5116     RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
5117                                CK_ArrayToPointerDecay).get();
5118     RHSTy = RHSExp->getType();
5119 
5120     BaseExpr = RHSExp;
5121     IndexExpr = LHSExp;
5122     ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
5123   } else {
5124     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
5125        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
5126   }
5127   // C99 6.5.2.1p1
5128   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
5129     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
5130                      << IndexExpr->getSourceRange());
5131 
5132   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5133        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5134          && !IndexExpr->isTypeDependent())
5135     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
5136 
5137   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5138   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5139   // type. Note that Functions are not objects, and that (in C99 parlance)
5140   // incomplete types are not object types.
5141   if (ResultType->isFunctionType()) {
5142     Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type)
5143         << ResultType << BaseExpr->getSourceRange();
5144     return ExprError();
5145   }
5146 
5147   if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
5148     // GNU extension: subscripting on pointer to void
5149     Diag(LLoc, diag::ext_gnu_subscript_void_type)
5150       << BaseExpr->getSourceRange();
5151 
5152     // C forbids expressions of unqualified void type from being l-values.
5153     // See IsCForbiddenLValueType.
5154     if (!ResultType.hasQualifiers()) VK = VK_RValue;
5155   } else if (!ResultType->isDependentType() &&
5156              RequireCompleteSizedType(
5157                  LLoc, ResultType,
5158                  diag::err_subscript_incomplete_or_sizeless_type, BaseExpr))
5159     return ExprError();
5160 
5161   assert(VK == VK_RValue || LangOpts.CPlusPlus ||
5162          !ResultType.isCForbiddenLValueType());
5163 
5164   if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() &&
5165       FunctionScopes.size() > 1) {
5166     if (auto *TT =
5167             LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) {
5168       for (auto I = FunctionScopes.rbegin(),
5169                 E = std::prev(FunctionScopes.rend());
5170            I != E; ++I) {
5171         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
5172         if (CSI == nullptr)
5173           break;
5174         DeclContext *DC = nullptr;
5175         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
5176           DC = LSI->CallOperator;
5177         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
5178           DC = CRSI->TheCapturedDecl;
5179         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
5180           DC = BSI->TheDecl;
5181         if (DC) {
5182           if (DC->containsDecl(TT->getDecl()))
5183             break;
5184           captureVariablyModifiedType(
5185               Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI);
5186         }
5187       }
5188     }
5189   }
5190 
5191   return new (Context)
5192       ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
5193 }
5194 
5195 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
5196                                   ParmVarDecl *Param) {
5197   if (Param->hasUnparsedDefaultArg()) {
5198     Diag(CallLoc,
5199          diag::err_use_of_default_argument_to_function_declared_later) <<
5200       FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
5201     Diag(UnparsedDefaultArgLocs[Param],
5202          diag::note_default_argument_declared_here);
5203     return true;
5204   }
5205 
5206   if (Param->hasUninstantiatedDefaultArg()) {
5207     Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
5208 
5209     EnterExpressionEvaluationContext EvalContext(
5210         *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
5211 
5212     // Instantiate the expression.
5213     //
5214     // FIXME: Pass in a correct Pattern argument, otherwise
5215     // getTemplateInstantiationArgs uses the lexical context of FD, e.g.
5216     //
5217     // template<typename T>
5218     // struct A {
5219     //   static int FooImpl();
5220     //
5221     //   template<typename Tp>
5222     //   // bug: default argument A<T>::FooImpl() is evaluated with 2-level
5223     //   // template argument list [[T], [Tp]], should be [[Tp]].
5224     //   friend A<Tp> Foo(int a);
5225     // };
5226     //
5227     // template<typename T>
5228     // A<T> Foo(int a = A<T>::FooImpl());
5229     MultiLevelTemplateArgumentList MutiLevelArgList
5230       = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true);
5231 
5232     InstantiatingTemplate Inst(*this, CallLoc, Param,
5233                                MutiLevelArgList.getInnermost());
5234     if (Inst.isInvalid())
5235       return true;
5236     if (Inst.isAlreadyInstantiating()) {
5237       Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
5238       Param->setInvalidDecl();
5239       return true;
5240     }
5241 
5242     ExprResult Result;
5243     {
5244       // C++ [dcl.fct.default]p5:
5245       //   The names in the [default argument] expression are bound, and
5246       //   the semantic constraints are checked, at the point where the
5247       //   default argument expression appears.
5248       ContextRAII SavedContext(*this, FD);
5249       LocalInstantiationScope Local(*this);
5250       runWithSufficientStackSpace(CallLoc, [&] {
5251         Result = SubstInitializer(UninstExpr, MutiLevelArgList,
5252                                   /*DirectInit*/false);
5253       });
5254     }
5255     if (Result.isInvalid())
5256       return true;
5257 
5258     // Check the expression as an initializer for the parameter.
5259     InitializedEntity Entity
5260       = InitializedEntity::InitializeParameter(Context, Param);
5261     InitializationKind Kind = InitializationKind::CreateCopy(
5262         Param->getLocation(),
5263         /*FIXME:EqualLoc*/ UninstExpr->getBeginLoc());
5264     Expr *ResultE = Result.getAs<Expr>();
5265 
5266     InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
5267     Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
5268     if (Result.isInvalid())
5269       return true;
5270 
5271     Result =
5272         ActOnFinishFullExpr(Result.getAs<Expr>(), Param->getOuterLocStart(),
5273                             /*DiscardedValue*/ false);
5274     if (Result.isInvalid())
5275       return true;
5276 
5277     // Remember the instantiated default argument.
5278     Param->setDefaultArg(Result.getAs<Expr>());
5279     if (ASTMutationListener *L = getASTMutationListener()) {
5280       L->DefaultArgumentInstantiated(Param);
5281     }
5282   }
5283 
5284   // If the default argument expression is not set yet, we are building it now.
5285   if (!Param->hasInit()) {
5286     Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
5287     Param->setInvalidDecl();
5288     return true;
5289   }
5290 
5291   // If the default expression creates temporaries, we need to
5292   // push them to the current stack of expression temporaries so they'll
5293   // be properly destroyed.
5294   // FIXME: We should really be rebuilding the default argument with new
5295   // bound temporaries; see the comment in PR5810.
5296   // We don't need to do that with block decls, though, because
5297   // blocks in default argument expression can never capture anything.
5298   if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
5299     // Set the "needs cleanups" bit regardless of whether there are
5300     // any explicit objects.
5301     Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
5302 
5303     // Append all the objects to the cleanup list.  Right now, this
5304     // should always be a no-op, because blocks in default argument
5305     // expressions should never be able to capture anything.
5306     assert(!Init->getNumObjects() &&
5307            "default argument expression has capturing blocks?");
5308   }
5309 
5310   // We already type-checked the argument, so we know it works.
5311   // Just mark all of the declarations in this potentially-evaluated expression
5312   // as being "referenced".
5313   EnterExpressionEvaluationContext EvalContext(
5314       *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
5315   MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
5316                                    /*SkipLocalVariables=*/true);
5317   return false;
5318 }
5319 
5320 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
5321                                         FunctionDecl *FD, ParmVarDecl *Param) {
5322   if (CheckCXXDefaultArgExpr(CallLoc, FD, Param))
5323     return ExprError();
5324   return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext);
5325 }
5326 
5327 Sema::VariadicCallType
5328 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
5329                           Expr *Fn) {
5330   if (Proto && Proto->isVariadic()) {
5331     if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
5332       return VariadicConstructor;
5333     else if (Fn && Fn->getType()->isBlockPointerType())
5334       return VariadicBlock;
5335     else if (FDecl) {
5336       if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5337         if (Method->isInstance())
5338           return VariadicMethod;
5339     } else if (Fn && Fn->getType() == Context.BoundMemberTy)
5340       return VariadicMethod;
5341     return VariadicFunction;
5342   }
5343   return VariadicDoesNotApply;
5344 }
5345 
5346 namespace {
5347 class FunctionCallCCC final : public FunctionCallFilterCCC {
5348 public:
5349   FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
5350                   unsigned NumArgs, MemberExpr *ME)
5351       : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
5352         FunctionName(FuncName) {}
5353 
5354   bool ValidateCandidate(const TypoCorrection &candidate) override {
5355     if (!candidate.getCorrectionSpecifier() ||
5356         candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
5357       return false;
5358     }
5359 
5360     return FunctionCallFilterCCC::ValidateCandidate(candidate);
5361   }
5362 
5363   std::unique_ptr<CorrectionCandidateCallback> clone() override {
5364     return std::make_unique<FunctionCallCCC>(*this);
5365   }
5366 
5367 private:
5368   const IdentifierInfo *const FunctionName;
5369 };
5370 }
5371 
5372 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
5373                                                FunctionDecl *FDecl,
5374                                                ArrayRef<Expr *> Args) {
5375   MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
5376   DeclarationName FuncName = FDecl->getDeclName();
5377   SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
5378 
5379   FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
5380   if (TypoCorrection Corrected = S.CorrectTypo(
5381           DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
5382           S.getScopeForContext(S.CurContext), nullptr, CCC,
5383           Sema::CTK_ErrorRecovery)) {
5384     if (NamedDecl *ND = Corrected.getFoundDecl()) {
5385       if (Corrected.isOverloaded()) {
5386         OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
5387         OverloadCandidateSet::iterator Best;
5388         for (NamedDecl *CD : Corrected) {
5389           if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
5390             S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
5391                                    OCS);
5392         }
5393         switch (OCS.BestViableFunction(S, NameLoc, Best)) {
5394         case OR_Success:
5395           ND = Best->FoundDecl;
5396           Corrected.setCorrectionDecl(ND);
5397           break;
5398         default:
5399           break;
5400         }
5401       }
5402       ND = ND->getUnderlyingDecl();
5403       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
5404         return Corrected;
5405     }
5406   }
5407   return TypoCorrection();
5408 }
5409 
5410 /// ConvertArgumentsForCall - Converts the arguments specified in
5411 /// Args/NumArgs to the parameter types of the function FDecl with
5412 /// function prototype Proto. Call is the call expression itself, and
5413 /// Fn is the function expression. For a C++ member function, this
5414 /// routine does not attempt to convert the object argument. Returns
5415 /// true if the call is ill-formed.
5416 bool
5417 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
5418                               FunctionDecl *FDecl,
5419                               const FunctionProtoType *Proto,
5420                               ArrayRef<Expr *> Args,
5421                               SourceLocation RParenLoc,
5422                               bool IsExecConfig) {
5423   // Bail out early if calling a builtin with custom typechecking.
5424   if (FDecl)
5425     if (unsigned ID = FDecl->getBuiltinID())
5426       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
5427         return false;
5428 
5429   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
5430   // assignment, to the types of the corresponding parameter, ...
5431   unsigned NumParams = Proto->getNumParams();
5432   bool Invalid = false;
5433   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
5434   unsigned FnKind = Fn->getType()->isBlockPointerType()
5435                        ? 1 /* block */
5436                        : (IsExecConfig ? 3 /* kernel function (exec config) */
5437                                        : 0 /* function */);
5438 
5439   // If too few arguments are available (and we don't have default
5440   // arguments for the remaining parameters), don't make the call.
5441   if (Args.size() < NumParams) {
5442     if (Args.size() < MinArgs) {
5443       TypoCorrection TC;
5444       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5445         unsigned diag_id =
5446             MinArgs == NumParams && !Proto->isVariadic()
5447                 ? diag::err_typecheck_call_too_few_args_suggest
5448                 : diag::err_typecheck_call_too_few_args_at_least_suggest;
5449         diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
5450                                         << static_cast<unsigned>(Args.size())
5451                                         << TC.getCorrectionRange());
5452       } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
5453         Diag(RParenLoc,
5454              MinArgs == NumParams && !Proto->isVariadic()
5455                  ? diag::err_typecheck_call_too_few_args_one
5456                  : diag::err_typecheck_call_too_few_args_at_least_one)
5457             << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
5458       else
5459         Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
5460                             ? diag::err_typecheck_call_too_few_args
5461                             : diag::err_typecheck_call_too_few_args_at_least)
5462             << FnKind << MinArgs << static_cast<unsigned>(Args.size())
5463             << Fn->getSourceRange();
5464 
5465       // Emit the location of the prototype.
5466       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5467         Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
5468 
5469       return true;
5470     }
5471     // We reserve space for the default arguments when we create
5472     // the call expression, before calling ConvertArgumentsForCall.
5473     assert((Call->getNumArgs() == NumParams) &&
5474            "We should have reserved space for the default arguments before!");
5475   }
5476 
5477   // If too many are passed and not variadic, error on the extras and drop
5478   // them.
5479   if (Args.size() > NumParams) {
5480     if (!Proto->isVariadic()) {
5481       TypoCorrection TC;
5482       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5483         unsigned diag_id =
5484             MinArgs == NumParams && !Proto->isVariadic()
5485                 ? diag::err_typecheck_call_too_many_args_suggest
5486                 : diag::err_typecheck_call_too_many_args_at_most_suggest;
5487         diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
5488                                         << static_cast<unsigned>(Args.size())
5489                                         << TC.getCorrectionRange());
5490       } else if (NumParams == 1 && FDecl &&
5491                  FDecl->getParamDecl(0)->getDeclName())
5492         Diag(Args[NumParams]->getBeginLoc(),
5493              MinArgs == NumParams
5494                  ? diag::err_typecheck_call_too_many_args_one
5495                  : diag::err_typecheck_call_too_many_args_at_most_one)
5496             << FnKind << FDecl->getParamDecl(0)
5497             << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
5498             << SourceRange(Args[NumParams]->getBeginLoc(),
5499                            Args.back()->getEndLoc());
5500       else
5501         Diag(Args[NumParams]->getBeginLoc(),
5502              MinArgs == NumParams
5503                  ? diag::err_typecheck_call_too_many_args
5504                  : diag::err_typecheck_call_too_many_args_at_most)
5505             << FnKind << NumParams << static_cast<unsigned>(Args.size())
5506             << Fn->getSourceRange()
5507             << SourceRange(Args[NumParams]->getBeginLoc(),
5508                            Args.back()->getEndLoc());
5509 
5510       // Emit the location of the prototype.
5511       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5512         Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
5513 
5514       // This deletes the extra arguments.
5515       Call->shrinkNumArgs(NumParams);
5516       return true;
5517     }
5518   }
5519   SmallVector<Expr *, 8> AllArgs;
5520   VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
5521 
5522   Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args,
5523                                    AllArgs, CallType);
5524   if (Invalid)
5525     return true;
5526   unsigned TotalNumArgs = AllArgs.size();
5527   for (unsigned i = 0; i < TotalNumArgs; ++i)
5528     Call->setArg(i, AllArgs[i]);
5529 
5530   return false;
5531 }
5532 
5533 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
5534                                   const FunctionProtoType *Proto,
5535                                   unsigned FirstParam, ArrayRef<Expr *> Args,
5536                                   SmallVectorImpl<Expr *> &AllArgs,
5537                                   VariadicCallType CallType, bool AllowExplicit,
5538                                   bool IsListInitialization) {
5539   unsigned NumParams = Proto->getNumParams();
5540   bool Invalid = false;
5541   size_t ArgIx = 0;
5542   // Continue to check argument types (even if we have too few/many args).
5543   for (unsigned i = FirstParam; i < NumParams; i++) {
5544     QualType ProtoArgType = Proto->getParamType(i);
5545 
5546     Expr *Arg;
5547     ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
5548     if (ArgIx < Args.size()) {
5549       Arg = Args[ArgIx++];
5550 
5551       if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType,
5552                               diag::err_call_incomplete_argument, Arg))
5553         return true;
5554 
5555       // Strip the unbridged-cast placeholder expression off, if applicable.
5556       bool CFAudited = false;
5557       if (Arg->getType() == Context.ARCUnbridgedCastTy &&
5558           FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5559           (!Param || !Param->hasAttr<CFConsumedAttr>()))
5560         Arg = stripARCUnbridgedCast(Arg);
5561       else if (getLangOpts().ObjCAutoRefCount &&
5562                FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5563                (!Param || !Param->hasAttr<CFConsumedAttr>()))
5564         CFAudited = true;
5565 
5566       if (Proto->getExtParameterInfo(i).isNoEscape())
5567         if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
5568           BE->getBlockDecl()->setDoesNotEscape();
5569 
5570       InitializedEntity Entity =
5571           Param ? InitializedEntity::InitializeParameter(Context, Param,
5572                                                          ProtoArgType)
5573                 : InitializedEntity::InitializeParameter(
5574                       Context, ProtoArgType, Proto->isParamConsumed(i));
5575 
5576       // Remember that parameter belongs to a CF audited API.
5577       if (CFAudited)
5578         Entity.setParameterCFAudited();
5579 
5580       ExprResult ArgE = PerformCopyInitialization(
5581           Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
5582       if (ArgE.isInvalid())
5583         return true;
5584 
5585       Arg = ArgE.getAs<Expr>();
5586     } else {
5587       assert(Param && "can't use default arguments without a known callee");
5588 
5589       ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
5590       if (ArgExpr.isInvalid())
5591         return true;
5592 
5593       Arg = ArgExpr.getAs<Expr>();
5594     }
5595 
5596     // Check for array bounds violations for each argument to the call. This
5597     // check only triggers warnings when the argument isn't a more complex Expr
5598     // with its own checking, such as a BinaryOperator.
5599     CheckArrayAccess(Arg);
5600 
5601     // Check for violations of C99 static array rules (C99 6.7.5.3p7).
5602     CheckStaticArrayArgument(CallLoc, Param, Arg);
5603 
5604     AllArgs.push_back(Arg);
5605   }
5606 
5607   // If this is a variadic call, handle args passed through "...".
5608   if (CallType != VariadicDoesNotApply) {
5609     // Assume that extern "C" functions with variadic arguments that
5610     // return __unknown_anytype aren't *really* variadic.
5611     if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
5612         FDecl->isExternC()) {
5613       for (Expr *A : Args.slice(ArgIx)) {
5614         QualType paramType; // ignored
5615         ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
5616         Invalid |= arg.isInvalid();
5617         AllArgs.push_back(arg.get());
5618       }
5619 
5620     // Otherwise do argument promotion, (C99 6.5.2.2p7).
5621     } else {
5622       for (Expr *A : Args.slice(ArgIx)) {
5623         ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
5624         Invalid |= Arg.isInvalid();
5625         // Copy blocks to the heap.
5626         if (A->getType()->isBlockPointerType())
5627           maybeExtendBlockObject(Arg);
5628         AllArgs.push_back(Arg.get());
5629       }
5630     }
5631 
5632     // Check for array bounds violations.
5633     for (Expr *A : Args.slice(ArgIx))
5634       CheckArrayAccess(A);
5635   }
5636   return Invalid;
5637 }
5638 
5639 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
5640   TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
5641   if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
5642     TL = DTL.getOriginalLoc();
5643   if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
5644     S.Diag(PVD->getLocation(), diag::note_callee_static_array)
5645       << ATL.getLocalSourceRange();
5646 }
5647 
5648 /// CheckStaticArrayArgument - If the given argument corresponds to a static
5649 /// array parameter, check that it is non-null, and that if it is formed by
5650 /// array-to-pointer decay, the underlying array is sufficiently large.
5651 ///
5652 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
5653 /// array type derivation, then for each call to the function, the value of the
5654 /// corresponding actual argument shall provide access to the first element of
5655 /// an array with at least as many elements as specified by the size expression.
5656 void
5657 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
5658                                ParmVarDecl *Param,
5659                                const Expr *ArgExpr) {
5660   // Static array parameters are not supported in C++.
5661   if (!Param || getLangOpts().CPlusPlus)
5662     return;
5663 
5664   QualType OrigTy = Param->getOriginalType();
5665 
5666   const ArrayType *AT = Context.getAsArrayType(OrigTy);
5667   if (!AT || AT->getSizeModifier() != ArrayType::Static)
5668     return;
5669 
5670   if (ArgExpr->isNullPointerConstant(Context,
5671                                      Expr::NPC_NeverValueDependent)) {
5672     Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
5673     DiagnoseCalleeStaticArrayParam(*this, Param);
5674     return;
5675   }
5676 
5677   const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
5678   if (!CAT)
5679     return;
5680 
5681   const ConstantArrayType *ArgCAT =
5682     Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType());
5683   if (!ArgCAT)
5684     return;
5685 
5686   if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(),
5687                                              ArgCAT->getElementType())) {
5688     if (ArgCAT->getSize().ult(CAT->getSize())) {
5689       Diag(CallLoc, diag::warn_static_array_too_small)
5690           << ArgExpr->getSourceRange()
5691           << (unsigned)ArgCAT->getSize().getZExtValue()
5692           << (unsigned)CAT->getSize().getZExtValue() << 0;
5693       DiagnoseCalleeStaticArrayParam(*this, Param);
5694     }
5695     return;
5696   }
5697 
5698   Optional<CharUnits> ArgSize =
5699       getASTContext().getTypeSizeInCharsIfKnown(ArgCAT);
5700   Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT);
5701   if (ArgSize && ParmSize && *ArgSize < *ParmSize) {
5702     Diag(CallLoc, diag::warn_static_array_too_small)
5703         << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()
5704         << (unsigned)ParmSize->getQuantity() << 1;
5705     DiagnoseCalleeStaticArrayParam(*this, Param);
5706   }
5707 }
5708 
5709 /// Given a function expression of unknown-any type, try to rebuild it
5710 /// to have a function type.
5711 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
5712 
5713 /// Is the given type a placeholder that we need to lower out
5714 /// immediately during argument processing?
5715 static bool isPlaceholderToRemoveAsArg(QualType type) {
5716   // Placeholders are never sugared.
5717   const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
5718   if (!placeholder) return false;
5719 
5720   switch (placeholder->getKind()) {
5721   // Ignore all the non-placeholder types.
5722 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
5723   case BuiltinType::Id:
5724 #include "clang/Basic/OpenCLImageTypes.def"
5725 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
5726   case BuiltinType::Id:
5727 #include "clang/Basic/OpenCLExtensionTypes.def"
5728   // In practice we'll never use this, since all SVE types are sugared
5729   // via TypedefTypes rather than exposed directly as BuiltinTypes.
5730 #define SVE_TYPE(Name, Id, SingletonId) \
5731   case BuiltinType::Id:
5732 #include "clang/Basic/AArch64SVEACLETypes.def"
5733 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
5734 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
5735 #include "clang/AST/BuiltinTypes.def"
5736     return false;
5737 
5738   // We cannot lower out overload sets; they might validly be resolved
5739   // by the call machinery.
5740   case BuiltinType::Overload:
5741     return false;
5742 
5743   // Unbridged casts in ARC can be handled in some call positions and
5744   // should be left in place.
5745   case BuiltinType::ARCUnbridgedCast:
5746     return false;
5747 
5748   // Pseudo-objects should be converted as soon as possible.
5749   case BuiltinType::PseudoObject:
5750     return true;
5751 
5752   // The debugger mode could theoretically but currently does not try
5753   // to resolve unknown-typed arguments based on known parameter types.
5754   case BuiltinType::UnknownAny:
5755     return true;
5756 
5757   // These are always invalid as call arguments and should be reported.
5758   case BuiltinType::BoundMember:
5759   case BuiltinType::BuiltinFn:
5760   case BuiltinType::OMPArraySection:
5761   case BuiltinType::OMPArrayShaping:
5762   case BuiltinType::OMPIterator:
5763     return true;
5764 
5765   }
5766   llvm_unreachable("bad builtin type kind");
5767 }
5768 
5769 /// Check an argument list for placeholders that we won't try to
5770 /// handle later.
5771 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
5772   // Apply this processing to all the arguments at once instead of
5773   // dying at the first failure.
5774   bool hasInvalid = false;
5775   for (size_t i = 0, e = args.size(); i != e; i++) {
5776     if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
5777       ExprResult result = S.CheckPlaceholderExpr(args[i]);
5778       if (result.isInvalid()) hasInvalid = true;
5779       else args[i] = result.get();
5780     } else if (hasInvalid) {
5781       (void)S.CorrectDelayedTyposInExpr(args[i]);
5782     }
5783   }
5784   return hasInvalid;
5785 }
5786 
5787 /// If a builtin function has a pointer argument with no explicit address
5788 /// space, then it should be able to accept a pointer to any address
5789 /// space as input.  In order to do this, we need to replace the
5790 /// standard builtin declaration with one that uses the same address space
5791 /// as the call.
5792 ///
5793 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
5794 ///                  it does not contain any pointer arguments without
5795 ///                  an address space qualifer.  Otherwise the rewritten
5796 ///                  FunctionDecl is returned.
5797 /// TODO: Handle pointer return types.
5798 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
5799                                                 FunctionDecl *FDecl,
5800                                                 MultiExprArg ArgExprs) {
5801 
5802   QualType DeclType = FDecl->getType();
5803   const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
5804 
5805   if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT ||
5806       ArgExprs.size() < FT->getNumParams())
5807     return nullptr;
5808 
5809   bool NeedsNewDecl = false;
5810   unsigned i = 0;
5811   SmallVector<QualType, 8> OverloadParams;
5812 
5813   for (QualType ParamType : FT->param_types()) {
5814 
5815     // Convert array arguments to pointer to simplify type lookup.
5816     ExprResult ArgRes =
5817         Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
5818     if (ArgRes.isInvalid())
5819       return nullptr;
5820     Expr *Arg = ArgRes.get();
5821     QualType ArgType = Arg->getType();
5822     if (!ParamType->isPointerType() ||
5823         ParamType.hasAddressSpace() ||
5824         !ArgType->isPointerType() ||
5825         !ArgType->getPointeeType().hasAddressSpace()) {
5826       OverloadParams.push_back(ParamType);
5827       continue;
5828     }
5829 
5830     QualType PointeeType = ParamType->getPointeeType();
5831     if (PointeeType.hasAddressSpace())
5832       continue;
5833 
5834     NeedsNewDecl = true;
5835     LangAS AS = ArgType->getPointeeType().getAddressSpace();
5836 
5837     PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
5838     OverloadParams.push_back(Context.getPointerType(PointeeType));
5839   }
5840 
5841   if (!NeedsNewDecl)
5842     return nullptr;
5843 
5844   FunctionProtoType::ExtProtoInfo EPI;
5845   EPI.Variadic = FT->isVariadic();
5846   QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
5847                                                 OverloadParams, EPI);
5848   DeclContext *Parent = FDecl->getParent();
5849   FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
5850                                                     FDecl->getLocation(),
5851                                                     FDecl->getLocation(),
5852                                                     FDecl->getIdentifier(),
5853                                                     OverloadTy,
5854                                                     /*TInfo=*/nullptr,
5855                                                     SC_Extern, false,
5856                                                     /*hasPrototype=*/true);
5857   SmallVector<ParmVarDecl*, 16> Params;
5858   FT = cast<FunctionProtoType>(OverloadTy);
5859   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
5860     QualType ParamType = FT->getParamType(i);
5861     ParmVarDecl *Parm =
5862         ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
5863                                 SourceLocation(), nullptr, ParamType,
5864                                 /*TInfo=*/nullptr, SC_None, nullptr);
5865     Parm->setScopeInfo(0, i);
5866     Params.push_back(Parm);
5867   }
5868   OverloadDecl->setParams(Params);
5869   return OverloadDecl;
5870 }
5871 
5872 static void checkDirectCallValidity(Sema &S, const Expr *Fn,
5873                                     FunctionDecl *Callee,
5874                                     MultiExprArg ArgExprs) {
5875   // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
5876   // similar attributes) really don't like it when functions are called with an
5877   // invalid number of args.
5878   if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
5879                          /*PartialOverloading=*/false) &&
5880       !Callee->isVariadic())
5881     return;
5882   if (Callee->getMinRequiredArguments() > ArgExprs.size())
5883     return;
5884 
5885   if (const EnableIfAttr *Attr = S.CheckEnableIf(Callee, ArgExprs, true)) {
5886     S.Diag(Fn->getBeginLoc(),
5887            isa<CXXMethodDecl>(Callee)
5888                ? diag::err_ovl_no_viable_member_function_in_call
5889                : diag::err_ovl_no_viable_function_in_call)
5890         << Callee << Callee->getSourceRange();
5891     S.Diag(Callee->getLocation(),
5892            diag::note_ovl_candidate_disabled_by_function_cond_attr)
5893         << Attr->getCond()->getSourceRange() << Attr->getMessage();
5894     return;
5895   }
5896 }
5897 
5898 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(
5899     const UnresolvedMemberExpr *const UME, Sema &S) {
5900 
5901   const auto GetFunctionLevelDCIfCXXClass =
5902       [](Sema &S) -> const CXXRecordDecl * {
5903     const DeclContext *const DC = S.getFunctionLevelDeclContext();
5904     if (!DC || !DC->getParent())
5905       return nullptr;
5906 
5907     // If the call to some member function was made from within a member
5908     // function body 'M' return return 'M's parent.
5909     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
5910       return MD->getParent()->getCanonicalDecl();
5911     // else the call was made from within a default member initializer of a
5912     // class, so return the class.
5913     if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
5914       return RD->getCanonicalDecl();
5915     return nullptr;
5916   };
5917   // If our DeclContext is neither a member function nor a class (in the
5918   // case of a lambda in a default member initializer), we can't have an
5919   // enclosing 'this'.
5920 
5921   const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
5922   if (!CurParentClass)
5923     return false;
5924 
5925   // The naming class for implicit member functions call is the class in which
5926   // name lookup starts.
5927   const CXXRecordDecl *const NamingClass =
5928       UME->getNamingClass()->getCanonicalDecl();
5929   assert(NamingClass && "Must have naming class even for implicit access");
5930 
5931   // If the unresolved member functions were found in a 'naming class' that is
5932   // related (either the same or derived from) to the class that contains the
5933   // member function that itself contained the implicit member access.
5934 
5935   return CurParentClass == NamingClass ||
5936          CurParentClass->isDerivedFrom(NamingClass);
5937 }
5938 
5939 static void
5940 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
5941     Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
5942 
5943   if (!UME)
5944     return;
5945 
5946   LambdaScopeInfo *const CurLSI = S.getCurLambda();
5947   // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
5948   // already been captured, or if this is an implicit member function call (if
5949   // it isn't, an attempt to capture 'this' should already have been made).
5950   if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
5951       !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
5952     return;
5953 
5954   // Check if the naming class in which the unresolved members were found is
5955   // related (same as or is a base of) to the enclosing class.
5956 
5957   if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S))
5958     return;
5959 
5960 
5961   DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
5962   // If the enclosing function is not dependent, then this lambda is
5963   // capture ready, so if we can capture this, do so.
5964   if (!EnclosingFunctionCtx->isDependentContext()) {
5965     // If the current lambda and all enclosing lambdas can capture 'this' -
5966     // then go ahead and capture 'this' (since our unresolved overload set
5967     // contains at least one non-static member function).
5968     if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
5969       S.CheckCXXThisCapture(CallLoc);
5970   } else if (S.CurContext->isDependentContext()) {
5971     // ... since this is an implicit member reference, that might potentially
5972     // involve a 'this' capture, mark 'this' for potential capture in
5973     // enclosing lambdas.
5974     if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
5975       CurLSI->addPotentialThisCapture(CallLoc);
5976   }
5977 }
5978 
5979 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
5980                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
5981                                Expr *ExecConfig) {
5982   ExprResult Call =
5983       BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig);
5984   if (Call.isInvalid())
5985     return Call;
5986 
5987   // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier
5988   // language modes.
5989   if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) {
5990     if (ULE->hasExplicitTemplateArgs() &&
5991         ULE->decls_begin() == ULE->decls_end()) {
5992       Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus2a
5993                                  ? diag::warn_cxx17_compat_adl_only_template_id
5994                                  : diag::ext_adl_only_template_id)
5995           << ULE->getName();
5996     }
5997   }
5998 
5999   if (LangOpts.OpenMP)
6000     Call = ActOnOpenMPCall(*this, Call, Scope, LParenLoc, ArgExprs, RParenLoc,
6001                            ExecConfig);
6002 
6003   return Call;
6004 }
6005 
6006 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments.
6007 /// This provides the location of the left/right parens and a list of comma
6008 /// locations.
6009 ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
6010                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
6011                                Expr *ExecConfig, bool IsExecConfig) {
6012   // Since this might be a postfix expression, get rid of ParenListExprs.
6013   ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
6014   if (Result.isInvalid()) return ExprError();
6015   Fn = Result.get();
6016 
6017   if (checkArgsForPlaceholders(*this, ArgExprs))
6018     return ExprError();
6019 
6020   if (getLangOpts().CPlusPlus) {
6021     // If this is a pseudo-destructor expression, build the call immediately.
6022     if (isa<CXXPseudoDestructorExpr>(Fn)) {
6023       if (!ArgExprs.empty()) {
6024         // Pseudo-destructor calls should not have any arguments.
6025         Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args)
6026             << FixItHint::CreateRemoval(
6027                    SourceRange(ArgExprs.front()->getBeginLoc(),
6028                                ArgExprs.back()->getEndLoc()));
6029       }
6030 
6031       return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy,
6032                               VK_RValue, RParenLoc);
6033     }
6034     if (Fn->getType() == Context.PseudoObjectTy) {
6035       ExprResult result = CheckPlaceholderExpr(Fn);
6036       if (result.isInvalid()) return ExprError();
6037       Fn = result.get();
6038     }
6039 
6040     // Determine whether this is a dependent call inside a C++ template,
6041     // in which case we won't do any semantic analysis now.
6042     if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) {
6043       if (ExecConfig) {
6044         return CUDAKernelCallExpr::Create(
6045             Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
6046             Context.DependentTy, VK_RValue, RParenLoc);
6047       } else {
6048 
6049         tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
6050             *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
6051             Fn->getBeginLoc());
6052 
6053         return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6054                                 VK_RValue, RParenLoc);
6055       }
6056     }
6057 
6058     // Determine whether this is a call to an object (C++ [over.call.object]).
6059     if (Fn->getType()->isRecordType())
6060       return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
6061                                           RParenLoc);
6062 
6063     if (Fn->getType() == Context.UnknownAnyTy) {
6064       ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6065       if (result.isInvalid()) return ExprError();
6066       Fn = result.get();
6067     }
6068 
6069     if (Fn->getType() == Context.BoundMemberTy) {
6070       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6071                                        RParenLoc);
6072     }
6073   }
6074 
6075   // Check for overloaded calls.  This can happen even in C due to extensions.
6076   if (Fn->getType() == Context.OverloadTy) {
6077     OverloadExpr::FindResult find = OverloadExpr::find(Fn);
6078 
6079     // We aren't supposed to apply this logic if there's an '&' involved.
6080     if (!find.HasFormOfMemberPointer) {
6081       if (Expr::hasAnyTypeDependentArguments(ArgExprs))
6082         return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6083                                 VK_RValue, RParenLoc);
6084       OverloadExpr *ovl = find.Expression;
6085       if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
6086         return BuildOverloadedCallExpr(
6087             Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6088             /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
6089       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6090                                        RParenLoc);
6091     }
6092   }
6093 
6094   // If we're directly calling a function, get the appropriate declaration.
6095   if (Fn->getType() == Context.UnknownAnyTy) {
6096     ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6097     if (result.isInvalid()) return ExprError();
6098     Fn = result.get();
6099   }
6100 
6101   Expr *NakedFn = Fn->IgnoreParens();
6102 
6103   bool CallingNDeclIndirectly = false;
6104   NamedDecl *NDecl = nullptr;
6105   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
6106     if (UnOp->getOpcode() == UO_AddrOf) {
6107       CallingNDeclIndirectly = true;
6108       NakedFn = UnOp->getSubExpr()->IgnoreParens();
6109     }
6110   }
6111 
6112   if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
6113     NDecl = DRE->getDecl();
6114 
6115     FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
6116     if (FDecl && FDecl->getBuiltinID()) {
6117       // Rewrite the function decl for this builtin by replacing parameters
6118       // with no explicit address space with the address space of the arguments
6119       // in ArgExprs.
6120       if ((FDecl =
6121                rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
6122         NDecl = FDecl;
6123         Fn = DeclRefExpr::Create(
6124             Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
6125             SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl,
6126             nullptr, DRE->isNonOdrUse());
6127       }
6128     }
6129   } else if (isa<MemberExpr>(NakedFn))
6130     NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
6131 
6132   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
6133     if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
6134                                       FD, /*Complain=*/true, Fn->getBeginLoc()))
6135       return ExprError();
6136 
6137     if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn))
6138       return ExprError();
6139 
6140     checkDirectCallValidity(*this, Fn, FD, ArgExprs);
6141   }
6142 
6143   return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
6144                                ExecConfig, IsExecConfig);
6145 }
6146 
6147 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
6148 ///
6149 /// __builtin_astype( value, dst type )
6150 ///
6151 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
6152                                  SourceLocation BuiltinLoc,
6153                                  SourceLocation RParenLoc) {
6154   ExprValueKind VK = VK_RValue;
6155   ExprObjectKind OK = OK_Ordinary;
6156   QualType DstTy = GetTypeFromParser(ParsedDestTy);
6157   QualType SrcTy = E->getType();
6158   if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
6159     return ExprError(Diag(BuiltinLoc,
6160                           diag::err_invalid_astype_of_different_size)
6161                      << DstTy
6162                      << SrcTy
6163                      << E->getSourceRange());
6164   return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
6165 }
6166 
6167 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
6168 /// provided arguments.
6169 ///
6170 /// __builtin_convertvector( value, dst type )
6171 ///
6172 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
6173                                         SourceLocation BuiltinLoc,
6174                                         SourceLocation RParenLoc) {
6175   TypeSourceInfo *TInfo;
6176   GetTypeFromParser(ParsedDestTy, &TInfo);
6177   return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
6178 }
6179 
6180 /// BuildResolvedCallExpr - Build a call to a resolved expression,
6181 /// i.e. an expression not of \p OverloadTy.  The expression should
6182 /// unary-convert to an expression of function-pointer or
6183 /// block-pointer type.
6184 ///
6185 /// \param NDecl the declaration being called, if available
6186 ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
6187                                        SourceLocation LParenLoc,
6188                                        ArrayRef<Expr *> Args,
6189                                        SourceLocation RParenLoc, Expr *Config,
6190                                        bool IsExecConfig, ADLCallKind UsesADL) {
6191   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
6192   unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
6193 
6194   // Functions with 'interrupt' attribute cannot be called directly.
6195   if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
6196     Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
6197     return ExprError();
6198   }
6199 
6200   // Interrupt handlers don't save off the VFP regs automatically on ARM,
6201   // so there's some risk when calling out to non-interrupt handler functions
6202   // that the callee might not preserve them. This is easy to diagnose here,
6203   // but can be very challenging to debug.
6204   if (auto *Caller = getCurFunctionDecl())
6205     if (Caller->hasAttr<ARMInterruptAttr>()) {
6206       bool VFP = Context.getTargetInfo().hasFeature("vfp");
6207       if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>()))
6208         Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention);
6209     }
6210 
6211   // Promote the function operand.
6212   // We special-case function promotion here because we only allow promoting
6213   // builtin functions to function pointers in the callee of a call.
6214   ExprResult Result;
6215   QualType ResultTy;
6216   if (BuiltinID &&
6217       Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
6218     // Extract the return type from the (builtin) function pointer type.
6219     // FIXME Several builtins still have setType in
6220     // Sema::CheckBuiltinFunctionCall. One should review their definitions in
6221     // Builtins.def to ensure they are correct before removing setType calls.
6222     QualType FnPtrTy = Context.getPointerType(FDecl->getType());
6223     Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get();
6224     ResultTy = FDecl->getCallResultType();
6225   } else {
6226     Result = CallExprUnaryConversions(Fn);
6227     ResultTy = Context.BoolTy;
6228   }
6229   if (Result.isInvalid())
6230     return ExprError();
6231   Fn = Result.get();
6232 
6233   // Check for a valid function type, but only if it is not a builtin which
6234   // requires custom type checking. These will be handled by
6235   // CheckBuiltinFunctionCall below just after creation of the call expression.
6236   const FunctionType *FuncT = nullptr;
6237   if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
6238   retry:
6239     if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
6240       // C99 6.5.2.2p1 - "The expression that denotes the called function shall
6241       // have type pointer to function".
6242       FuncT = PT->getPointeeType()->getAs<FunctionType>();
6243       if (!FuncT)
6244         return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
6245                          << Fn->getType() << Fn->getSourceRange());
6246     } else if (const BlockPointerType *BPT =
6247                    Fn->getType()->getAs<BlockPointerType>()) {
6248       FuncT = BPT->getPointeeType()->castAs<FunctionType>();
6249     } else {
6250       // Handle calls to expressions of unknown-any type.
6251       if (Fn->getType() == Context.UnknownAnyTy) {
6252         ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
6253         if (rewrite.isInvalid())
6254           return ExprError();
6255         Fn = rewrite.get();
6256         goto retry;
6257       }
6258 
6259       return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
6260                        << Fn->getType() << Fn->getSourceRange());
6261     }
6262   }
6263 
6264   // Get the number of parameters in the function prototype, if any.
6265   // We will allocate space for max(Args.size(), NumParams) arguments
6266   // in the call expression.
6267   const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT);
6268   unsigned NumParams = Proto ? Proto->getNumParams() : 0;
6269 
6270   CallExpr *TheCall;
6271   if (Config) {
6272     assert(UsesADL == ADLCallKind::NotADL &&
6273            "CUDAKernelCallExpr should not use ADL");
6274     TheCall =
6275         CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config), Args,
6276                                    ResultTy, VK_RValue, RParenLoc, NumParams);
6277   } else {
6278     TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue,
6279                                RParenLoc, NumParams, UsesADL);
6280   }
6281 
6282   if (!getLangOpts().CPlusPlus) {
6283     // Forget about the nulled arguments since typo correction
6284     // do not handle them well.
6285     TheCall->shrinkNumArgs(Args.size());
6286     // C cannot always handle TypoExpr nodes in builtin calls and direct
6287     // function calls as their argument checking don't necessarily handle
6288     // dependent types properly, so make sure any TypoExprs have been
6289     // dealt with.
6290     ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
6291     if (!Result.isUsable()) return ExprError();
6292     CallExpr *TheOldCall = TheCall;
6293     TheCall = dyn_cast<CallExpr>(Result.get());
6294     bool CorrectedTypos = TheCall != TheOldCall;
6295     if (!TheCall) return Result;
6296     Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
6297 
6298     // A new call expression node was created if some typos were corrected.
6299     // However it may not have been constructed with enough storage. In this
6300     // case, rebuild the node with enough storage. The waste of space is
6301     // immaterial since this only happens when some typos were corrected.
6302     if (CorrectedTypos && Args.size() < NumParams) {
6303       if (Config)
6304         TheCall = CUDAKernelCallExpr::Create(
6305             Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_RValue,
6306             RParenLoc, NumParams);
6307       else
6308         TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue,
6309                                    RParenLoc, NumParams, UsesADL);
6310     }
6311     // We can now handle the nulled arguments for the default arguments.
6312     TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams));
6313   }
6314 
6315   // Bail out early if calling a builtin with custom type checking.
6316   if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
6317     return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
6318 
6319   if (getLangOpts().CUDA) {
6320     if (Config) {
6321       // CUDA: Kernel calls must be to global functions
6322       if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
6323         return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
6324             << FDecl << Fn->getSourceRange());
6325 
6326       // CUDA: Kernel function must have 'void' return type
6327       if (!FuncT->getReturnType()->isVoidType() &&
6328           !FuncT->getReturnType()->getAs<AutoType>() &&
6329           !FuncT->getReturnType()->isInstantiationDependentType())
6330         return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
6331             << Fn->getType() << Fn->getSourceRange());
6332     } else {
6333       // CUDA: Calls to global functions must be configured
6334       if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
6335         return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
6336             << FDecl << Fn->getSourceRange());
6337     }
6338   }
6339 
6340   // Check for a valid return type
6341   if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall,
6342                           FDecl))
6343     return ExprError();
6344 
6345   // We know the result type of the call, set it.
6346   TheCall->setType(FuncT->getCallResultType(Context));
6347   TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
6348 
6349   if (Proto) {
6350     if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
6351                                 IsExecConfig))
6352       return ExprError();
6353   } else {
6354     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
6355 
6356     if (FDecl) {
6357       // Check if we have too few/too many template arguments, based
6358       // on our knowledge of the function definition.
6359       const FunctionDecl *Def = nullptr;
6360       if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
6361         Proto = Def->getType()->getAs<FunctionProtoType>();
6362        if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
6363           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
6364           << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
6365       }
6366 
6367       // If the function we're calling isn't a function prototype, but we have
6368       // a function prototype from a prior declaratiom, use that prototype.
6369       if (!FDecl->hasPrototype())
6370         Proto = FDecl->getType()->getAs<FunctionProtoType>();
6371     }
6372 
6373     // Promote the arguments (C99 6.5.2.2p6).
6374     for (unsigned i = 0, e = Args.size(); i != e; i++) {
6375       Expr *Arg = Args[i];
6376 
6377       if (Proto && i < Proto->getNumParams()) {
6378         InitializedEntity Entity = InitializedEntity::InitializeParameter(
6379             Context, Proto->getParamType(i), Proto->isParamConsumed(i));
6380         ExprResult ArgE =
6381             PerformCopyInitialization(Entity, SourceLocation(), Arg);
6382         if (ArgE.isInvalid())
6383           return true;
6384 
6385         Arg = ArgE.getAs<Expr>();
6386 
6387       } else {
6388         ExprResult ArgE = DefaultArgumentPromotion(Arg);
6389 
6390         if (ArgE.isInvalid())
6391           return true;
6392 
6393         Arg = ArgE.getAs<Expr>();
6394       }
6395 
6396       if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(),
6397                               diag::err_call_incomplete_argument, Arg))
6398         return ExprError();
6399 
6400       TheCall->setArg(i, Arg);
6401     }
6402   }
6403 
6404   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
6405     if (!Method->isStatic())
6406       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
6407         << Fn->getSourceRange());
6408 
6409   // Check for sentinels
6410   if (NDecl)
6411     DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
6412 
6413   // Do special checking on direct calls to functions.
6414   if (FDecl) {
6415     if (CheckFunctionCall(FDecl, TheCall, Proto))
6416       return ExprError();
6417 
6418     checkFortifiedBuiltinMemoryFunction(FDecl, TheCall);
6419 
6420     if (BuiltinID)
6421       return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
6422   } else if (NDecl) {
6423     if (CheckPointerCall(NDecl, TheCall, Proto))
6424       return ExprError();
6425   } else {
6426     if (CheckOtherCall(TheCall, Proto))
6427       return ExprError();
6428   }
6429 
6430   return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl);
6431 }
6432 
6433 ExprResult
6434 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
6435                            SourceLocation RParenLoc, Expr *InitExpr) {
6436   assert(Ty && "ActOnCompoundLiteral(): missing type");
6437   assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
6438 
6439   TypeSourceInfo *TInfo;
6440   QualType literalType = GetTypeFromParser(Ty, &TInfo);
6441   if (!TInfo)
6442     TInfo = Context.getTrivialTypeSourceInfo(literalType);
6443 
6444   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
6445 }
6446 
6447 ExprResult
6448 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
6449                                SourceLocation RParenLoc, Expr *LiteralExpr) {
6450   QualType literalType = TInfo->getType();
6451 
6452   if (literalType->isArrayType()) {
6453     if (RequireCompleteSizedType(
6454             LParenLoc, Context.getBaseElementType(literalType),
6455             diag::err_array_incomplete_or_sizeless_type,
6456             SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
6457       return ExprError();
6458     if (literalType->isVariableArrayType())
6459       return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
6460         << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
6461   } else if (!literalType->isDependentType() &&
6462              RequireCompleteType(LParenLoc, literalType,
6463                diag::err_typecheck_decl_incomplete_type,
6464                SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
6465     return ExprError();
6466 
6467   InitializedEntity Entity
6468     = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
6469   InitializationKind Kind
6470     = InitializationKind::CreateCStyleCast(LParenLoc,
6471                                            SourceRange(LParenLoc, RParenLoc),
6472                                            /*InitList=*/true);
6473   InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
6474   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
6475                                       &literalType);
6476   if (Result.isInvalid())
6477     return ExprError();
6478   LiteralExpr = Result.get();
6479 
6480   bool isFileScope = !CurContext->isFunctionOrMethod();
6481 
6482   // In C, compound literals are l-values for some reason.
6483   // For GCC compatibility, in C++, file-scope array compound literals with
6484   // constant initializers are also l-values, and compound literals are
6485   // otherwise prvalues.
6486   //
6487   // (GCC also treats C++ list-initialized file-scope array prvalues with
6488   // constant initializers as l-values, but that's non-conforming, so we don't
6489   // follow it there.)
6490   //
6491   // FIXME: It would be better to handle the lvalue cases as materializing and
6492   // lifetime-extending a temporary object, but our materialized temporaries
6493   // representation only supports lifetime extension from a variable, not "out
6494   // of thin air".
6495   // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
6496   // is bound to the result of applying array-to-pointer decay to the compound
6497   // literal.
6498   // FIXME: GCC supports compound literals of reference type, which should
6499   // obviously have a value kind derived from the kind of reference involved.
6500   ExprValueKind VK =
6501       (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
6502           ? VK_RValue
6503           : VK_LValue;
6504 
6505   if (isFileScope)
6506     if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr))
6507       for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {
6508         Expr *Init = ILE->getInit(i);
6509         ILE->setInit(i, ConstantExpr::Create(Context, Init));
6510       }
6511 
6512   auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
6513                                               VK, LiteralExpr, isFileScope);
6514   if (isFileScope) {
6515     if (!LiteralExpr->isTypeDependent() &&
6516         !LiteralExpr->isValueDependent() &&
6517         !literalType->isDependentType()) // C99 6.5.2.5p3
6518       if (CheckForConstantInitializer(LiteralExpr, literalType))
6519         return ExprError();
6520   } else if (literalType.getAddressSpace() != LangAS::opencl_private &&
6521              literalType.getAddressSpace() != LangAS::Default) {
6522     // Embedded-C extensions to C99 6.5.2.5:
6523     //   "If the compound literal occurs inside the body of a function, the
6524     //   type name shall not be qualified by an address-space qualifier."
6525     Diag(LParenLoc, diag::err_compound_literal_with_address_space)
6526       << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
6527     return ExprError();
6528   }
6529 
6530   if (!isFileScope && !getLangOpts().CPlusPlus) {
6531     // Compound literals that have automatic storage duration are destroyed at
6532     // the end of the scope in C; in C++, they're just temporaries.
6533 
6534     // Emit diagnostics if it is or contains a C union type that is non-trivial
6535     // to destruct.
6536     if (E->getType().hasNonTrivialToPrimitiveDestructCUnion())
6537       checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
6538                             NTCUC_CompoundLiteral, NTCUK_Destruct);
6539 
6540     // Diagnose jumps that enter or exit the lifetime of the compound literal.
6541     if (literalType.isDestructedType()) {
6542       Cleanup.setExprNeedsCleanups(true);
6543       ExprCleanupObjects.push_back(E);
6544       getCurFunction()->setHasBranchProtectedScope();
6545     }
6546   }
6547 
6548   if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
6549       E->getType().hasNonTrivialToPrimitiveCopyCUnion())
6550     checkNonTrivialCUnionInInitializer(E->getInitializer(),
6551                                        E->getInitializer()->getExprLoc());
6552 
6553   return MaybeBindToTemporary(E);
6554 }
6555 
6556 ExprResult
6557 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
6558                     SourceLocation RBraceLoc) {
6559   // Only produce each kind of designated initialization diagnostic once.
6560   SourceLocation FirstDesignator;
6561   bool DiagnosedArrayDesignator = false;
6562   bool DiagnosedNestedDesignator = false;
6563   bool DiagnosedMixedDesignator = false;
6564 
6565   // Check that any designated initializers are syntactically valid in the
6566   // current language mode.
6567   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
6568     if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) {
6569       if (FirstDesignator.isInvalid())
6570         FirstDesignator = DIE->getBeginLoc();
6571 
6572       if (!getLangOpts().CPlusPlus)
6573         break;
6574 
6575       if (!DiagnosedNestedDesignator && DIE->size() > 1) {
6576         DiagnosedNestedDesignator = true;
6577         Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested)
6578           << DIE->getDesignatorsSourceRange();
6579       }
6580 
6581       for (auto &Desig : DIE->designators()) {
6582         if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) {
6583           DiagnosedArrayDesignator = true;
6584           Diag(Desig.getBeginLoc(), diag::ext_designated_init_array)
6585             << Desig.getSourceRange();
6586         }
6587       }
6588 
6589       if (!DiagnosedMixedDesignator &&
6590           !isa<DesignatedInitExpr>(InitArgList[0])) {
6591         DiagnosedMixedDesignator = true;
6592         Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
6593           << DIE->getSourceRange();
6594         Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed)
6595           << InitArgList[0]->getSourceRange();
6596       }
6597     } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator &&
6598                isa<DesignatedInitExpr>(InitArgList[0])) {
6599       DiagnosedMixedDesignator = true;
6600       auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]);
6601       Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
6602         << DIE->getSourceRange();
6603       Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed)
6604         << InitArgList[I]->getSourceRange();
6605     }
6606   }
6607 
6608   if (FirstDesignator.isValid()) {
6609     // Only diagnose designated initiaization as a C++20 extension if we didn't
6610     // already diagnose use of (non-C++20) C99 designator syntax.
6611     if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator &&
6612         !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) {
6613       Diag(FirstDesignator, getLangOpts().CPlusPlus2a
6614                                 ? diag::warn_cxx17_compat_designated_init
6615                                 : diag::ext_cxx_designated_init);
6616     } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) {
6617       Diag(FirstDesignator, diag::ext_designated_init);
6618     }
6619   }
6620 
6621   return BuildInitList(LBraceLoc, InitArgList, RBraceLoc);
6622 }
6623 
6624 ExprResult
6625 Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
6626                     SourceLocation RBraceLoc) {
6627   // Semantic analysis for initializers is done by ActOnDeclarator() and
6628   // CheckInitializer() - it requires knowledge of the object being initialized.
6629 
6630   // Immediately handle non-overload placeholders.  Overloads can be
6631   // resolved contextually, but everything else here can't.
6632   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
6633     if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
6634       ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
6635 
6636       // Ignore failures; dropping the entire initializer list because
6637       // of one failure would be terrible for indexing/etc.
6638       if (result.isInvalid()) continue;
6639 
6640       InitArgList[I] = result.get();
6641     }
6642   }
6643 
6644   InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
6645                                                RBraceLoc);
6646   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
6647   return E;
6648 }
6649 
6650 /// Do an explicit extend of the given block pointer if we're in ARC.
6651 void Sema::maybeExtendBlockObject(ExprResult &E) {
6652   assert(E.get()->getType()->isBlockPointerType());
6653   assert(E.get()->isRValue());
6654 
6655   // Only do this in an r-value context.
6656   if (!getLangOpts().ObjCAutoRefCount) return;
6657 
6658   E = ImplicitCastExpr::Create(Context, E.get()->getType(),
6659                                CK_ARCExtendBlockObject, E.get(),
6660                                /*base path*/ nullptr, VK_RValue);
6661   Cleanup.setExprNeedsCleanups(true);
6662 }
6663 
6664 /// Prepare a conversion of the given expression to an ObjC object
6665 /// pointer type.
6666 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
6667   QualType type = E.get()->getType();
6668   if (type->isObjCObjectPointerType()) {
6669     return CK_BitCast;
6670   } else if (type->isBlockPointerType()) {
6671     maybeExtendBlockObject(E);
6672     return CK_BlockPointerToObjCPointerCast;
6673   } else {
6674     assert(type->isPointerType());
6675     return CK_CPointerToObjCPointerCast;
6676   }
6677 }
6678 
6679 /// Prepares for a scalar cast, performing all the necessary stages
6680 /// except the final cast and returning the kind required.
6681 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
6682   // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
6683   // Also, callers should have filtered out the invalid cases with
6684   // pointers.  Everything else should be possible.
6685 
6686   QualType SrcTy = Src.get()->getType();
6687   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
6688     return CK_NoOp;
6689 
6690   switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
6691   case Type::STK_MemberPointer:
6692     llvm_unreachable("member pointer type in C");
6693 
6694   case Type::STK_CPointer:
6695   case Type::STK_BlockPointer:
6696   case Type::STK_ObjCObjectPointer:
6697     switch (DestTy->getScalarTypeKind()) {
6698     case Type::STK_CPointer: {
6699       LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
6700       LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
6701       if (SrcAS != DestAS)
6702         return CK_AddressSpaceConversion;
6703       if (Context.hasCvrSimilarType(SrcTy, DestTy))
6704         return CK_NoOp;
6705       return CK_BitCast;
6706     }
6707     case Type::STK_BlockPointer:
6708       return (SrcKind == Type::STK_BlockPointer
6709                 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
6710     case Type::STK_ObjCObjectPointer:
6711       if (SrcKind == Type::STK_ObjCObjectPointer)
6712         return CK_BitCast;
6713       if (SrcKind == Type::STK_CPointer)
6714         return CK_CPointerToObjCPointerCast;
6715       maybeExtendBlockObject(Src);
6716       return CK_BlockPointerToObjCPointerCast;
6717     case Type::STK_Bool:
6718       return CK_PointerToBoolean;
6719     case Type::STK_Integral:
6720       return CK_PointerToIntegral;
6721     case Type::STK_Floating:
6722     case Type::STK_FloatingComplex:
6723     case Type::STK_IntegralComplex:
6724     case Type::STK_MemberPointer:
6725     case Type::STK_FixedPoint:
6726       llvm_unreachable("illegal cast from pointer");
6727     }
6728     llvm_unreachable("Should have returned before this");
6729 
6730   case Type::STK_FixedPoint:
6731     switch (DestTy->getScalarTypeKind()) {
6732     case Type::STK_FixedPoint:
6733       return CK_FixedPointCast;
6734     case Type::STK_Bool:
6735       return CK_FixedPointToBoolean;
6736     case Type::STK_Integral:
6737       return CK_FixedPointToIntegral;
6738     case Type::STK_Floating:
6739     case Type::STK_IntegralComplex:
6740     case Type::STK_FloatingComplex:
6741       Diag(Src.get()->getExprLoc(),
6742            diag::err_unimplemented_conversion_with_fixed_point_type)
6743           << DestTy;
6744       return CK_IntegralCast;
6745     case Type::STK_CPointer:
6746     case Type::STK_ObjCObjectPointer:
6747     case Type::STK_BlockPointer:
6748     case Type::STK_MemberPointer:
6749       llvm_unreachable("illegal cast to pointer type");
6750     }
6751     llvm_unreachable("Should have returned before this");
6752 
6753   case Type::STK_Bool: // casting from bool is like casting from an integer
6754   case Type::STK_Integral:
6755     switch (DestTy->getScalarTypeKind()) {
6756     case Type::STK_CPointer:
6757     case Type::STK_ObjCObjectPointer:
6758     case Type::STK_BlockPointer:
6759       if (Src.get()->isNullPointerConstant(Context,
6760                                            Expr::NPC_ValueDependentIsNull))
6761         return CK_NullToPointer;
6762       return CK_IntegralToPointer;
6763     case Type::STK_Bool:
6764       return CK_IntegralToBoolean;
6765     case Type::STK_Integral:
6766       return CK_IntegralCast;
6767     case Type::STK_Floating:
6768       return CK_IntegralToFloating;
6769     case Type::STK_IntegralComplex:
6770       Src = ImpCastExprToType(Src.get(),
6771                       DestTy->castAs<ComplexType>()->getElementType(),
6772                       CK_IntegralCast);
6773       return CK_IntegralRealToComplex;
6774     case Type::STK_FloatingComplex:
6775       Src = ImpCastExprToType(Src.get(),
6776                       DestTy->castAs<ComplexType>()->getElementType(),
6777                       CK_IntegralToFloating);
6778       return CK_FloatingRealToComplex;
6779     case Type::STK_MemberPointer:
6780       llvm_unreachable("member pointer type in C");
6781     case Type::STK_FixedPoint:
6782       return CK_IntegralToFixedPoint;
6783     }
6784     llvm_unreachable("Should have returned before this");
6785 
6786   case Type::STK_Floating:
6787     switch (DestTy->getScalarTypeKind()) {
6788     case Type::STK_Floating:
6789       return CK_FloatingCast;
6790     case Type::STK_Bool:
6791       return CK_FloatingToBoolean;
6792     case Type::STK_Integral:
6793       return CK_FloatingToIntegral;
6794     case Type::STK_FloatingComplex:
6795       Src = ImpCastExprToType(Src.get(),
6796                               DestTy->castAs<ComplexType>()->getElementType(),
6797                               CK_FloatingCast);
6798       return CK_FloatingRealToComplex;
6799     case Type::STK_IntegralComplex:
6800       Src = ImpCastExprToType(Src.get(),
6801                               DestTy->castAs<ComplexType>()->getElementType(),
6802                               CK_FloatingToIntegral);
6803       return CK_IntegralRealToComplex;
6804     case Type::STK_CPointer:
6805     case Type::STK_ObjCObjectPointer:
6806     case Type::STK_BlockPointer:
6807       llvm_unreachable("valid float->pointer cast?");
6808     case Type::STK_MemberPointer:
6809       llvm_unreachable("member pointer type in C");
6810     case Type::STK_FixedPoint:
6811       Diag(Src.get()->getExprLoc(),
6812            diag::err_unimplemented_conversion_with_fixed_point_type)
6813           << SrcTy;
6814       return CK_IntegralCast;
6815     }
6816     llvm_unreachable("Should have returned before this");
6817 
6818   case Type::STK_FloatingComplex:
6819     switch (DestTy->getScalarTypeKind()) {
6820     case Type::STK_FloatingComplex:
6821       return CK_FloatingComplexCast;
6822     case Type::STK_IntegralComplex:
6823       return CK_FloatingComplexToIntegralComplex;
6824     case Type::STK_Floating: {
6825       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
6826       if (Context.hasSameType(ET, DestTy))
6827         return CK_FloatingComplexToReal;
6828       Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
6829       return CK_FloatingCast;
6830     }
6831     case Type::STK_Bool:
6832       return CK_FloatingComplexToBoolean;
6833     case Type::STK_Integral:
6834       Src = ImpCastExprToType(Src.get(),
6835                               SrcTy->castAs<ComplexType>()->getElementType(),
6836                               CK_FloatingComplexToReal);
6837       return CK_FloatingToIntegral;
6838     case Type::STK_CPointer:
6839     case Type::STK_ObjCObjectPointer:
6840     case Type::STK_BlockPointer:
6841       llvm_unreachable("valid complex float->pointer cast?");
6842     case Type::STK_MemberPointer:
6843       llvm_unreachable("member pointer type in C");
6844     case Type::STK_FixedPoint:
6845       Diag(Src.get()->getExprLoc(),
6846            diag::err_unimplemented_conversion_with_fixed_point_type)
6847           << SrcTy;
6848       return CK_IntegralCast;
6849     }
6850     llvm_unreachable("Should have returned before this");
6851 
6852   case Type::STK_IntegralComplex:
6853     switch (DestTy->getScalarTypeKind()) {
6854     case Type::STK_FloatingComplex:
6855       return CK_IntegralComplexToFloatingComplex;
6856     case Type::STK_IntegralComplex:
6857       return CK_IntegralComplexCast;
6858     case Type::STK_Integral: {
6859       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
6860       if (Context.hasSameType(ET, DestTy))
6861         return CK_IntegralComplexToReal;
6862       Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
6863       return CK_IntegralCast;
6864     }
6865     case Type::STK_Bool:
6866       return CK_IntegralComplexToBoolean;
6867     case Type::STK_Floating:
6868       Src = ImpCastExprToType(Src.get(),
6869                               SrcTy->castAs<ComplexType>()->getElementType(),
6870                               CK_IntegralComplexToReal);
6871       return CK_IntegralToFloating;
6872     case Type::STK_CPointer:
6873     case Type::STK_ObjCObjectPointer:
6874     case Type::STK_BlockPointer:
6875       llvm_unreachable("valid complex int->pointer cast?");
6876     case Type::STK_MemberPointer:
6877       llvm_unreachable("member pointer type in C");
6878     case Type::STK_FixedPoint:
6879       Diag(Src.get()->getExprLoc(),
6880            diag::err_unimplemented_conversion_with_fixed_point_type)
6881           << SrcTy;
6882       return CK_IntegralCast;
6883     }
6884     llvm_unreachable("Should have returned before this");
6885   }
6886 
6887   llvm_unreachable("Unhandled scalar cast");
6888 }
6889 
6890 static bool breakDownVectorType(QualType type, uint64_t &len,
6891                                 QualType &eltType) {
6892   // Vectors are simple.
6893   if (const VectorType *vecType = type->getAs<VectorType>()) {
6894     len = vecType->getNumElements();
6895     eltType = vecType->getElementType();
6896     assert(eltType->isScalarType());
6897     return true;
6898   }
6899 
6900   // We allow lax conversion to and from non-vector types, but only if
6901   // they're real types (i.e. non-complex, non-pointer scalar types).
6902   if (!type->isRealType()) return false;
6903 
6904   len = 1;
6905   eltType = type;
6906   return true;
6907 }
6908 
6909 /// Are the two types lax-compatible vector types?  That is, given
6910 /// that one of them is a vector, do they have equal storage sizes,
6911 /// where the storage size is the number of elements times the element
6912 /// size?
6913 ///
6914 /// This will also return false if either of the types is neither a
6915 /// vector nor a real type.
6916 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
6917   assert(destTy->isVectorType() || srcTy->isVectorType());
6918 
6919   // Disallow lax conversions between scalars and ExtVectors (these
6920   // conversions are allowed for other vector types because common headers
6921   // depend on them).  Most scalar OP ExtVector cases are handled by the
6922   // splat path anyway, which does what we want (convert, not bitcast).
6923   // What this rules out for ExtVectors is crazy things like char4*float.
6924   if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
6925   if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
6926 
6927   uint64_t srcLen, destLen;
6928   QualType srcEltTy, destEltTy;
6929   if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false;
6930   if (!breakDownVectorType(destTy, destLen, destEltTy)) return false;
6931 
6932   // ASTContext::getTypeSize will return the size rounded up to a
6933   // power of 2, so instead of using that, we need to use the raw
6934   // element size multiplied by the element count.
6935   uint64_t srcEltSize = Context.getTypeSize(srcEltTy);
6936   uint64_t destEltSize = Context.getTypeSize(destEltTy);
6937 
6938   return (srcLen * srcEltSize == destLen * destEltSize);
6939 }
6940 
6941 /// Is this a legal conversion between two types, one of which is
6942 /// known to be a vector type?
6943 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
6944   assert(destTy->isVectorType() || srcTy->isVectorType());
6945 
6946   switch (Context.getLangOpts().getLaxVectorConversions()) {
6947   case LangOptions::LaxVectorConversionKind::None:
6948     return false;
6949 
6950   case LangOptions::LaxVectorConversionKind::Integer:
6951     if (!srcTy->isIntegralOrEnumerationType()) {
6952       auto *Vec = srcTy->getAs<VectorType>();
6953       if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
6954         return false;
6955     }
6956     if (!destTy->isIntegralOrEnumerationType()) {
6957       auto *Vec = destTy->getAs<VectorType>();
6958       if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
6959         return false;
6960     }
6961     // OK, integer (vector) -> integer (vector) bitcast.
6962     break;
6963 
6964     case LangOptions::LaxVectorConversionKind::All:
6965     break;
6966   }
6967 
6968   return areLaxCompatibleVectorTypes(srcTy, destTy);
6969 }
6970 
6971 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
6972                            CastKind &Kind) {
6973   assert(VectorTy->isVectorType() && "Not a vector type!");
6974 
6975   if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
6976     if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
6977       return Diag(R.getBegin(),
6978                   Ty->isVectorType() ?
6979                   diag::err_invalid_conversion_between_vectors :
6980                   diag::err_invalid_conversion_between_vector_and_integer)
6981         << VectorTy << Ty << R;
6982   } else
6983     return Diag(R.getBegin(),
6984                 diag::err_invalid_conversion_between_vector_and_scalar)
6985       << VectorTy << Ty << R;
6986 
6987   Kind = CK_BitCast;
6988   return false;
6989 }
6990 
6991 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
6992   QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
6993 
6994   if (DestElemTy == SplattedExpr->getType())
6995     return SplattedExpr;
6996 
6997   assert(DestElemTy->isFloatingType() ||
6998          DestElemTy->isIntegralOrEnumerationType());
6999 
7000   CastKind CK;
7001   if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
7002     // OpenCL requires that we convert `true` boolean expressions to -1, but
7003     // only when splatting vectors.
7004     if (DestElemTy->isFloatingType()) {
7005       // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
7006       // in two steps: boolean to signed integral, then to floating.
7007       ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
7008                                                  CK_BooleanToSignedIntegral);
7009       SplattedExpr = CastExprRes.get();
7010       CK = CK_IntegralToFloating;
7011     } else {
7012       CK = CK_BooleanToSignedIntegral;
7013     }
7014   } else {
7015     ExprResult CastExprRes = SplattedExpr;
7016     CK = PrepareScalarCast(CastExprRes, DestElemTy);
7017     if (CastExprRes.isInvalid())
7018       return ExprError();
7019     SplattedExpr = CastExprRes.get();
7020   }
7021   return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
7022 }
7023 
7024 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
7025                                     Expr *CastExpr, CastKind &Kind) {
7026   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
7027 
7028   QualType SrcTy = CastExpr->getType();
7029 
7030   // If SrcTy is a VectorType, the total size must match to explicitly cast to
7031   // an ExtVectorType.
7032   // In OpenCL, casts between vectors of different types are not allowed.
7033   // (See OpenCL 6.2).
7034   if (SrcTy->isVectorType()) {
7035     if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
7036         (getLangOpts().OpenCL &&
7037          !Context.hasSameUnqualifiedType(DestTy, SrcTy))) {
7038       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
7039         << DestTy << SrcTy << R;
7040       return ExprError();
7041     }
7042     Kind = CK_BitCast;
7043     return CastExpr;
7044   }
7045 
7046   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
7047   // conversion will take place first from scalar to elt type, and then
7048   // splat from elt type to vector.
7049   if (SrcTy->isPointerType())
7050     return Diag(R.getBegin(),
7051                 diag::err_invalid_conversion_between_vector_and_scalar)
7052       << DestTy << SrcTy << R;
7053 
7054   Kind = CK_VectorSplat;
7055   return prepareVectorSplat(DestTy, CastExpr);
7056 }
7057 
7058 ExprResult
7059 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
7060                     Declarator &D, ParsedType &Ty,
7061                     SourceLocation RParenLoc, Expr *CastExpr) {
7062   assert(!D.isInvalidType() && (CastExpr != nullptr) &&
7063          "ActOnCastExpr(): missing type or expr");
7064 
7065   TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
7066   if (D.isInvalidType())
7067     return ExprError();
7068 
7069   if (getLangOpts().CPlusPlus) {
7070     // Check that there are no default arguments (C++ only).
7071     CheckExtraCXXDefaultArguments(D);
7072   } else {
7073     // Make sure any TypoExprs have been dealt with.
7074     ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
7075     if (!Res.isUsable())
7076       return ExprError();
7077     CastExpr = Res.get();
7078   }
7079 
7080   checkUnusedDeclAttributes(D);
7081 
7082   QualType castType = castTInfo->getType();
7083   Ty = CreateParsedType(castType, castTInfo);
7084 
7085   bool isVectorLiteral = false;
7086 
7087   // Check for an altivec or OpenCL literal,
7088   // i.e. all the elements are integer constants.
7089   ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
7090   ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
7091   if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
7092        && castType->isVectorType() && (PE || PLE)) {
7093     if (PLE && PLE->getNumExprs() == 0) {
7094       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
7095       return ExprError();
7096     }
7097     if (PE || PLE->getNumExprs() == 1) {
7098       Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
7099       if (!E->getType()->isVectorType())
7100         isVectorLiteral = true;
7101     }
7102     else
7103       isVectorLiteral = true;
7104   }
7105 
7106   // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
7107   // then handle it as such.
7108   if (isVectorLiteral)
7109     return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
7110 
7111   // If the Expr being casted is a ParenListExpr, handle it specially.
7112   // This is not an AltiVec-style cast, so turn the ParenListExpr into a
7113   // sequence of BinOp comma operators.
7114   if (isa<ParenListExpr>(CastExpr)) {
7115     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
7116     if (Result.isInvalid()) return ExprError();
7117     CastExpr = Result.get();
7118   }
7119 
7120   if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
7121       !getSourceManager().isInSystemMacro(LParenLoc))
7122     Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
7123 
7124   CheckTollFreeBridgeCast(castType, CastExpr);
7125 
7126   CheckObjCBridgeRelatedCast(castType, CastExpr);
7127 
7128   DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
7129 
7130   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
7131 }
7132 
7133 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
7134                                     SourceLocation RParenLoc, Expr *E,
7135                                     TypeSourceInfo *TInfo) {
7136   assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
7137          "Expected paren or paren list expression");
7138 
7139   Expr **exprs;
7140   unsigned numExprs;
7141   Expr *subExpr;
7142   SourceLocation LiteralLParenLoc, LiteralRParenLoc;
7143   if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
7144     LiteralLParenLoc = PE->getLParenLoc();
7145     LiteralRParenLoc = PE->getRParenLoc();
7146     exprs = PE->getExprs();
7147     numExprs = PE->getNumExprs();
7148   } else { // isa<ParenExpr> by assertion at function entrance
7149     LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
7150     LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
7151     subExpr = cast<ParenExpr>(E)->getSubExpr();
7152     exprs = &subExpr;
7153     numExprs = 1;
7154   }
7155 
7156   QualType Ty = TInfo->getType();
7157   assert(Ty->isVectorType() && "Expected vector type");
7158 
7159   SmallVector<Expr *, 8> initExprs;
7160   const VectorType *VTy = Ty->castAs<VectorType>();
7161   unsigned numElems = VTy->getNumElements();
7162 
7163   // '(...)' form of vector initialization in AltiVec: the number of
7164   // initializers must be one or must match the size of the vector.
7165   // If a single value is specified in the initializer then it will be
7166   // replicated to all the components of the vector
7167   if (VTy->getVectorKind() == VectorType::AltiVecVector) {
7168     // The number of initializers must be one or must match the size of the
7169     // vector. If a single value is specified in the initializer then it will
7170     // be replicated to all the components of the vector
7171     if (numExprs == 1) {
7172       QualType ElemTy = VTy->getElementType();
7173       ExprResult Literal = DefaultLvalueConversion(exprs[0]);
7174       if (Literal.isInvalid())
7175         return ExprError();
7176       Literal = ImpCastExprToType(Literal.get(), ElemTy,
7177                                   PrepareScalarCast(Literal, ElemTy));
7178       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
7179     }
7180     else if (numExprs < numElems) {
7181       Diag(E->getExprLoc(),
7182            diag::err_incorrect_number_of_vector_initializers);
7183       return ExprError();
7184     }
7185     else
7186       initExprs.append(exprs, exprs + numExprs);
7187   }
7188   else {
7189     // For OpenCL, when the number of initializers is a single value,
7190     // it will be replicated to all components of the vector.
7191     if (getLangOpts().OpenCL &&
7192         VTy->getVectorKind() == VectorType::GenericVector &&
7193         numExprs == 1) {
7194         QualType ElemTy = VTy->getElementType();
7195         ExprResult Literal = DefaultLvalueConversion(exprs[0]);
7196         if (Literal.isInvalid())
7197           return ExprError();
7198         Literal = ImpCastExprToType(Literal.get(), ElemTy,
7199                                     PrepareScalarCast(Literal, ElemTy));
7200         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
7201     }
7202 
7203     initExprs.append(exprs, exprs + numExprs);
7204   }
7205   // FIXME: This means that pretty-printing the final AST will produce curly
7206   // braces instead of the original commas.
7207   InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
7208                                                    initExprs, LiteralRParenLoc);
7209   initE->setType(Ty);
7210   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
7211 }
7212 
7213 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
7214 /// the ParenListExpr into a sequence of comma binary operators.
7215 ExprResult
7216 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
7217   ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
7218   if (!E)
7219     return OrigExpr;
7220 
7221   ExprResult Result(E->getExpr(0));
7222 
7223   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
7224     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
7225                         E->getExpr(i));
7226 
7227   if (Result.isInvalid()) return ExprError();
7228 
7229   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
7230 }
7231 
7232 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
7233                                     SourceLocation R,
7234                                     MultiExprArg Val) {
7235   return ParenListExpr::Create(Context, L, Val, R);
7236 }
7237 
7238 /// Emit a specialized diagnostic when one expression is a null pointer
7239 /// constant and the other is not a pointer.  Returns true if a diagnostic is
7240 /// emitted.
7241 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
7242                                       SourceLocation QuestionLoc) {
7243   Expr *NullExpr = LHSExpr;
7244   Expr *NonPointerExpr = RHSExpr;
7245   Expr::NullPointerConstantKind NullKind =
7246       NullExpr->isNullPointerConstant(Context,
7247                                       Expr::NPC_ValueDependentIsNotNull);
7248 
7249   if (NullKind == Expr::NPCK_NotNull) {
7250     NullExpr = RHSExpr;
7251     NonPointerExpr = LHSExpr;
7252     NullKind =
7253         NullExpr->isNullPointerConstant(Context,
7254                                         Expr::NPC_ValueDependentIsNotNull);
7255   }
7256 
7257   if (NullKind == Expr::NPCK_NotNull)
7258     return false;
7259 
7260   if (NullKind == Expr::NPCK_ZeroExpression)
7261     return false;
7262 
7263   if (NullKind == Expr::NPCK_ZeroLiteral) {
7264     // In this case, check to make sure that we got here from a "NULL"
7265     // string in the source code.
7266     NullExpr = NullExpr->IgnoreParenImpCasts();
7267     SourceLocation loc = NullExpr->getExprLoc();
7268     if (!findMacroSpelling(loc, "NULL"))
7269       return false;
7270   }
7271 
7272   int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
7273   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
7274       << NonPointerExpr->getType() << DiagType
7275       << NonPointerExpr->getSourceRange();
7276   return true;
7277 }
7278 
7279 /// Return false if the condition expression is valid, true otherwise.
7280 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
7281   QualType CondTy = Cond->getType();
7282 
7283   // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
7284   if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
7285     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
7286       << CondTy << Cond->getSourceRange();
7287     return true;
7288   }
7289 
7290   // C99 6.5.15p2
7291   if (CondTy->isScalarType()) return false;
7292 
7293   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
7294     << CondTy << Cond->getSourceRange();
7295   return true;
7296 }
7297 
7298 /// Handle when one or both operands are void type.
7299 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
7300                                          ExprResult &RHS) {
7301     Expr *LHSExpr = LHS.get();
7302     Expr *RHSExpr = RHS.get();
7303 
7304     if (!LHSExpr->getType()->isVoidType())
7305       S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
7306           << RHSExpr->getSourceRange();
7307     if (!RHSExpr->getType()->isVoidType())
7308       S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
7309           << LHSExpr->getSourceRange();
7310     LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
7311     RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
7312     return S.Context.VoidTy;
7313 }
7314 
7315 /// Return false if the NullExpr can be promoted to PointerTy,
7316 /// true otherwise.
7317 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
7318                                         QualType PointerTy) {
7319   if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
7320       !NullExpr.get()->isNullPointerConstant(S.Context,
7321                                             Expr::NPC_ValueDependentIsNull))
7322     return true;
7323 
7324   NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
7325   return false;
7326 }
7327 
7328 /// Checks compatibility between two pointers and return the resulting
7329 /// type.
7330 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
7331                                                      ExprResult &RHS,
7332                                                      SourceLocation Loc) {
7333   QualType LHSTy = LHS.get()->getType();
7334   QualType RHSTy = RHS.get()->getType();
7335 
7336   if (S.Context.hasSameType(LHSTy, RHSTy)) {
7337     // Two identical pointers types are always compatible.
7338     return LHSTy;
7339   }
7340 
7341   QualType lhptee, rhptee;
7342 
7343   // Get the pointee types.
7344   bool IsBlockPointer = false;
7345   if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
7346     lhptee = LHSBTy->getPointeeType();
7347     rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
7348     IsBlockPointer = true;
7349   } else {
7350     lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
7351     rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
7352   }
7353 
7354   // C99 6.5.15p6: If both operands are pointers to compatible types or to
7355   // differently qualified versions of compatible types, the result type is
7356   // a pointer to an appropriately qualified version of the composite
7357   // type.
7358 
7359   // Only CVR-qualifiers exist in the standard, and the differently-qualified
7360   // clause doesn't make sense for our extensions. E.g. address space 2 should
7361   // be incompatible with address space 3: they may live on different devices or
7362   // anything.
7363   Qualifiers lhQual = lhptee.getQualifiers();
7364   Qualifiers rhQual = rhptee.getQualifiers();
7365 
7366   LangAS ResultAddrSpace = LangAS::Default;
7367   LangAS LAddrSpace = lhQual.getAddressSpace();
7368   LangAS RAddrSpace = rhQual.getAddressSpace();
7369 
7370   // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
7371   // spaces is disallowed.
7372   if (lhQual.isAddressSpaceSupersetOf(rhQual))
7373     ResultAddrSpace = LAddrSpace;
7374   else if (rhQual.isAddressSpaceSupersetOf(lhQual))
7375     ResultAddrSpace = RAddrSpace;
7376   else {
7377     S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
7378         << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
7379         << RHS.get()->getSourceRange();
7380     return QualType();
7381   }
7382 
7383   unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
7384   auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
7385   lhQual.removeCVRQualifiers();
7386   rhQual.removeCVRQualifiers();
7387 
7388   // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
7389   // (C99 6.7.3) for address spaces. We assume that the check should behave in
7390   // the same manner as it's defined for CVR qualifiers, so for OpenCL two
7391   // qual types are compatible iff
7392   //  * corresponded types are compatible
7393   //  * CVR qualifiers are equal
7394   //  * address spaces are equal
7395   // Thus for conditional operator we merge CVR and address space unqualified
7396   // pointees and if there is a composite type we return a pointer to it with
7397   // merged qualifiers.
7398   LHSCastKind =
7399       LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
7400   RHSCastKind =
7401       RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
7402   lhQual.removeAddressSpace();
7403   rhQual.removeAddressSpace();
7404 
7405   lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
7406   rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
7407 
7408   QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
7409 
7410   if (CompositeTy.isNull()) {
7411     // In this situation, we assume void* type. No especially good
7412     // reason, but this is what gcc does, and we do have to pick
7413     // to get a consistent AST.
7414     QualType incompatTy;
7415     incompatTy = S.Context.getPointerType(
7416         S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
7417     LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
7418     RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
7419 
7420     // FIXME: For OpenCL the warning emission and cast to void* leaves a room
7421     // for casts between types with incompatible address space qualifiers.
7422     // For the following code the compiler produces casts between global and
7423     // local address spaces of the corresponded innermost pointees:
7424     // local int *global *a;
7425     // global int *global *b;
7426     // a = (0 ? a : b); // see C99 6.5.16.1.p1.
7427     S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
7428         << LHSTy << RHSTy << LHS.get()->getSourceRange()
7429         << RHS.get()->getSourceRange();
7430 
7431     return incompatTy;
7432   }
7433 
7434   // The pointer types are compatible.
7435   // In case of OpenCL ResultTy should have the address space qualifier
7436   // which is a superset of address spaces of both the 2nd and the 3rd
7437   // operands of the conditional operator.
7438   QualType ResultTy = [&, ResultAddrSpace]() {
7439     if (S.getLangOpts().OpenCL) {
7440       Qualifiers CompositeQuals = CompositeTy.getQualifiers();
7441       CompositeQuals.setAddressSpace(ResultAddrSpace);
7442       return S.Context
7443           .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
7444           .withCVRQualifiers(MergedCVRQual);
7445     }
7446     return CompositeTy.withCVRQualifiers(MergedCVRQual);
7447   }();
7448   if (IsBlockPointer)
7449     ResultTy = S.Context.getBlockPointerType(ResultTy);
7450   else
7451     ResultTy = S.Context.getPointerType(ResultTy);
7452 
7453   LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
7454   RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
7455   return ResultTy;
7456 }
7457 
7458 /// Return the resulting type when the operands are both block pointers.
7459 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
7460                                                           ExprResult &LHS,
7461                                                           ExprResult &RHS,
7462                                                           SourceLocation Loc) {
7463   QualType LHSTy = LHS.get()->getType();
7464   QualType RHSTy = RHS.get()->getType();
7465 
7466   if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
7467     if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
7468       QualType destType = S.Context.getPointerType(S.Context.VoidTy);
7469       LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
7470       RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
7471       return destType;
7472     }
7473     S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
7474       << LHSTy << RHSTy << LHS.get()->getSourceRange()
7475       << RHS.get()->getSourceRange();
7476     return QualType();
7477   }
7478 
7479   // We have 2 block pointer types.
7480   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
7481 }
7482 
7483 /// Return the resulting type when the operands are both pointers.
7484 static QualType
7485 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
7486                                             ExprResult &RHS,
7487                                             SourceLocation Loc) {
7488   // get the pointer types
7489   QualType LHSTy = LHS.get()->getType();
7490   QualType RHSTy = RHS.get()->getType();
7491 
7492   // get the "pointed to" types
7493   QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
7494   QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
7495 
7496   // ignore qualifiers on void (C99 6.5.15p3, clause 6)
7497   if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
7498     // Figure out necessary qualifiers (C99 6.5.15p6)
7499     QualType destPointee
7500       = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
7501     QualType destType = S.Context.getPointerType(destPointee);
7502     // Add qualifiers if necessary.
7503     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
7504     // Promote to void*.
7505     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
7506     return destType;
7507   }
7508   if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
7509     QualType destPointee
7510       = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
7511     QualType destType = S.Context.getPointerType(destPointee);
7512     // Add qualifiers if necessary.
7513     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
7514     // Promote to void*.
7515     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
7516     return destType;
7517   }
7518 
7519   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
7520 }
7521 
7522 /// Return false if the first expression is not an integer and the second
7523 /// expression is not a pointer, true otherwise.
7524 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
7525                                         Expr* PointerExpr, SourceLocation Loc,
7526                                         bool IsIntFirstExpr) {
7527   if (!PointerExpr->getType()->isPointerType() ||
7528       !Int.get()->getType()->isIntegerType())
7529     return false;
7530 
7531   Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
7532   Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
7533 
7534   S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
7535     << Expr1->getType() << Expr2->getType()
7536     << Expr1->getSourceRange() << Expr2->getSourceRange();
7537   Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
7538                             CK_IntegralToPointer);
7539   return true;
7540 }
7541 
7542 /// Simple conversion between integer and floating point types.
7543 ///
7544 /// Used when handling the OpenCL conditional operator where the
7545 /// condition is a vector while the other operands are scalar.
7546 ///
7547 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
7548 /// types are either integer or floating type. Between the two
7549 /// operands, the type with the higher rank is defined as the "result
7550 /// type". The other operand needs to be promoted to the same type. No
7551 /// other type promotion is allowed. We cannot use
7552 /// UsualArithmeticConversions() for this purpose, since it always
7553 /// promotes promotable types.
7554 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
7555                                             ExprResult &RHS,
7556                                             SourceLocation QuestionLoc) {
7557   LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
7558   if (LHS.isInvalid())
7559     return QualType();
7560   RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
7561   if (RHS.isInvalid())
7562     return QualType();
7563 
7564   // For conversion purposes, we ignore any qualifiers.
7565   // For example, "const float" and "float" are equivalent.
7566   QualType LHSType =
7567     S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
7568   QualType RHSType =
7569     S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
7570 
7571   if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
7572     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
7573       << LHSType << LHS.get()->getSourceRange();
7574     return QualType();
7575   }
7576 
7577   if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
7578     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
7579       << RHSType << RHS.get()->getSourceRange();
7580     return QualType();
7581   }
7582 
7583   // If both types are identical, no conversion is needed.
7584   if (LHSType == RHSType)
7585     return LHSType;
7586 
7587   // Now handle "real" floating types (i.e. float, double, long double).
7588   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
7589     return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
7590                                  /*IsCompAssign = */ false);
7591 
7592   // Finally, we have two differing integer types.
7593   return handleIntegerConversion<doIntegralCast, doIntegralCast>
7594   (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
7595 }
7596 
7597 /// Convert scalar operands to a vector that matches the
7598 ///        condition in length.
7599 ///
7600 /// Used when handling the OpenCL conditional operator where the
7601 /// condition is a vector while the other operands are scalar.
7602 ///
7603 /// We first compute the "result type" for the scalar operands
7604 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
7605 /// into a vector of that type where the length matches the condition
7606 /// vector type. s6.11.6 requires that the element types of the result
7607 /// and the condition must have the same number of bits.
7608 static QualType
7609 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
7610                               QualType CondTy, SourceLocation QuestionLoc) {
7611   QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
7612   if (ResTy.isNull()) return QualType();
7613 
7614   const VectorType *CV = CondTy->getAs<VectorType>();
7615   assert(CV);
7616 
7617   // Determine the vector result type
7618   unsigned NumElements = CV->getNumElements();
7619   QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
7620 
7621   // Ensure that all types have the same number of bits
7622   if (S.Context.getTypeSize(CV->getElementType())
7623       != S.Context.getTypeSize(ResTy)) {
7624     // Since VectorTy is created internally, it does not pretty print
7625     // with an OpenCL name. Instead, we just print a description.
7626     std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
7627     SmallString<64> Str;
7628     llvm::raw_svector_ostream OS(Str);
7629     OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
7630     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
7631       << CondTy << OS.str();
7632     return QualType();
7633   }
7634 
7635   // Convert operands to the vector result type
7636   LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
7637   RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
7638 
7639   return VectorTy;
7640 }
7641 
7642 /// Return false if this is a valid OpenCL condition vector
7643 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
7644                                        SourceLocation QuestionLoc) {
7645   // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
7646   // integral type.
7647   const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
7648   assert(CondTy);
7649   QualType EleTy = CondTy->getElementType();
7650   if (EleTy->isIntegerType()) return false;
7651 
7652   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
7653     << Cond->getType() << Cond->getSourceRange();
7654   return true;
7655 }
7656 
7657 /// Return false if the vector condition type and the vector
7658 ///        result type are compatible.
7659 ///
7660 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
7661 /// number of elements, and their element types have the same number
7662 /// of bits.
7663 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
7664                               SourceLocation QuestionLoc) {
7665   const VectorType *CV = CondTy->getAs<VectorType>();
7666   const VectorType *RV = VecResTy->getAs<VectorType>();
7667   assert(CV && RV);
7668 
7669   if (CV->getNumElements() != RV->getNumElements()) {
7670     S.Diag(QuestionLoc, diag::err_conditional_vector_size)
7671       << CondTy << VecResTy;
7672     return true;
7673   }
7674 
7675   QualType CVE = CV->getElementType();
7676   QualType RVE = RV->getElementType();
7677 
7678   if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
7679     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
7680       << CondTy << VecResTy;
7681     return true;
7682   }
7683 
7684   return false;
7685 }
7686 
7687 /// Return the resulting type for the conditional operator in
7688 ///        OpenCL (aka "ternary selection operator", OpenCL v1.1
7689 ///        s6.3.i) when the condition is a vector type.
7690 static QualType
7691 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
7692                              ExprResult &LHS, ExprResult &RHS,
7693                              SourceLocation QuestionLoc) {
7694   Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
7695   if (Cond.isInvalid())
7696     return QualType();
7697   QualType CondTy = Cond.get()->getType();
7698 
7699   if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
7700     return QualType();
7701 
7702   // If either operand is a vector then find the vector type of the
7703   // result as specified in OpenCL v1.1 s6.3.i.
7704   if (LHS.get()->getType()->isVectorType() ||
7705       RHS.get()->getType()->isVectorType()) {
7706     QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
7707                                               /*isCompAssign*/false,
7708                                               /*AllowBothBool*/true,
7709                                               /*AllowBoolConversions*/false);
7710     if (VecResTy.isNull()) return QualType();
7711     // The result type must match the condition type as specified in
7712     // OpenCL v1.1 s6.11.6.
7713     if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
7714       return QualType();
7715     return VecResTy;
7716   }
7717 
7718   // Both operands are scalar.
7719   return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
7720 }
7721 
7722 /// Return true if the Expr is block type
7723 static bool checkBlockType(Sema &S, const Expr *E) {
7724   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
7725     QualType Ty = CE->getCallee()->getType();
7726     if (Ty->isBlockPointerType()) {
7727       S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
7728       return true;
7729     }
7730   }
7731   return false;
7732 }
7733 
7734 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
7735 /// In that case, LHS = cond.
7736 /// C99 6.5.15
7737 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
7738                                         ExprResult &RHS, ExprValueKind &VK,
7739                                         ExprObjectKind &OK,
7740                                         SourceLocation QuestionLoc) {
7741 
7742   ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
7743   if (!LHSResult.isUsable()) return QualType();
7744   LHS = LHSResult;
7745 
7746   ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
7747   if (!RHSResult.isUsable()) return QualType();
7748   RHS = RHSResult;
7749 
7750   // C++ is sufficiently different to merit its own checker.
7751   if (getLangOpts().CPlusPlus)
7752     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
7753 
7754   VK = VK_RValue;
7755   OK = OK_Ordinary;
7756 
7757   // The OpenCL operator with a vector condition is sufficiently
7758   // different to merit its own checker.
7759   if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType())
7760     return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
7761 
7762   // First, check the condition.
7763   Cond = UsualUnaryConversions(Cond.get());
7764   if (Cond.isInvalid())
7765     return QualType();
7766   if (checkCondition(*this, Cond.get(), QuestionLoc))
7767     return QualType();
7768 
7769   // Now check the two expressions.
7770   if (LHS.get()->getType()->isVectorType() ||
7771       RHS.get()->getType()->isVectorType())
7772     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
7773                                /*AllowBothBool*/true,
7774                                /*AllowBoolConversions*/false);
7775 
7776   QualType ResTy =
7777       UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional);
7778   if (LHS.isInvalid() || RHS.isInvalid())
7779     return QualType();
7780 
7781   QualType LHSTy = LHS.get()->getType();
7782   QualType RHSTy = RHS.get()->getType();
7783 
7784   // Diagnose attempts to convert between __float128 and long double where
7785   // such conversions currently can't be handled.
7786   if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
7787     Diag(QuestionLoc,
7788          diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
7789       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7790     return QualType();
7791   }
7792 
7793   // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
7794   // selection operator (?:).
7795   if (getLangOpts().OpenCL &&
7796       (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) {
7797     return QualType();
7798   }
7799 
7800   // If both operands have arithmetic type, do the usual arithmetic conversions
7801   // to find a common type: C99 6.5.15p3,5.
7802   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
7803     LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
7804     RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
7805 
7806     return ResTy;
7807   }
7808 
7809   // If both operands are the same structure or union type, the result is that
7810   // type.
7811   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
7812     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
7813       if (LHSRT->getDecl() == RHSRT->getDecl())
7814         // "If both the operands have structure or union type, the result has
7815         // that type."  This implies that CV qualifiers are dropped.
7816         return LHSTy.getUnqualifiedType();
7817     // FIXME: Type of conditional expression must be complete in C mode.
7818   }
7819 
7820   // C99 6.5.15p5: "If both operands have void type, the result has void type."
7821   // The following || allows only one side to be void (a GCC-ism).
7822   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
7823     return checkConditionalVoidType(*this, LHS, RHS);
7824   }
7825 
7826   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
7827   // the type of the other operand."
7828   if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
7829   if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
7830 
7831   // All objective-c pointer type analysis is done here.
7832   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
7833                                                         QuestionLoc);
7834   if (LHS.isInvalid() || RHS.isInvalid())
7835     return QualType();
7836   if (!compositeType.isNull())
7837     return compositeType;
7838 
7839 
7840   // Handle block pointer types.
7841   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
7842     return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
7843                                                      QuestionLoc);
7844 
7845   // Check constraints for C object pointers types (C99 6.5.15p3,6).
7846   if (LHSTy->isPointerType() && RHSTy->isPointerType())
7847     return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
7848                                                        QuestionLoc);
7849 
7850   // GCC compatibility: soften pointer/integer mismatch.  Note that
7851   // null pointers have been filtered out by this point.
7852   if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
7853       /*IsIntFirstExpr=*/true))
7854     return RHSTy;
7855   if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
7856       /*IsIntFirstExpr=*/false))
7857     return LHSTy;
7858 
7859   // Allow ?: operations in which both operands have the same
7860   // built-in sizeless type.
7861   if (LHSTy->isSizelessBuiltinType() && LHSTy == RHSTy)
7862     return LHSTy;
7863 
7864   // Emit a better diagnostic if one of the expressions is a null pointer
7865   // constant and the other is not a pointer type. In this case, the user most
7866   // likely forgot to take the address of the other expression.
7867   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
7868     return QualType();
7869 
7870   // Otherwise, the operands are not compatible.
7871   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
7872     << LHSTy << RHSTy << LHS.get()->getSourceRange()
7873     << RHS.get()->getSourceRange();
7874   return QualType();
7875 }
7876 
7877 /// FindCompositeObjCPointerType - Helper method to find composite type of
7878 /// two objective-c pointer types of the two input expressions.
7879 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
7880                                             SourceLocation QuestionLoc) {
7881   QualType LHSTy = LHS.get()->getType();
7882   QualType RHSTy = RHS.get()->getType();
7883 
7884   // Handle things like Class and struct objc_class*.  Here we case the result
7885   // to the pseudo-builtin, because that will be implicitly cast back to the
7886   // redefinition type if an attempt is made to access its fields.
7887   if (LHSTy->isObjCClassType() &&
7888       (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
7889     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
7890     return LHSTy;
7891   }
7892   if (RHSTy->isObjCClassType() &&
7893       (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
7894     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
7895     return RHSTy;
7896   }
7897   // And the same for struct objc_object* / id
7898   if (LHSTy->isObjCIdType() &&
7899       (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
7900     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
7901     return LHSTy;
7902   }
7903   if (RHSTy->isObjCIdType() &&
7904       (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
7905     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
7906     return RHSTy;
7907   }
7908   // And the same for struct objc_selector* / SEL
7909   if (Context.isObjCSelType(LHSTy) &&
7910       (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
7911     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
7912     return LHSTy;
7913   }
7914   if (Context.isObjCSelType(RHSTy) &&
7915       (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
7916     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
7917     return RHSTy;
7918   }
7919   // Check constraints for Objective-C object pointers types.
7920   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
7921 
7922     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
7923       // Two identical object pointer types are always compatible.
7924       return LHSTy;
7925     }
7926     const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
7927     const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
7928     QualType compositeType = LHSTy;
7929 
7930     // If both operands are interfaces and either operand can be
7931     // assigned to the other, use that type as the composite
7932     // type. This allows
7933     //   xxx ? (A*) a : (B*) b
7934     // where B is a subclass of A.
7935     //
7936     // Additionally, as for assignment, if either type is 'id'
7937     // allow silent coercion. Finally, if the types are
7938     // incompatible then make sure to use 'id' as the composite
7939     // type so the result is acceptable for sending messages to.
7940 
7941     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
7942     // It could return the composite type.
7943     if (!(compositeType =
7944           Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
7945       // Nothing more to do.
7946     } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
7947       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
7948     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
7949       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
7950     } else if ((LHSOPT->isObjCQualifiedIdType() ||
7951                 RHSOPT->isObjCQualifiedIdType()) &&
7952                Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT,
7953                                                          true)) {
7954       // Need to handle "id<xx>" explicitly.
7955       // GCC allows qualified id and any Objective-C type to devolve to
7956       // id. Currently localizing to here until clear this should be
7957       // part of ObjCQualifiedIdTypesAreCompatible.
7958       compositeType = Context.getObjCIdType();
7959     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
7960       compositeType = Context.getObjCIdType();
7961     } else {
7962       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
7963       << LHSTy << RHSTy
7964       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7965       QualType incompatTy = Context.getObjCIdType();
7966       LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
7967       RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
7968       return incompatTy;
7969     }
7970     // The object pointer types are compatible.
7971     LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
7972     RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
7973     return compositeType;
7974   }
7975   // Check Objective-C object pointer types and 'void *'
7976   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
7977     if (getLangOpts().ObjCAutoRefCount) {
7978       // ARC forbids the implicit conversion of object pointers to 'void *',
7979       // so these types are not compatible.
7980       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
7981           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7982       LHS = RHS = true;
7983       return QualType();
7984     }
7985     QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
7986     QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
7987     QualType destPointee
7988     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
7989     QualType destType = Context.getPointerType(destPointee);
7990     // Add qualifiers if necessary.
7991     LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
7992     // Promote to void*.
7993     RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
7994     return destType;
7995   }
7996   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
7997     if (getLangOpts().ObjCAutoRefCount) {
7998       // ARC forbids the implicit conversion of object pointers to 'void *',
7999       // so these types are not compatible.
8000       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
8001           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8002       LHS = RHS = true;
8003       return QualType();
8004     }
8005     QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
8006     QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8007     QualType destPointee
8008     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
8009     QualType destType = Context.getPointerType(destPointee);
8010     // Add qualifiers if necessary.
8011     RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
8012     // Promote to void*.
8013     LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8014     return destType;
8015   }
8016   return QualType();
8017 }
8018 
8019 /// SuggestParentheses - Emit a note with a fixit hint that wraps
8020 /// ParenRange in parentheses.
8021 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
8022                                const PartialDiagnostic &Note,
8023                                SourceRange ParenRange) {
8024   SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
8025   if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
8026       EndLoc.isValid()) {
8027     Self.Diag(Loc, Note)
8028       << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
8029       << FixItHint::CreateInsertion(EndLoc, ")");
8030   } else {
8031     // We can't display the parentheses, so just show the bare note.
8032     Self.Diag(Loc, Note) << ParenRange;
8033   }
8034 }
8035 
8036 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
8037   return BinaryOperator::isAdditiveOp(Opc) ||
8038          BinaryOperator::isMultiplicativeOp(Opc) ||
8039          BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or;
8040   // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and
8041   // not any of the logical operators.  Bitwise-xor is commonly used as a
8042   // logical-xor because there is no logical-xor operator.  The logical
8043   // operators, including uses of xor, have a high false positive rate for
8044   // precedence warnings.
8045 }
8046 
8047 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
8048 /// expression, either using a built-in or overloaded operator,
8049 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
8050 /// expression.
8051 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
8052                                    Expr **RHSExprs) {
8053   // Don't strip parenthesis: we should not warn if E is in parenthesis.
8054   E = E->IgnoreImpCasts();
8055   E = E->IgnoreConversionOperator();
8056   E = E->IgnoreImpCasts();
8057   if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
8058     E = MTE->getSubExpr();
8059     E = E->IgnoreImpCasts();
8060   }
8061 
8062   // Built-in binary operator.
8063   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
8064     if (IsArithmeticOp(OP->getOpcode())) {
8065       *Opcode = OP->getOpcode();
8066       *RHSExprs = OP->getRHS();
8067       return true;
8068     }
8069   }
8070 
8071   // Overloaded operator.
8072   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
8073     if (Call->getNumArgs() != 2)
8074       return false;
8075 
8076     // Make sure this is really a binary operator that is safe to pass into
8077     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
8078     OverloadedOperatorKind OO = Call->getOperator();
8079     if (OO < OO_Plus || OO > OO_Arrow ||
8080         OO == OO_PlusPlus || OO == OO_MinusMinus)
8081       return false;
8082 
8083     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
8084     if (IsArithmeticOp(OpKind)) {
8085       *Opcode = OpKind;
8086       *RHSExprs = Call->getArg(1);
8087       return true;
8088     }
8089   }
8090 
8091   return false;
8092 }
8093 
8094 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
8095 /// or is a logical expression such as (x==y) which has int type, but is
8096 /// commonly interpreted as boolean.
8097 static bool ExprLooksBoolean(Expr *E) {
8098   E = E->IgnoreParenImpCasts();
8099 
8100   if (E->getType()->isBooleanType())
8101     return true;
8102   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
8103     return OP->isComparisonOp() || OP->isLogicalOp();
8104   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
8105     return OP->getOpcode() == UO_LNot;
8106   if (E->getType()->isPointerType())
8107     return true;
8108   // FIXME: What about overloaded operator calls returning "unspecified boolean
8109   // type"s (commonly pointer-to-members)?
8110 
8111   return false;
8112 }
8113 
8114 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
8115 /// and binary operator are mixed in a way that suggests the programmer assumed
8116 /// the conditional operator has higher precedence, for example:
8117 /// "int x = a + someBinaryCondition ? 1 : 2".
8118 static void DiagnoseConditionalPrecedence(Sema &Self,
8119                                           SourceLocation OpLoc,
8120                                           Expr *Condition,
8121                                           Expr *LHSExpr,
8122                                           Expr *RHSExpr) {
8123   BinaryOperatorKind CondOpcode;
8124   Expr *CondRHS;
8125 
8126   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
8127     return;
8128   if (!ExprLooksBoolean(CondRHS))
8129     return;
8130 
8131   // The condition is an arithmetic binary expression, with a right-
8132   // hand side that looks boolean, so warn.
8133 
8134   unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode)
8135                         ? diag::warn_precedence_bitwise_conditional
8136                         : diag::warn_precedence_conditional;
8137 
8138   Self.Diag(OpLoc, DiagID)
8139       << Condition->getSourceRange()
8140       << BinaryOperator::getOpcodeStr(CondOpcode);
8141 
8142   SuggestParentheses(
8143       Self, OpLoc,
8144       Self.PDiag(diag::note_precedence_silence)
8145           << BinaryOperator::getOpcodeStr(CondOpcode),
8146       SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
8147 
8148   SuggestParentheses(Self, OpLoc,
8149                      Self.PDiag(diag::note_precedence_conditional_first),
8150                      SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
8151 }
8152 
8153 /// Compute the nullability of a conditional expression.
8154 static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
8155                                               QualType LHSTy, QualType RHSTy,
8156                                               ASTContext &Ctx) {
8157   if (!ResTy->isAnyPointerType())
8158     return ResTy;
8159 
8160   auto GetNullability = [&Ctx](QualType Ty) {
8161     Optional<NullabilityKind> Kind = Ty->getNullability(Ctx);
8162     if (Kind)
8163       return *Kind;
8164     return NullabilityKind::Unspecified;
8165   };
8166 
8167   auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
8168   NullabilityKind MergedKind;
8169 
8170   // Compute nullability of a binary conditional expression.
8171   if (IsBin) {
8172     if (LHSKind == NullabilityKind::NonNull)
8173       MergedKind = NullabilityKind::NonNull;
8174     else
8175       MergedKind = RHSKind;
8176   // Compute nullability of a normal conditional expression.
8177   } else {
8178     if (LHSKind == NullabilityKind::Nullable ||
8179         RHSKind == NullabilityKind::Nullable)
8180       MergedKind = NullabilityKind::Nullable;
8181     else if (LHSKind == NullabilityKind::NonNull)
8182       MergedKind = RHSKind;
8183     else if (RHSKind == NullabilityKind::NonNull)
8184       MergedKind = LHSKind;
8185     else
8186       MergedKind = NullabilityKind::Unspecified;
8187   }
8188 
8189   // Return if ResTy already has the correct nullability.
8190   if (GetNullability(ResTy) == MergedKind)
8191     return ResTy;
8192 
8193   // Strip all nullability from ResTy.
8194   while (ResTy->getNullability(Ctx))
8195     ResTy = ResTy.getSingleStepDesugaredType(Ctx);
8196 
8197   // Create a new AttributedType with the new nullability kind.
8198   auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
8199   return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
8200 }
8201 
8202 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
8203 /// in the case of a the GNU conditional expr extension.
8204 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
8205                                     SourceLocation ColonLoc,
8206                                     Expr *CondExpr, Expr *LHSExpr,
8207                                     Expr *RHSExpr) {
8208   if (!getLangOpts().CPlusPlus) {
8209     // C cannot handle TypoExpr nodes in the condition because it
8210     // doesn't handle dependent types properly, so make sure any TypoExprs have
8211     // been dealt with before checking the operands.
8212     ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
8213     ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
8214     ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
8215 
8216     if (!CondResult.isUsable())
8217       return ExprError();
8218 
8219     if (LHSExpr) {
8220       if (!LHSResult.isUsable())
8221         return ExprError();
8222     }
8223 
8224     if (!RHSResult.isUsable())
8225       return ExprError();
8226 
8227     CondExpr = CondResult.get();
8228     LHSExpr = LHSResult.get();
8229     RHSExpr = RHSResult.get();
8230   }
8231 
8232   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
8233   // was the condition.
8234   OpaqueValueExpr *opaqueValue = nullptr;
8235   Expr *commonExpr = nullptr;
8236   if (!LHSExpr) {
8237     commonExpr = CondExpr;
8238     // Lower out placeholder types first.  This is important so that we don't
8239     // try to capture a placeholder. This happens in few cases in C++; such
8240     // as Objective-C++'s dictionary subscripting syntax.
8241     if (commonExpr->hasPlaceholderType()) {
8242       ExprResult result = CheckPlaceholderExpr(commonExpr);
8243       if (!result.isUsable()) return ExprError();
8244       commonExpr = result.get();
8245     }
8246     // We usually want to apply unary conversions *before* saving, except
8247     // in the special case of a C++ l-value conditional.
8248     if (!(getLangOpts().CPlusPlus
8249           && !commonExpr->isTypeDependent()
8250           && commonExpr->getValueKind() == RHSExpr->getValueKind()
8251           && commonExpr->isGLValue()
8252           && commonExpr->isOrdinaryOrBitFieldObject()
8253           && RHSExpr->isOrdinaryOrBitFieldObject()
8254           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
8255       ExprResult commonRes = UsualUnaryConversions(commonExpr);
8256       if (commonRes.isInvalid())
8257         return ExprError();
8258       commonExpr = commonRes.get();
8259     }
8260 
8261     // If the common expression is a class or array prvalue, materialize it
8262     // so that we can safely refer to it multiple times.
8263     if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() ||
8264                                    commonExpr->getType()->isArrayType())) {
8265       ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
8266       if (MatExpr.isInvalid())
8267         return ExprError();
8268       commonExpr = MatExpr.get();
8269     }
8270 
8271     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
8272                                                 commonExpr->getType(),
8273                                                 commonExpr->getValueKind(),
8274                                                 commonExpr->getObjectKind(),
8275                                                 commonExpr);
8276     LHSExpr = CondExpr = opaqueValue;
8277   }
8278 
8279   QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
8280   ExprValueKind VK = VK_RValue;
8281   ExprObjectKind OK = OK_Ordinary;
8282   ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
8283   QualType result = CheckConditionalOperands(Cond, LHS, RHS,
8284                                              VK, OK, QuestionLoc);
8285   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
8286       RHS.isInvalid())
8287     return ExprError();
8288 
8289   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
8290                                 RHS.get());
8291 
8292   CheckBoolLikeConversion(Cond.get(), QuestionLoc);
8293 
8294   result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
8295                                          Context);
8296 
8297   if (!commonExpr)
8298     return new (Context)
8299         ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
8300                             RHS.get(), result, VK, OK);
8301 
8302   return new (Context) BinaryConditionalOperator(
8303       commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
8304       ColonLoc, result, VK, OK);
8305 }
8306 
8307 // Check if we have a conversion between incompatible cmse function pointer
8308 // types, that is, a conversion between a function pointer with the
8309 // cmse_nonsecure_call attribute and one without.
8310 static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType,
8311                                           QualType ToType) {
8312   if (const auto *ToFn =
8313           dyn_cast<FunctionType>(S.Context.getCanonicalType(ToType))) {
8314     if (const auto *FromFn =
8315             dyn_cast<FunctionType>(S.Context.getCanonicalType(FromType))) {
8316       FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
8317       FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
8318 
8319       return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall();
8320     }
8321   }
8322   return false;
8323 }
8324 
8325 // checkPointerTypesForAssignment - This is a very tricky routine (despite
8326 // being closely modeled after the C99 spec:-). The odd characteristic of this
8327 // routine is it effectively iqnores the qualifiers on the top level pointee.
8328 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
8329 // FIXME: add a couple examples in this comment.
8330 static Sema::AssignConvertType
8331 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
8332   assert(LHSType.isCanonical() && "LHS not canonicalized!");
8333   assert(RHSType.isCanonical() && "RHS not canonicalized!");
8334 
8335   // get the "pointed to" type (ignoring qualifiers at the top level)
8336   const Type *lhptee, *rhptee;
8337   Qualifiers lhq, rhq;
8338   std::tie(lhptee, lhq) =
8339       cast<PointerType>(LHSType)->getPointeeType().split().asPair();
8340   std::tie(rhptee, rhq) =
8341       cast<PointerType>(RHSType)->getPointeeType().split().asPair();
8342 
8343   Sema::AssignConvertType ConvTy = Sema::Compatible;
8344 
8345   // C99 6.5.16.1p1: This following citation is common to constraints
8346   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
8347   // qualifiers of the type *pointed to* by the right;
8348 
8349   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
8350   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
8351       lhq.compatiblyIncludesObjCLifetime(rhq)) {
8352     // Ignore lifetime for further calculation.
8353     lhq.removeObjCLifetime();
8354     rhq.removeObjCLifetime();
8355   }
8356 
8357   if (!lhq.compatiblyIncludes(rhq)) {
8358     // Treat address-space mismatches as fatal.
8359     if (!lhq.isAddressSpaceSupersetOf(rhq))
8360       return Sema::IncompatiblePointerDiscardsQualifiers;
8361 
8362     // It's okay to add or remove GC or lifetime qualifiers when converting to
8363     // and from void*.
8364     else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
8365                         .compatiblyIncludes(
8366                                 rhq.withoutObjCGCAttr().withoutObjCLifetime())
8367              && (lhptee->isVoidType() || rhptee->isVoidType()))
8368       ; // keep old
8369 
8370     // Treat lifetime mismatches as fatal.
8371     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
8372       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
8373 
8374     // For GCC/MS compatibility, other qualifier mismatches are treated
8375     // as still compatible in C.
8376     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
8377   }
8378 
8379   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
8380   // incomplete type and the other is a pointer to a qualified or unqualified
8381   // version of void...
8382   if (lhptee->isVoidType()) {
8383     if (rhptee->isIncompleteOrObjectType())
8384       return ConvTy;
8385 
8386     // As an extension, we allow cast to/from void* to function pointer.
8387     assert(rhptee->isFunctionType());
8388     return Sema::FunctionVoidPointer;
8389   }
8390 
8391   if (rhptee->isVoidType()) {
8392     if (lhptee->isIncompleteOrObjectType())
8393       return ConvTy;
8394 
8395     // As an extension, we allow cast to/from void* to function pointer.
8396     assert(lhptee->isFunctionType());
8397     return Sema::FunctionVoidPointer;
8398   }
8399 
8400   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
8401   // unqualified versions of compatible types, ...
8402   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
8403   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
8404     // Check if the pointee types are compatible ignoring the sign.
8405     // We explicitly check for char so that we catch "char" vs
8406     // "unsigned char" on systems where "char" is unsigned.
8407     if (lhptee->isCharType())
8408       ltrans = S.Context.UnsignedCharTy;
8409     else if (lhptee->hasSignedIntegerRepresentation())
8410       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
8411 
8412     if (rhptee->isCharType())
8413       rtrans = S.Context.UnsignedCharTy;
8414     else if (rhptee->hasSignedIntegerRepresentation())
8415       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
8416 
8417     if (ltrans == rtrans) {
8418       // Types are compatible ignoring the sign. Qualifier incompatibility
8419       // takes priority over sign incompatibility because the sign
8420       // warning can be disabled.
8421       if (ConvTy != Sema::Compatible)
8422         return ConvTy;
8423 
8424       return Sema::IncompatiblePointerSign;
8425     }
8426 
8427     // If we are a multi-level pointer, it's possible that our issue is simply
8428     // one of qualification - e.g. char ** -> const char ** is not allowed. If
8429     // the eventual target type is the same and the pointers have the same
8430     // level of indirection, this must be the issue.
8431     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
8432       do {
8433         std::tie(lhptee, lhq) =
8434           cast<PointerType>(lhptee)->getPointeeType().split().asPair();
8435         std::tie(rhptee, rhq) =
8436           cast<PointerType>(rhptee)->getPointeeType().split().asPair();
8437 
8438         // Inconsistent address spaces at this point is invalid, even if the
8439         // address spaces would be compatible.
8440         // FIXME: This doesn't catch address space mismatches for pointers of
8441         // different nesting levels, like:
8442         //   __local int *** a;
8443         //   int ** b = a;
8444         // It's not clear how to actually determine when such pointers are
8445         // invalidly incompatible.
8446         if (lhq.getAddressSpace() != rhq.getAddressSpace())
8447           return Sema::IncompatibleNestedPointerAddressSpaceMismatch;
8448 
8449       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
8450 
8451       if (lhptee == rhptee)
8452         return Sema::IncompatibleNestedPointerQualifiers;
8453     }
8454 
8455     // General pointer incompatibility takes priority over qualifiers.
8456     if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType())
8457       return Sema::IncompatibleFunctionPointer;
8458     return Sema::IncompatiblePointer;
8459   }
8460   if (!S.getLangOpts().CPlusPlus &&
8461       S.IsFunctionConversion(ltrans, rtrans, ltrans))
8462     return Sema::IncompatibleFunctionPointer;
8463   if (IsInvalidCmseNSCallConversion(S, ltrans, rtrans))
8464     return Sema::IncompatibleFunctionPointer;
8465   return ConvTy;
8466 }
8467 
8468 /// checkBlockPointerTypesForAssignment - This routine determines whether two
8469 /// block pointer types are compatible or whether a block and normal pointer
8470 /// are compatible. It is more restrict than comparing two function pointer
8471 // types.
8472 static Sema::AssignConvertType
8473 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
8474                                     QualType RHSType) {
8475   assert(LHSType.isCanonical() && "LHS not canonicalized!");
8476   assert(RHSType.isCanonical() && "RHS not canonicalized!");
8477 
8478   QualType lhptee, rhptee;
8479 
8480   // get the "pointed to" type (ignoring qualifiers at the top level)
8481   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
8482   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
8483 
8484   // In C++, the types have to match exactly.
8485   if (S.getLangOpts().CPlusPlus)
8486     return Sema::IncompatibleBlockPointer;
8487 
8488   Sema::AssignConvertType ConvTy = Sema::Compatible;
8489 
8490   // For blocks we enforce that qualifiers are identical.
8491   Qualifiers LQuals = lhptee.getLocalQualifiers();
8492   Qualifiers RQuals = rhptee.getLocalQualifiers();
8493   if (S.getLangOpts().OpenCL) {
8494     LQuals.removeAddressSpace();
8495     RQuals.removeAddressSpace();
8496   }
8497   if (LQuals != RQuals)
8498     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
8499 
8500   // FIXME: OpenCL doesn't define the exact compile time semantics for a block
8501   // assignment.
8502   // The current behavior is similar to C++ lambdas. A block might be
8503   // assigned to a variable iff its return type and parameters are compatible
8504   // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
8505   // an assignment. Presumably it should behave in way that a function pointer
8506   // assignment does in C, so for each parameter and return type:
8507   //  * CVR and address space of LHS should be a superset of CVR and address
8508   //  space of RHS.
8509   //  * unqualified types should be compatible.
8510   if (S.getLangOpts().OpenCL) {
8511     if (!S.Context.typesAreBlockPointerCompatible(
8512             S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
8513             S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
8514       return Sema::IncompatibleBlockPointer;
8515   } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
8516     return Sema::IncompatibleBlockPointer;
8517 
8518   return ConvTy;
8519 }
8520 
8521 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
8522 /// for assignment compatibility.
8523 static Sema::AssignConvertType
8524 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
8525                                    QualType RHSType) {
8526   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
8527   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
8528 
8529   if (LHSType->isObjCBuiltinType()) {
8530     // Class is not compatible with ObjC object pointers.
8531     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
8532         !RHSType->isObjCQualifiedClassType())
8533       return Sema::IncompatiblePointer;
8534     return Sema::Compatible;
8535   }
8536   if (RHSType->isObjCBuiltinType()) {
8537     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
8538         !LHSType->isObjCQualifiedClassType())
8539       return Sema::IncompatiblePointer;
8540     return Sema::Compatible;
8541   }
8542   QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
8543   QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
8544 
8545   if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
8546       // make an exception for id<P>
8547       !LHSType->isObjCQualifiedIdType())
8548     return Sema::CompatiblePointerDiscardsQualifiers;
8549 
8550   if (S.Context.typesAreCompatible(LHSType, RHSType))
8551     return Sema::Compatible;
8552   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
8553     return Sema::IncompatibleObjCQualifiedId;
8554   return Sema::IncompatiblePointer;
8555 }
8556 
8557 Sema::AssignConvertType
8558 Sema::CheckAssignmentConstraints(SourceLocation Loc,
8559                                  QualType LHSType, QualType RHSType) {
8560   // Fake up an opaque expression.  We don't actually care about what
8561   // cast operations are required, so if CheckAssignmentConstraints
8562   // adds casts to this they'll be wasted, but fortunately that doesn't
8563   // usually happen on valid code.
8564   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
8565   ExprResult RHSPtr = &RHSExpr;
8566   CastKind K;
8567 
8568   return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
8569 }
8570 
8571 /// This helper function returns true if QT is a vector type that has element
8572 /// type ElementType.
8573 static bool isVector(QualType QT, QualType ElementType) {
8574   if (const VectorType *VT = QT->getAs<VectorType>())
8575     return VT->getElementType().getCanonicalType() == ElementType;
8576   return false;
8577 }
8578 
8579 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
8580 /// has code to accommodate several GCC extensions when type checking
8581 /// pointers. Here are some objectionable examples that GCC considers warnings:
8582 ///
8583 ///  int a, *pint;
8584 ///  short *pshort;
8585 ///  struct foo *pfoo;
8586 ///
8587 ///  pint = pshort; // warning: assignment from incompatible pointer type
8588 ///  a = pint; // warning: assignment makes integer from pointer without a cast
8589 ///  pint = a; // warning: assignment makes pointer from integer without a cast
8590 ///  pint = pfoo; // warning: assignment from incompatible pointer type
8591 ///
8592 /// As a result, the code for dealing with pointers is more complex than the
8593 /// C99 spec dictates.
8594 ///
8595 /// Sets 'Kind' for any result kind except Incompatible.
8596 Sema::AssignConvertType
8597 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
8598                                  CastKind &Kind, bool ConvertRHS) {
8599   QualType RHSType = RHS.get()->getType();
8600   QualType OrigLHSType = LHSType;
8601 
8602   // Get canonical types.  We're not formatting these types, just comparing
8603   // them.
8604   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
8605   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
8606 
8607   // Common case: no conversion required.
8608   if (LHSType == RHSType) {
8609     Kind = CK_NoOp;
8610     return Compatible;
8611   }
8612 
8613   // If we have an atomic type, try a non-atomic assignment, then just add an
8614   // atomic qualification step.
8615   if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
8616     Sema::AssignConvertType result =
8617       CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
8618     if (result != Compatible)
8619       return result;
8620     if (Kind != CK_NoOp && ConvertRHS)
8621       RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
8622     Kind = CK_NonAtomicToAtomic;
8623     return Compatible;
8624   }
8625 
8626   // If the left-hand side is a reference type, then we are in a
8627   // (rare!) case where we've allowed the use of references in C,
8628   // e.g., as a parameter type in a built-in function. In this case,
8629   // just make sure that the type referenced is compatible with the
8630   // right-hand side type. The caller is responsible for adjusting
8631   // LHSType so that the resulting expression does not have reference
8632   // type.
8633   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
8634     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
8635       Kind = CK_LValueBitCast;
8636       return Compatible;
8637     }
8638     return Incompatible;
8639   }
8640 
8641   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
8642   // to the same ExtVector type.
8643   if (LHSType->isExtVectorType()) {
8644     if (RHSType->isExtVectorType())
8645       return Incompatible;
8646     if (RHSType->isArithmeticType()) {
8647       // CK_VectorSplat does T -> vector T, so first cast to the element type.
8648       if (ConvertRHS)
8649         RHS = prepareVectorSplat(LHSType, RHS.get());
8650       Kind = CK_VectorSplat;
8651       return Compatible;
8652     }
8653   }
8654 
8655   // Conversions to or from vector type.
8656   if (LHSType->isVectorType() || RHSType->isVectorType()) {
8657     if (LHSType->isVectorType() && RHSType->isVectorType()) {
8658       // Allow assignments of an AltiVec vector type to an equivalent GCC
8659       // vector type and vice versa
8660       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
8661         Kind = CK_BitCast;
8662         return Compatible;
8663       }
8664 
8665       // If we are allowing lax vector conversions, and LHS and RHS are both
8666       // vectors, the total size only needs to be the same. This is a bitcast;
8667       // no bits are changed but the result type is different.
8668       if (isLaxVectorConversion(RHSType, LHSType)) {
8669         Kind = CK_BitCast;
8670         return IncompatibleVectors;
8671       }
8672     }
8673 
8674     // When the RHS comes from another lax conversion (e.g. binops between
8675     // scalars and vectors) the result is canonicalized as a vector. When the
8676     // LHS is also a vector, the lax is allowed by the condition above. Handle
8677     // the case where LHS is a scalar.
8678     if (LHSType->isScalarType()) {
8679       const VectorType *VecType = RHSType->getAs<VectorType>();
8680       if (VecType && VecType->getNumElements() == 1 &&
8681           isLaxVectorConversion(RHSType, LHSType)) {
8682         ExprResult *VecExpr = &RHS;
8683         *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
8684         Kind = CK_BitCast;
8685         return Compatible;
8686       }
8687     }
8688 
8689     return Incompatible;
8690   }
8691 
8692   // Diagnose attempts to convert between __float128 and long double where
8693   // such conversions currently can't be handled.
8694   if (unsupportedTypeConversion(*this, LHSType, RHSType))
8695     return Incompatible;
8696 
8697   // Disallow assigning a _Complex to a real type in C++ mode since it simply
8698   // discards the imaginary part.
8699   if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
8700       !LHSType->getAs<ComplexType>())
8701     return Incompatible;
8702 
8703   // Arithmetic conversions.
8704   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
8705       !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
8706     if (ConvertRHS)
8707       Kind = PrepareScalarCast(RHS, LHSType);
8708     return Compatible;
8709   }
8710 
8711   // Conversions to normal pointers.
8712   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
8713     // U* -> T*
8714     if (isa<PointerType>(RHSType)) {
8715       LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
8716       LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
8717       if (AddrSpaceL != AddrSpaceR)
8718         Kind = CK_AddressSpaceConversion;
8719       else if (Context.hasCvrSimilarType(RHSType, LHSType))
8720         Kind = CK_NoOp;
8721       else
8722         Kind = CK_BitCast;
8723       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
8724     }
8725 
8726     // int -> T*
8727     if (RHSType->isIntegerType()) {
8728       Kind = CK_IntegralToPointer; // FIXME: null?
8729       return IntToPointer;
8730     }
8731 
8732     // C pointers are not compatible with ObjC object pointers,
8733     // with two exceptions:
8734     if (isa<ObjCObjectPointerType>(RHSType)) {
8735       //  - conversions to void*
8736       if (LHSPointer->getPointeeType()->isVoidType()) {
8737         Kind = CK_BitCast;
8738         return Compatible;
8739       }
8740 
8741       //  - conversions from 'Class' to the redefinition type
8742       if (RHSType->isObjCClassType() &&
8743           Context.hasSameType(LHSType,
8744                               Context.getObjCClassRedefinitionType())) {
8745         Kind = CK_BitCast;
8746         return Compatible;
8747       }
8748 
8749       Kind = CK_BitCast;
8750       return IncompatiblePointer;
8751     }
8752 
8753     // U^ -> void*
8754     if (RHSType->getAs<BlockPointerType>()) {
8755       if (LHSPointer->getPointeeType()->isVoidType()) {
8756         LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
8757         LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
8758                                 ->getPointeeType()
8759                                 .getAddressSpace();
8760         Kind =
8761             AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
8762         return Compatible;
8763       }
8764     }
8765 
8766     return Incompatible;
8767   }
8768 
8769   // Conversions to block pointers.
8770   if (isa<BlockPointerType>(LHSType)) {
8771     // U^ -> T^
8772     if (RHSType->isBlockPointerType()) {
8773       LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
8774                               ->getPointeeType()
8775                               .getAddressSpace();
8776       LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
8777                               ->getPointeeType()
8778                               .getAddressSpace();
8779       Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
8780       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
8781     }
8782 
8783     // int or null -> T^
8784     if (RHSType->isIntegerType()) {
8785       Kind = CK_IntegralToPointer; // FIXME: null
8786       return IntToBlockPointer;
8787     }
8788 
8789     // id -> T^
8790     if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
8791       Kind = CK_AnyPointerToBlockPointerCast;
8792       return Compatible;
8793     }
8794 
8795     // void* -> T^
8796     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
8797       if (RHSPT->getPointeeType()->isVoidType()) {
8798         Kind = CK_AnyPointerToBlockPointerCast;
8799         return Compatible;
8800       }
8801 
8802     return Incompatible;
8803   }
8804 
8805   // Conversions to Objective-C pointers.
8806   if (isa<ObjCObjectPointerType>(LHSType)) {
8807     // A* -> B*
8808     if (RHSType->isObjCObjectPointerType()) {
8809       Kind = CK_BitCast;
8810       Sema::AssignConvertType result =
8811         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
8812       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
8813           result == Compatible &&
8814           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
8815         result = IncompatibleObjCWeakRef;
8816       return result;
8817     }
8818 
8819     // int or null -> A*
8820     if (RHSType->isIntegerType()) {
8821       Kind = CK_IntegralToPointer; // FIXME: null
8822       return IntToPointer;
8823     }
8824 
8825     // In general, C pointers are not compatible with ObjC object pointers,
8826     // with two exceptions:
8827     if (isa<PointerType>(RHSType)) {
8828       Kind = CK_CPointerToObjCPointerCast;
8829 
8830       //  - conversions from 'void*'
8831       if (RHSType->isVoidPointerType()) {
8832         return Compatible;
8833       }
8834 
8835       //  - conversions to 'Class' from its redefinition type
8836       if (LHSType->isObjCClassType() &&
8837           Context.hasSameType(RHSType,
8838                               Context.getObjCClassRedefinitionType())) {
8839         return Compatible;
8840       }
8841 
8842       return IncompatiblePointer;
8843     }
8844 
8845     // Only under strict condition T^ is compatible with an Objective-C pointer.
8846     if (RHSType->isBlockPointerType() &&
8847         LHSType->isBlockCompatibleObjCPointerType(Context)) {
8848       if (ConvertRHS)
8849         maybeExtendBlockObject(RHS);
8850       Kind = CK_BlockPointerToObjCPointerCast;
8851       return Compatible;
8852     }
8853 
8854     return Incompatible;
8855   }
8856 
8857   // Conversions from pointers that are not covered by the above.
8858   if (isa<PointerType>(RHSType)) {
8859     // T* -> _Bool
8860     if (LHSType == Context.BoolTy) {
8861       Kind = CK_PointerToBoolean;
8862       return Compatible;
8863     }
8864 
8865     // T* -> int
8866     if (LHSType->isIntegerType()) {
8867       Kind = CK_PointerToIntegral;
8868       return PointerToInt;
8869     }
8870 
8871     return Incompatible;
8872   }
8873 
8874   // Conversions from Objective-C pointers that are not covered by the above.
8875   if (isa<ObjCObjectPointerType>(RHSType)) {
8876     // T* -> _Bool
8877     if (LHSType == Context.BoolTy) {
8878       Kind = CK_PointerToBoolean;
8879       return Compatible;
8880     }
8881 
8882     // T* -> int
8883     if (LHSType->isIntegerType()) {
8884       Kind = CK_PointerToIntegral;
8885       return PointerToInt;
8886     }
8887 
8888     return Incompatible;
8889   }
8890 
8891   // struct A -> struct B
8892   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
8893     if (Context.typesAreCompatible(LHSType, RHSType)) {
8894       Kind = CK_NoOp;
8895       return Compatible;
8896     }
8897   }
8898 
8899   if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
8900     Kind = CK_IntToOCLSampler;
8901     return Compatible;
8902   }
8903 
8904   return Incompatible;
8905 }
8906 
8907 /// Constructs a transparent union from an expression that is
8908 /// used to initialize the transparent union.
8909 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
8910                                       ExprResult &EResult, QualType UnionType,
8911                                       FieldDecl *Field) {
8912   // Build an initializer list that designates the appropriate member
8913   // of the transparent union.
8914   Expr *E = EResult.get();
8915   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
8916                                                    E, SourceLocation());
8917   Initializer->setType(UnionType);
8918   Initializer->setInitializedFieldInUnion(Field);
8919 
8920   // Build a compound literal constructing a value of the transparent
8921   // union type from this initializer list.
8922   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
8923   EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
8924                                         VK_RValue, Initializer, false);
8925 }
8926 
8927 Sema::AssignConvertType
8928 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
8929                                                ExprResult &RHS) {
8930   QualType RHSType = RHS.get()->getType();
8931 
8932   // If the ArgType is a Union type, we want to handle a potential
8933   // transparent_union GCC extension.
8934   const RecordType *UT = ArgType->getAsUnionType();
8935   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
8936     return Incompatible;
8937 
8938   // The field to initialize within the transparent union.
8939   RecordDecl *UD = UT->getDecl();
8940   FieldDecl *InitField = nullptr;
8941   // It's compatible if the expression matches any of the fields.
8942   for (auto *it : UD->fields()) {
8943     if (it->getType()->isPointerType()) {
8944       // If the transparent union contains a pointer type, we allow:
8945       // 1) void pointer
8946       // 2) null pointer constant
8947       if (RHSType->isPointerType())
8948         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
8949           RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
8950           InitField = it;
8951           break;
8952         }
8953 
8954       if (RHS.get()->isNullPointerConstant(Context,
8955                                            Expr::NPC_ValueDependentIsNull)) {
8956         RHS = ImpCastExprToType(RHS.get(), it->getType(),
8957                                 CK_NullToPointer);
8958         InitField = it;
8959         break;
8960       }
8961     }
8962 
8963     CastKind Kind;
8964     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
8965           == Compatible) {
8966       RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
8967       InitField = it;
8968       break;
8969     }
8970   }
8971 
8972   if (!InitField)
8973     return Incompatible;
8974 
8975   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
8976   return Compatible;
8977 }
8978 
8979 Sema::AssignConvertType
8980 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
8981                                        bool Diagnose,
8982                                        bool DiagnoseCFAudited,
8983                                        bool ConvertRHS) {
8984   // We need to be able to tell the caller whether we diagnosed a problem, if
8985   // they ask us to issue diagnostics.
8986   assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
8987 
8988   // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
8989   // we can't avoid *all* modifications at the moment, so we need some somewhere
8990   // to put the updated value.
8991   ExprResult LocalRHS = CallerRHS;
8992   ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
8993 
8994   if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
8995     if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
8996       if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
8997           !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
8998         Diag(RHS.get()->getExprLoc(),
8999              diag::warn_noderef_to_dereferenceable_pointer)
9000             << RHS.get()->getSourceRange();
9001       }
9002     }
9003   }
9004 
9005   if (getLangOpts().CPlusPlus) {
9006     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
9007       // C++ 5.17p3: If the left operand is not of class type, the
9008       // expression is implicitly converted (C++ 4) to the
9009       // cv-unqualified type of the left operand.
9010       QualType RHSType = RHS.get()->getType();
9011       if (Diagnose) {
9012         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9013                                         AA_Assigning);
9014       } else {
9015         ImplicitConversionSequence ICS =
9016             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9017                                   /*SuppressUserConversions=*/false,
9018                                   AllowedExplicit::None,
9019                                   /*InOverloadResolution=*/false,
9020                                   /*CStyle=*/false,
9021                                   /*AllowObjCWritebackConversion=*/false);
9022         if (ICS.isFailure())
9023           return Incompatible;
9024         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9025                                         ICS, AA_Assigning);
9026       }
9027       if (RHS.isInvalid())
9028         return Incompatible;
9029       Sema::AssignConvertType result = Compatible;
9030       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9031           !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
9032         result = IncompatibleObjCWeakRef;
9033       return result;
9034     }
9035 
9036     // FIXME: Currently, we fall through and treat C++ classes like C
9037     // structures.
9038     // FIXME: We also fall through for atomics; not sure what should
9039     // happen there, though.
9040   } else if (RHS.get()->getType() == Context.OverloadTy) {
9041     // As a set of extensions to C, we support overloading on functions. These
9042     // functions need to be resolved here.
9043     DeclAccessPair DAP;
9044     if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
9045             RHS.get(), LHSType, /*Complain=*/false, DAP))
9046       RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
9047     else
9048       return Incompatible;
9049   }
9050 
9051   // C99 6.5.16.1p1: the left operand is a pointer and the right is
9052   // a null pointer constant.
9053   if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
9054        LHSType->isBlockPointerType()) &&
9055       RHS.get()->isNullPointerConstant(Context,
9056                                        Expr::NPC_ValueDependentIsNull)) {
9057     if (Diagnose || ConvertRHS) {
9058       CastKind Kind;
9059       CXXCastPath Path;
9060       CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
9061                              /*IgnoreBaseAccess=*/false, Diagnose);
9062       if (ConvertRHS)
9063         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
9064     }
9065     return Compatible;
9066   }
9067 
9068   // OpenCL queue_t type assignment.
9069   if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
9070                                  Context, Expr::NPC_ValueDependentIsNull)) {
9071     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9072     return Compatible;
9073   }
9074 
9075   // This check seems unnatural, however it is necessary to ensure the proper
9076   // conversion of functions/arrays. If the conversion were done for all
9077   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
9078   // expressions that suppress this implicit conversion (&, sizeof).
9079   //
9080   // Suppress this for references: C++ 8.5.3p5.
9081   if (!LHSType->isReferenceType()) {
9082     // FIXME: We potentially allocate here even if ConvertRHS is false.
9083     RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
9084     if (RHS.isInvalid())
9085       return Incompatible;
9086   }
9087   CastKind Kind;
9088   Sema::AssignConvertType result =
9089     CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
9090 
9091   // C99 6.5.16.1p2: The value of the right operand is converted to the
9092   // type of the assignment expression.
9093   // CheckAssignmentConstraints allows the left-hand side to be a reference,
9094   // so that we can use references in built-in functions even in C.
9095   // The getNonReferenceType() call makes sure that the resulting expression
9096   // does not have reference type.
9097   if (result != Incompatible && RHS.get()->getType() != LHSType) {
9098     QualType Ty = LHSType.getNonLValueExprType(Context);
9099     Expr *E = RHS.get();
9100 
9101     // Check for various Objective-C errors. If we are not reporting
9102     // diagnostics and just checking for errors, e.g., during overload
9103     // resolution, return Incompatible to indicate the failure.
9104     if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9105         CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
9106                             Diagnose, DiagnoseCFAudited) != ACR_okay) {
9107       if (!Diagnose)
9108         return Incompatible;
9109     }
9110     if (getLangOpts().ObjC &&
9111         (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType,
9112                                            E->getType(), E, Diagnose) ||
9113          ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) {
9114       if (!Diagnose)
9115         return Incompatible;
9116       // Replace the expression with a corrected version and continue so we
9117       // can find further errors.
9118       RHS = E;
9119       return Compatible;
9120     }
9121 
9122     if (ConvertRHS)
9123       RHS = ImpCastExprToType(E, Ty, Kind);
9124   }
9125 
9126   return result;
9127 }
9128 
9129 namespace {
9130 /// The original operand to an operator, prior to the application of the usual
9131 /// arithmetic conversions and converting the arguments of a builtin operator
9132 /// candidate.
9133 struct OriginalOperand {
9134   explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
9135     if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op))
9136       Op = MTE->getSubExpr();
9137     if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op))
9138       Op = BTE->getSubExpr();
9139     if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) {
9140       Orig = ICE->getSubExprAsWritten();
9141       Conversion = ICE->getConversionFunction();
9142     }
9143   }
9144 
9145   QualType getType() const { return Orig->getType(); }
9146 
9147   Expr *Orig;
9148   NamedDecl *Conversion;
9149 };
9150 }
9151 
9152 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
9153                                ExprResult &RHS) {
9154   OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
9155 
9156   Diag(Loc, diag::err_typecheck_invalid_operands)
9157     << OrigLHS.getType() << OrigRHS.getType()
9158     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9159 
9160   // If a user-defined conversion was applied to either of the operands prior
9161   // to applying the built-in operator rules, tell the user about it.
9162   if (OrigLHS.Conversion) {
9163     Diag(OrigLHS.Conversion->getLocation(),
9164          diag::note_typecheck_invalid_operands_converted)
9165       << 0 << LHS.get()->getType();
9166   }
9167   if (OrigRHS.Conversion) {
9168     Diag(OrigRHS.Conversion->getLocation(),
9169          diag::note_typecheck_invalid_operands_converted)
9170       << 1 << RHS.get()->getType();
9171   }
9172 
9173   return QualType();
9174 }
9175 
9176 // Diagnose cases where a scalar was implicitly converted to a vector and
9177 // diagnose the underlying types. Otherwise, diagnose the error
9178 // as invalid vector logical operands for non-C++ cases.
9179 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
9180                                             ExprResult &RHS) {
9181   QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
9182   QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
9183 
9184   bool LHSNatVec = LHSType->isVectorType();
9185   bool RHSNatVec = RHSType->isVectorType();
9186 
9187   if (!(LHSNatVec && RHSNatVec)) {
9188     Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
9189     Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
9190     Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
9191         << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
9192         << Vector->getSourceRange();
9193     return QualType();
9194   }
9195 
9196   Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
9197       << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
9198       << RHS.get()->getSourceRange();
9199 
9200   return QualType();
9201 }
9202 
9203 /// Try to convert a value of non-vector type to a vector type by converting
9204 /// the type to the element type of the vector and then performing a splat.
9205 /// If the language is OpenCL, we only use conversions that promote scalar
9206 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
9207 /// for float->int.
9208 ///
9209 /// OpenCL V2.0 6.2.6.p2:
9210 /// An error shall occur if any scalar operand type has greater rank
9211 /// than the type of the vector element.
9212 ///
9213 /// \param scalar - if non-null, actually perform the conversions
9214 /// \return true if the operation fails (but without diagnosing the failure)
9215 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
9216                                      QualType scalarTy,
9217                                      QualType vectorEltTy,
9218                                      QualType vectorTy,
9219                                      unsigned &DiagID) {
9220   // The conversion to apply to the scalar before splatting it,
9221   // if necessary.
9222   CastKind scalarCast = CK_NoOp;
9223 
9224   if (vectorEltTy->isIntegralType(S.Context)) {
9225     if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
9226         (scalarTy->isIntegerType() &&
9227          S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
9228       DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
9229       return true;
9230     }
9231     if (!scalarTy->isIntegralType(S.Context))
9232       return true;
9233     scalarCast = CK_IntegralCast;
9234   } else if (vectorEltTy->isRealFloatingType()) {
9235     if (scalarTy->isRealFloatingType()) {
9236       if (S.getLangOpts().OpenCL &&
9237           S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
9238         DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
9239         return true;
9240       }
9241       scalarCast = CK_FloatingCast;
9242     }
9243     else if (scalarTy->isIntegralType(S.Context))
9244       scalarCast = CK_IntegralToFloating;
9245     else
9246       return true;
9247   } else {
9248     return true;
9249   }
9250 
9251   // Adjust scalar if desired.
9252   if (scalar) {
9253     if (scalarCast != CK_NoOp)
9254       *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
9255     *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
9256   }
9257   return false;
9258 }
9259 
9260 /// Convert vector E to a vector with the same number of elements but different
9261 /// element type.
9262 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
9263   const auto *VecTy = E->getType()->getAs<VectorType>();
9264   assert(VecTy && "Expression E must be a vector");
9265   QualType NewVecTy = S.Context.getVectorType(ElementType,
9266                                               VecTy->getNumElements(),
9267                                               VecTy->getVectorKind());
9268 
9269   // Look through the implicit cast. Return the subexpression if its type is
9270   // NewVecTy.
9271   if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
9272     if (ICE->getSubExpr()->getType() == NewVecTy)
9273       return ICE->getSubExpr();
9274 
9275   auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
9276   return S.ImpCastExprToType(E, NewVecTy, Cast);
9277 }
9278 
9279 /// Test if a (constant) integer Int can be casted to another integer type
9280 /// IntTy without losing precision.
9281 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int,
9282                                       QualType OtherIntTy) {
9283   QualType IntTy = Int->get()->getType().getUnqualifiedType();
9284 
9285   // Reject cases where the value of the Int is unknown as that would
9286   // possibly cause truncation, but accept cases where the scalar can be
9287   // demoted without loss of precision.
9288   Expr::EvalResult EVResult;
9289   bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
9290   int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
9291   bool IntSigned = IntTy->hasSignedIntegerRepresentation();
9292   bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
9293 
9294   if (CstInt) {
9295     // If the scalar is constant and is of a higher order and has more active
9296     // bits that the vector element type, reject it.
9297     llvm::APSInt Result = EVResult.Val.getInt();
9298     unsigned NumBits = IntSigned
9299                            ? (Result.isNegative() ? Result.getMinSignedBits()
9300                                                   : Result.getActiveBits())
9301                            : Result.getActiveBits();
9302     if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
9303       return true;
9304 
9305     // If the signedness of the scalar type and the vector element type
9306     // differs and the number of bits is greater than that of the vector
9307     // element reject it.
9308     return (IntSigned != OtherIntSigned &&
9309             NumBits > S.Context.getIntWidth(OtherIntTy));
9310   }
9311 
9312   // Reject cases where the value of the scalar is not constant and it's
9313   // order is greater than that of the vector element type.
9314   return (Order < 0);
9315 }
9316 
9317 /// Test if a (constant) integer Int can be casted to floating point type
9318 /// FloatTy without losing precision.
9319 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int,
9320                                      QualType FloatTy) {
9321   QualType IntTy = Int->get()->getType().getUnqualifiedType();
9322 
9323   // Determine if the integer constant can be expressed as a floating point
9324   // number of the appropriate type.
9325   Expr::EvalResult EVResult;
9326   bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
9327 
9328   uint64_t Bits = 0;
9329   if (CstInt) {
9330     // Reject constants that would be truncated if they were converted to
9331     // the floating point type. Test by simple to/from conversion.
9332     // FIXME: Ideally the conversion to an APFloat and from an APFloat
9333     //        could be avoided if there was a convertFromAPInt method
9334     //        which could signal back if implicit truncation occurred.
9335     llvm::APSInt Result = EVResult.Val.getInt();
9336     llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
9337     Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
9338                            llvm::APFloat::rmTowardZero);
9339     llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
9340                              !IntTy->hasSignedIntegerRepresentation());
9341     bool Ignored = false;
9342     Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
9343                            &Ignored);
9344     if (Result != ConvertBack)
9345       return true;
9346   } else {
9347     // Reject types that cannot be fully encoded into the mantissa of
9348     // the float.
9349     Bits = S.Context.getTypeSize(IntTy);
9350     unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
9351         S.Context.getFloatTypeSemantics(FloatTy));
9352     if (Bits > FloatPrec)
9353       return true;
9354   }
9355 
9356   return false;
9357 }
9358 
9359 /// Attempt to convert and splat Scalar into a vector whose types matches
9360 /// Vector following GCC conversion rules. The rule is that implicit
9361 /// conversion can occur when Scalar can be casted to match Vector's element
9362 /// type without causing truncation of Scalar.
9363 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar,
9364                                         ExprResult *Vector) {
9365   QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
9366   QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
9367   const VectorType *VT = VectorTy->getAs<VectorType>();
9368 
9369   assert(!isa<ExtVectorType>(VT) &&
9370          "ExtVectorTypes should not be handled here!");
9371 
9372   QualType VectorEltTy = VT->getElementType();
9373 
9374   // Reject cases where the vector element type or the scalar element type are
9375   // not integral or floating point types.
9376   if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
9377     return true;
9378 
9379   // The conversion to apply to the scalar before splatting it,
9380   // if necessary.
9381   CastKind ScalarCast = CK_NoOp;
9382 
9383   // Accept cases where the vector elements are integers and the scalar is
9384   // an integer.
9385   // FIXME: Notionally if the scalar was a floating point value with a precise
9386   //        integral representation, we could cast it to an appropriate integer
9387   //        type and then perform the rest of the checks here. GCC will perform
9388   //        this conversion in some cases as determined by the input language.
9389   //        We should accept it on a language independent basis.
9390   if (VectorEltTy->isIntegralType(S.Context) &&
9391       ScalarTy->isIntegralType(S.Context) &&
9392       S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
9393 
9394     if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
9395       return true;
9396 
9397     ScalarCast = CK_IntegralCast;
9398   } else if (VectorEltTy->isIntegralType(S.Context) &&
9399              ScalarTy->isRealFloatingType()) {
9400     if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy))
9401       ScalarCast = CK_FloatingToIntegral;
9402     else
9403       return true;
9404   } else if (VectorEltTy->isRealFloatingType()) {
9405     if (ScalarTy->isRealFloatingType()) {
9406 
9407       // Reject cases where the scalar type is not a constant and has a higher
9408       // Order than the vector element type.
9409       llvm::APFloat Result(0.0);
9410 
9411       // Determine whether this is a constant scalar. In the event that the
9412       // value is dependent (and thus cannot be evaluated by the constant
9413       // evaluator), skip the evaluation. This will then diagnose once the
9414       // expression is instantiated.
9415       bool CstScalar = Scalar->get()->isValueDependent() ||
9416                        Scalar->get()->EvaluateAsFloat(Result, S.Context);
9417       int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
9418       if (!CstScalar && Order < 0)
9419         return true;
9420 
9421       // If the scalar cannot be safely casted to the vector element type,
9422       // reject it.
9423       if (CstScalar) {
9424         bool Truncated = false;
9425         Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
9426                        llvm::APFloat::rmNearestTiesToEven, &Truncated);
9427         if (Truncated)
9428           return true;
9429       }
9430 
9431       ScalarCast = CK_FloatingCast;
9432     } else if (ScalarTy->isIntegralType(S.Context)) {
9433       if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
9434         return true;
9435 
9436       ScalarCast = CK_IntegralToFloating;
9437     } else
9438       return true;
9439   }
9440 
9441   // Adjust scalar if desired.
9442   if (Scalar) {
9443     if (ScalarCast != CK_NoOp)
9444       *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
9445     *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
9446   }
9447   return false;
9448 }
9449 
9450 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
9451                                    SourceLocation Loc, bool IsCompAssign,
9452                                    bool AllowBothBool,
9453                                    bool AllowBoolConversions) {
9454   if (!IsCompAssign) {
9455     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
9456     if (LHS.isInvalid())
9457       return QualType();
9458   }
9459   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
9460   if (RHS.isInvalid())
9461     return QualType();
9462 
9463   // For conversion purposes, we ignore any qualifiers.
9464   // For example, "const float" and "float" are equivalent.
9465   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
9466   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
9467 
9468   const VectorType *LHSVecType = LHSType->getAs<VectorType>();
9469   const VectorType *RHSVecType = RHSType->getAs<VectorType>();
9470   assert(LHSVecType || RHSVecType);
9471 
9472   // AltiVec-style "vector bool op vector bool" combinations are allowed
9473   // for some operators but not others.
9474   if (!AllowBothBool &&
9475       LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
9476       RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
9477     return InvalidOperands(Loc, LHS, RHS);
9478 
9479   // If the vector types are identical, return.
9480   if (Context.hasSameType(LHSType, RHSType))
9481     return LHSType;
9482 
9483   // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
9484   if (LHSVecType && RHSVecType &&
9485       Context.areCompatibleVectorTypes(LHSType, RHSType)) {
9486     if (isa<ExtVectorType>(LHSVecType)) {
9487       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9488       return LHSType;
9489     }
9490 
9491     if (!IsCompAssign)
9492       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
9493     return RHSType;
9494   }
9495 
9496   // AllowBoolConversions says that bool and non-bool AltiVec vectors
9497   // can be mixed, with the result being the non-bool type.  The non-bool
9498   // operand must have integer element type.
9499   if (AllowBoolConversions && LHSVecType && RHSVecType &&
9500       LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
9501       (Context.getTypeSize(LHSVecType->getElementType()) ==
9502        Context.getTypeSize(RHSVecType->getElementType()))) {
9503     if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
9504         LHSVecType->getElementType()->isIntegerType() &&
9505         RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
9506       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9507       return LHSType;
9508     }
9509     if (!IsCompAssign &&
9510         LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
9511         RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
9512         RHSVecType->getElementType()->isIntegerType()) {
9513       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
9514       return RHSType;
9515     }
9516   }
9517 
9518   // If there's a vector type and a scalar, try to convert the scalar to
9519   // the vector element type and splat.
9520   unsigned DiagID = diag::err_typecheck_vector_not_convertable;
9521   if (!RHSVecType) {
9522     if (isa<ExtVectorType>(LHSVecType)) {
9523       if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
9524                                     LHSVecType->getElementType(), LHSType,
9525                                     DiagID))
9526         return LHSType;
9527     } else {
9528       if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
9529         return LHSType;
9530     }
9531   }
9532   if (!LHSVecType) {
9533     if (isa<ExtVectorType>(RHSVecType)) {
9534       if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
9535                                     LHSType, RHSVecType->getElementType(),
9536                                     RHSType, DiagID))
9537         return RHSType;
9538     } else {
9539       if (LHS.get()->getValueKind() == VK_LValue ||
9540           !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
9541         return RHSType;
9542     }
9543   }
9544 
9545   // FIXME: The code below also handles conversion between vectors and
9546   // non-scalars, we should break this down into fine grained specific checks
9547   // and emit proper diagnostics.
9548   QualType VecType = LHSVecType ? LHSType : RHSType;
9549   const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
9550   QualType OtherType = LHSVecType ? RHSType : LHSType;
9551   ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
9552   if (isLaxVectorConversion(OtherType, VecType)) {
9553     // If we're allowing lax vector conversions, only the total (data) size
9554     // needs to be the same. For non compound assignment, if one of the types is
9555     // scalar, the result is always the vector type.
9556     if (!IsCompAssign) {
9557       *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
9558       return VecType;
9559     // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
9560     // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
9561     // type. Note that this is already done by non-compound assignments in
9562     // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
9563     // <1 x T> -> T. The result is also a vector type.
9564     } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
9565                (OtherType->isScalarType() && VT->getNumElements() == 1)) {
9566       ExprResult *RHSExpr = &RHS;
9567       *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
9568       return VecType;
9569     }
9570   }
9571 
9572   // Okay, the expression is invalid.
9573 
9574   // If there's a non-vector, non-real operand, diagnose that.
9575   if ((!RHSVecType && !RHSType->isRealType()) ||
9576       (!LHSVecType && !LHSType->isRealType())) {
9577     Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
9578       << LHSType << RHSType
9579       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9580     return QualType();
9581   }
9582 
9583   // OpenCL V1.1 6.2.6.p1:
9584   // If the operands are of more than one vector type, then an error shall
9585   // occur. Implicit conversions between vector types are not permitted, per
9586   // section 6.2.1.
9587   if (getLangOpts().OpenCL &&
9588       RHSVecType && isa<ExtVectorType>(RHSVecType) &&
9589       LHSVecType && isa<ExtVectorType>(LHSVecType)) {
9590     Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
9591                                                            << RHSType;
9592     return QualType();
9593   }
9594 
9595 
9596   // If there is a vector type that is not a ExtVector and a scalar, we reach
9597   // this point if scalar could not be converted to the vector's element type
9598   // without truncation.
9599   if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
9600       (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
9601     QualType Scalar = LHSVecType ? RHSType : LHSType;
9602     QualType Vector = LHSVecType ? LHSType : RHSType;
9603     unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
9604     Diag(Loc,
9605          diag::err_typecheck_vector_not_convertable_implict_truncation)
9606         << ScalarOrVector << Scalar << Vector;
9607 
9608     return QualType();
9609   }
9610 
9611   // Otherwise, use the generic diagnostic.
9612   Diag(Loc, DiagID)
9613     << LHSType << RHSType
9614     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9615   return QualType();
9616 }
9617 
9618 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
9619 // expression.  These are mainly cases where the null pointer is used as an
9620 // integer instead of a pointer.
9621 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
9622                                 SourceLocation Loc, bool IsCompare) {
9623   // The canonical way to check for a GNU null is with isNullPointerConstant,
9624   // but we use a bit of a hack here for speed; this is a relatively
9625   // hot path, and isNullPointerConstant is slow.
9626   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
9627   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
9628 
9629   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
9630 
9631   // Avoid analyzing cases where the result will either be invalid (and
9632   // diagnosed as such) or entirely valid and not something to warn about.
9633   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
9634       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
9635     return;
9636 
9637   // Comparison operations would not make sense with a null pointer no matter
9638   // what the other expression is.
9639   if (!IsCompare) {
9640     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
9641         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
9642         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
9643     return;
9644   }
9645 
9646   // The rest of the operations only make sense with a null pointer
9647   // if the other expression is a pointer.
9648   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
9649       NonNullType->canDecayToPointerType())
9650     return;
9651 
9652   S.Diag(Loc, diag::warn_null_in_comparison_operation)
9653       << LHSNull /* LHS is NULL */ << NonNullType
9654       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9655 }
9656 
9657 static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS,
9658                                           SourceLocation Loc) {
9659   const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS);
9660   const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS);
9661   if (!LUE || !RUE)
9662     return;
9663   if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
9664       RUE->getKind() != UETT_SizeOf)
9665     return;
9666 
9667   const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens();
9668   QualType LHSTy = LHSArg->getType();
9669   QualType RHSTy;
9670 
9671   if (RUE->isArgumentType())
9672     RHSTy = RUE->getArgumentType();
9673   else
9674     RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
9675 
9676   if (LHSTy->isPointerType() && !RHSTy->isPointerType()) {
9677     if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy))
9678       return;
9679 
9680     S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
9681     if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
9682       if (const ValueDecl *LHSArgDecl = DRE->getDecl())
9683         S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here)
9684             << LHSArgDecl;
9685     }
9686   } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) {
9687     QualType ArrayElemTy = ArrayTy->getElementType();
9688     if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) ||
9689         ArrayElemTy->isDependentType() || RHSTy->isDependentType() ||
9690         ArrayElemTy->isCharType() ||
9691         S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy))
9692       return;
9693     S.Diag(Loc, diag::warn_division_sizeof_array)
9694         << LHSArg->getSourceRange() << ArrayElemTy << RHSTy;
9695     if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
9696       if (const ValueDecl *LHSArgDecl = DRE->getDecl())
9697         S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here)
9698             << LHSArgDecl;
9699     }
9700 
9701     S.Diag(Loc, diag::note_precedence_silence) << RHS;
9702   }
9703 }
9704 
9705 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
9706                                                ExprResult &RHS,
9707                                                SourceLocation Loc, bool IsDiv) {
9708   // Check for division/remainder by zero.
9709   Expr::EvalResult RHSValue;
9710   if (!RHS.get()->isValueDependent() &&
9711       RHS.get()->EvaluateAsInt(RHSValue, S.Context) &&
9712       RHSValue.Val.getInt() == 0)
9713     S.DiagRuntimeBehavior(Loc, RHS.get(),
9714                           S.PDiag(diag::warn_remainder_division_by_zero)
9715                             << IsDiv << RHS.get()->getSourceRange());
9716 }
9717 
9718 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
9719                                            SourceLocation Loc,
9720                                            bool IsCompAssign, bool IsDiv) {
9721   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
9722 
9723   if (LHS.get()->getType()->isVectorType() ||
9724       RHS.get()->getType()->isVectorType())
9725     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
9726                                /*AllowBothBool*/getLangOpts().AltiVec,
9727                                /*AllowBoolConversions*/false);
9728 
9729   QualType compType = UsualArithmeticConversions(
9730       LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
9731   if (LHS.isInvalid() || RHS.isInvalid())
9732     return QualType();
9733 
9734 
9735   if (compType.isNull() || !compType->isArithmeticType())
9736     return InvalidOperands(Loc, LHS, RHS);
9737   if (IsDiv) {
9738     DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
9739     DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc);
9740   }
9741   return compType;
9742 }
9743 
9744 QualType Sema::CheckRemainderOperands(
9745   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
9746   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
9747 
9748   if (LHS.get()->getType()->isVectorType() ||
9749       RHS.get()->getType()->isVectorType()) {
9750     if (LHS.get()->getType()->hasIntegerRepresentation() &&
9751         RHS.get()->getType()->hasIntegerRepresentation())
9752       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
9753                                  /*AllowBothBool*/getLangOpts().AltiVec,
9754                                  /*AllowBoolConversions*/false);
9755     return InvalidOperands(Loc, LHS, RHS);
9756   }
9757 
9758   QualType compType = UsualArithmeticConversions(
9759       LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
9760   if (LHS.isInvalid() || RHS.isInvalid())
9761     return QualType();
9762 
9763   if (compType.isNull() || !compType->isIntegerType())
9764     return InvalidOperands(Loc, LHS, RHS);
9765   DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
9766   return compType;
9767 }
9768 
9769 /// Diagnose invalid arithmetic on two void pointers.
9770 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
9771                                                 Expr *LHSExpr, Expr *RHSExpr) {
9772   S.Diag(Loc, S.getLangOpts().CPlusPlus
9773                 ? diag::err_typecheck_pointer_arith_void_type
9774                 : diag::ext_gnu_void_ptr)
9775     << 1 /* two pointers */ << LHSExpr->getSourceRange()
9776                             << RHSExpr->getSourceRange();
9777 }
9778 
9779 /// Diagnose invalid arithmetic on a void pointer.
9780 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
9781                                             Expr *Pointer) {
9782   S.Diag(Loc, S.getLangOpts().CPlusPlus
9783                 ? diag::err_typecheck_pointer_arith_void_type
9784                 : diag::ext_gnu_void_ptr)
9785     << 0 /* one pointer */ << Pointer->getSourceRange();
9786 }
9787 
9788 /// Diagnose invalid arithmetic on a null pointer.
9789 ///
9790 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
9791 /// idiom, which we recognize as a GNU extension.
9792 ///
9793 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc,
9794                                             Expr *Pointer, bool IsGNUIdiom) {
9795   if (IsGNUIdiom)
9796     S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
9797       << Pointer->getSourceRange();
9798   else
9799     S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
9800       << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
9801 }
9802 
9803 /// Diagnose invalid arithmetic on two function pointers.
9804 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
9805                                                     Expr *LHS, Expr *RHS) {
9806   assert(LHS->getType()->isAnyPointerType());
9807   assert(RHS->getType()->isAnyPointerType());
9808   S.Diag(Loc, S.getLangOpts().CPlusPlus
9809                 ? diag::err_typecheck_pointer_arith_function_type
9810                 : diag::ext_gnu_ptr_func_arith)
9811     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
9812     // We only show the second type if it differs from the first.
9813     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
9814                                                    RHS->getType())
9815     << RHS->getType()->getPointeeType()
9816     << LHS->getSourceRange() << RHS->getSourceRange();
9817 }
9818 
9819 /// Diagnose invalid arithmetic on a function pointer.
9820 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
9821                                                 Expr *Pointer) {
9822   assert(Pointer->getType()->isAnyPointerType());
9823   S.Diag(Loc, S.getLangOpts().CPlusPlus
9824                 ? diag::err_typecheck_pointer_arith_function_type
9825                 : diag::ext_gnu_ptr_func_arith)
9826     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
9827     << 0 /* one pointer, so only one type */
9828     << Pointer->getSourceRange();
9829 }
9830 
9831 /// Emit error if Operand is incomplete pointer type
9832 ///
9833 /// \returns True if pointer has incomplete type
9834 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
9835                                                  Expr *Operand) {
9836   QualType ResType = Operand->getType();
9837   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
9838     ResType = ResAtomicType->getValueType();
9839 
9840   assert(ResType->isAnyPointerType() && !ResType->isDependentType());
9841   QualType PointeeTy = ResType->getPointeeType();
9842   return S.RequireCompleteSizedType(
9843       Loc, PointeeTy,
9844       diag::err_typecheck_arithmetic_incomplete_or_sizeless_type,
9845       Operand->getSourceRange());
9846 }
9847 
9848 /// Check the validity of an arithmetic pointer operand.
9849 ///
9850 /// If the operand has pointer type, this code will check for pointer types
9851 /// which are invalid in arithmetic operations. These will be diagnosed
9852 /// appropriately, including whether or not the use is supported as an
9853 /// extension.
9854 ///
9855 /// \returns True when the operand is valid to use (even if as an extension).
9856 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
9857                                             Expr *Operand) {
9858   QualType ResType = Operand->getType();
9859   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
9860     ResType = ResAtomicType->getValueType();
9861 
9862   if (!ResType->isAnyPointerType()) return true;
9863 
9864   QualType PointeeTy = ResType->getPointeeType();
9865   if (PointeeTy->isVoidType()) {
9866     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
9867     return !S.getLangOpts().CPlusPlus;
9868   }
9869   if (PointeeTy->isFunctionType()) {
9870     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
9871     return !S.getLangOpts().CPlusPlus;
9872   }
9873 
9874   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
9875 
9876   return true;
9877 }
9878 
9879 /// Check the validity of a binary arithmetic operation w.r.t. pointer
9880 /// operands.
9881 ///
9882 /// This routine will diagnose any invalid arithmetic on pointer operands much
9883 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
9884 /// for emitting a single diagnostic even for operations where both LHS and RHS
9885 /// are (potentially problematic) pointers.
9886 ///
9887 /// \returns True when the operand is valid to use (even if as an extension).
9888 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
9889                                                 Expr *LHSExpr, Expr *RHSExpr) {
9890   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
9891   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
9892   if (!isLHSPointer && !isRHSPointer) return true;
9893 
9894   QualType LHSPointeeTy, RHSPointeeTy;
9895   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
9896   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
9897 
9898   // if both are pointers check if operation is valid wrt address spaces
9899   if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) {
9900     const PointerType *lhsPtr = LHSExpr->getType()->castAs<PointerType>();
9901     const PointerType *rhsPtr = RHSExpr->getType()->castAs<PointerType>();
9902     if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) {
9903       S.Diag(Loc,
9904              diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
9905           << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
9906           << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
9907       return false;
9908     }
9909   }
9910 
9911   // Check for arithmetic on pointers to incomplete types.
9912   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
9913   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
9914   if (isLHSVoidPtr || isRHSVoidPtr) {
9915     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
9916     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
9917     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
9918 
9919     return !S.getLangOpts().CPlusPlus;
9920   }
9921 
9922   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
9923   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
9924   if (isLHSFuncPtr || isRHSFuncPtr) {
9925     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
9926     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
9927                                                                 RHSExpr);
9928     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
9929 
9930     return !S.getLangOpts().CPlusPlus;
9931   }
9932 
9933   if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
9934     return false;
9935   if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
9936     return false;
9937 
9938   return true;
9939 }
9940 
9941 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
9942 /// literal.
9943 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
9944                                   Expr *LHSExpr, Expr *RHSExpr) {
9945   StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
9946   Expr* IndexExpr = RHSExpr;
9947   if (!StrExpr) {
9948     StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
9949     IndexExpr = LHSExpr;
9950   }
9951 
9952   bool IsStringPlusInt = StrExpr &&
9953       IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
9954   if (!IsStringPlusInt || IndexExpr->isValueDependent())
9955     return;
9956 
9957   SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
9958   Self.Diag(OpLoc, diag::warn_string_plus_int)
9959       << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
9960 
9961   // Only print a fixit for "str" + int, not for int + "str".
9962   if (IndexExpr == RHSExpr) {
9963     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
9964     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
9965         << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
9966         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
9967         << FixItHint::CreateInsertion(EndLoc, "]");
9968   } else
9969     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
9970 }
9971 
9972 /// Emit a warning when adding a char literal to a string.
9973 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
9974                                    Expr *LHSExpr, Expr *RHSExpr) {
9975   const Expr *StringRefExpr = LHSExpr;
9976   const CharacterLiteral *CharExpr =
9977       dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
9978 
9979   if (!CharExpr) {
9980     CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
9981     StringRefExpr = RHSExpr;
9982   }
9983 
9984   if (!CharExpr || !StringRefExpr)
9985     return;
9986 
9987   const QualType StringType = StringRefExpr->getType();
9988 
9989   // Return if not a PointerType.
9990   if (!StringType->isAnyPointerType())
9991     return;
9992 
9993   // Return if not a CharacterType.
9994   if (!StringType->getPointeeType()->isAnyCharacterType())
9995     return;
9996 
9997   ASTContext &Ctx = Self.getASTContext();
9998   SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
9999 
10000   const QualType CharType = CharExpr->getType();
10001   if (!CharType->isAnyCharacterType() &&
10002       CharType->isIntegerType() &&
10003       llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
10004     Self.Diag(OpLoc, diag::warn_string_plus_char)
10005         << DiagRange << Ctx.CharTy;
10006   } else {
10007     Self.Diag(OpLoc, diag::warn_string_plus_char)
10008         << DiagRange << CharExpr->getType();
10009   }
10010 
10011   // Only print a fixit for str + char, not for char + str.
10012   if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
10013     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
10014     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
10015         << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
10016         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
10017         << FixItHint::CreateInsertion(EndLoc, "]");
10018   } else {
10019     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
10020   }
10021 }
10022 
10023 /// Emit error when two pointers are incompatible.
10024 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
10025                                            Expr *LHSExpr, Expr *RHSExpr) {
10026   assert(LHSExpr->getType()->isAnyPointerType());
10027   assert(RHSExpr->getType()->isAnyPointerType());
10028   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
10029     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
10030     << RHSExpr->getSourceRange();
10031 }
10032 
10033 // C99 6.5.6
10034 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
10035                                      SourceLocation Loc, BinaryOperatorKind Opc,
10036                                      QualType* CompLHSTy) {
10037   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10038 
10039   if (LHS.get()->getType()->isVectorType() ||
10040       RHS.get()->getType()->isVectorType()) {
10041     QualType compType = CheckVectorOperands(
10042         LHS, RHS, Loc, CompLHSTy,
10043         /*AllowBothBool*/getLangOpts().AltiVec,
10044         /*AllowBoolConversions*/getLangOpts().ZVector);
10045     if (CompLHSTy) *CompLHSTy = compType;
10046     return compType;
10047   }
10048 
10049   QualType compType = UsualArithmeticConversions(
10050       LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
10051   if (LHS.isInvalid() || RHS.isInvalid())
10052     return QualType();
10053 
10054   // Diagnose "string literal" '+' int and string '+' "char literal".
10055   if (Opc == BO_Add) {
10056     diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
10057     diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
10058   }
10059 
10060   // handle the common case first (both operands are arithmetic).
10061   if (!compType.isNull() && compType->isArithmeticType()) {
10062     if (CompLHSTy) *CompLHSTy = compType;
10063     return compType;
10064   }
10065 
10066   // Type-checking.  Ultimately the pointer's going to be in PExp;
10067   // note that we bias towards the LHS being the pointer.
10068   Expr *PExp = LHS.get(), *IExp = RHS.get();
10069 
10070   bool isObjCPointer;
10071   if (PExp->getType()->isPointerType()) {
10072     isObjCPointer = false;
10073   } else if (PExp->getType()->isObjCObjectPointerType()) {
10074     isObjCPointer = true;
10075   } else {
10076     std::swap(PExp, IExp);
10077     if (PExp->getType()->isPointerType()) {
10078       isObjCPointer = false;
10079     } else if (PExp->getType()->isObjCObjectPointerType()) {
10080       isObjCPointer = true;
10081     } else {
10082       return InvalidOperands(Loc, LHS, RHS);
10083     }
10084   }
10085   assert(PExp->getType()->isAnyPointerType());
10086 
10087   if (!IExp->getType()->isIntegerType())
10088     return InvalidOperands(Loc, LHS, RHS);
10089 
10090   // Adding to a null pointer results in undefined behavior.
10091   if (PExp->IgnoreParenCasts()->isNullPointerConstant(
10092           Context, Expr::NPC_ValueDependentIsNotNull)) {
10093     // In C++ adding zero to a null pointer is defined.
10094     Expr::EvalResult KnownVal;
10095     if (!getLangOpts().CPlusPlus ||
10096         (!IExp->isValueDependent() &&
10097          (!IExp->EvaluateAsInt(KnownVal, Context) ||
10098           KnownVal.Val.getInt() != 0))) {
10099       // Check the conditions to see if this is the 'p = nullptr + n' idiom.
10100       bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension(
10101           Context, BO_Add, PExp, IExp);
10102       diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
10103     }
10104   }
10105 
10106   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
10107     return QualType();
10108 
10109   if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
10110     return QualType();
10111 
10112   // Check array bounds for pointer arithemtic
10113   CheckArrayAccess(PExp, IExp);
10114 
10115   if (CompLHSTy) {
10116     QualType LHSTy = Context.isPromotableBitField(LHS.get());
10117     if (LHSTy.isNull()) {
10118       LHSTy = LHS.get()->getType();
10119       if (LHSTy->isPromotableIntegerType())
10120         LHSTy = Context.getPromotedIntegerType(LHSTy);
10121     }
10122     *CompLHSTy = LHSTy;
10123   }
10124 
10125   return PExp->getType();
10126 }
10127 
10128 // C99 6.5.6
10129 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
10130                                         SourceLocation Loc,
10131                                         QualType* CompLHSTy) {
10132   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10133 
10134   if (LHS.get()->getType()->isVectorType() ||
10135       RHS.get()->getType()->isVectorType()) {
10136     QualType compType = CheckVectorOperands(
10137         LHS, RHS, Loc, CompLHSTy,
10138         /*AllowBothBool*/getLangOpts().AltiVec,
10139         /*AllowBoolConversions*/getLangOpts().ZVector);
10140     if (CompLHSTy) *CompLHSTy = compType;
10141     return compType;
10142   }
10143 
10144   QualType compType = UsualArithmeticConversions(
10145       LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
10146   if (LHS.isInvalid() || RHS.isInvalid())
10147     return QualType();
10148 
10149   // Enforce type constraints: C99 6.5.6p3.
10150 
10151   // Handle the common case first (both operands are arithmetic).
10152   if (!compType.isNull() && compType->isArithmeticType()) {
10153     if (CompLHSTy) *CompLHSTy = compType;
10154     return compType;
10155   }
10156 
10157   // Either ptr - int   or   ptr - ptr.
10158   if (LHS.get()->getType()->isAnyPointerType()) {
10159     QualType lpointee = LHS.get()->getType()->getPointeeType();
10160 
10161     // Diagnose bad cases where we step over interface counts.
10162     if (LHS.get()->getType()->isObjCObjectPointerType() &&
10163         checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
10164       return QualType();
10165 
10166     // The result type of a pointer-int computation is the pointer type.
10167     if (RHS.get()->getType()->isIntegerType()) {
10168       // Subtracting from a null pointer should produce a warning.
10169       // The last argument to the diagnose call says this doesn't match the
10170       // GNU int-to-pointer idiom.
10171       if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context,
10172                                            Expr::NPC_ValueDependentIsNotNull)) {
10173         // In C++ adding zero to a null pointer is defined.
10174         Expr::EvalResult KnownVal;
10175         if (!getLangOpts().CPlusPlus ||
10176             (!RHS.get()->isValueDependent() &&
10177              (!RHS.get()->EvaluateAsInt(KnownVal, Context) ||
10178               KnownVal.Val.getInt() != 0))) {
10179           diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
10180         }
10181       }
10182 
10183       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
10184         return QualType();
10185 
10186       // Check array bounds for pointer arithemtic
10187       CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
10188                        /*AllowOnePastEnd*/true, /*IndexNegated*/true);
10189 
10190       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
10191       return LHS.get()->getType();
10192     }
10193 
10194     // Handle pointer-pointer subtractions.
10195     if (const PointerType *RHSPTy
10196           = RHS.get()->getType()->getAs<PointerType>()) {
10197       QualType rpointee = RHSPTy->getPointeeType();
10198 
10199       if (getLangOpts().CPlusPlus) {
10200         // Pointee types must be the same: C++ [expr.add]
10201         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
10202           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
10203         }
10204       } else {
10205         // Pointee types must be compatible C99 6.5.6p3
10206         if (!Context.typesAreCompatible(
10207                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
10208                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
10209           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
10210           return QualType();
10211         }
10212       }
10213 
10214       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
10215                                                LHS.get(), RHS.get()))
10216         return QualType();
10217 
10218       // FIXME: Add warnings for nullptr - ptr.
10219 
10220       // The pointee type may have zero size.  As an extension, a structure or
10221       // union may have zero size or an array may have zero length.  In this
10222       // case subtraction does not make sense.
10223       if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
10224         CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
10225         if (ElementSize.isZero()) {
10226           Diag(Loc,diag::warn_sub_ptr_zero_size_types)
10227             << rpointee.getUnqualifiedType()
10228             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10229         }
10230       }
10231 
10232       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
10233       return Context.getPointerDiffType();
10234     }
10235   }
10236 
10237   return InvalidOperands(Loc, LHS, RHS);
10238 }
10239 
10240 static bool isScopedEnumerationType(QualType T) {
10241   if (const EnumType *ET = T->getAs<EnumType>())
10242     return ET->getDecl()->isScoped();
10243   return false;
10244 }
10245 
10246 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
10247                                    SourceLocation Loc, BinaryOperatorKind Opc,
10248                                    QualType LHSType) {
10249   // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
10250   // so skip remaining warnings as we don't want to modify values within Sema.
10251   if (S.getLangOpts().OpenCL)
10252     return;
10253 
10254   // Check right/shifter operand
10255   Expr::EvalResult RHSResult;
10256   if (RHS.get()->isValueDependent() ||
10257       !RHS.get()->EvaluateAsInt(RHSResult, S.Context))
10258     return;
10259   llvm::APSInt Right = RHSResult.Val.getInt();
10260 
10261   if (Right.isNegative()) {
10262     S.DiagRuntimeBehavior(Loc, RHS.get(),
10263                           S.PDiag(diag::warn_shift_negative)
10264                             << RHS.get()->getSourceRange());
10265     return;
10266   }
10267   llvm::APInt LeftBits(Right.getBitWidth(),
10268                        S.Context.getTypeSize(LHS.get()->getType()));
10269   if (Right.uge(LeftBits)) {
10270     S.DiagRuntimeBehavior(Loc, RHS.get(),
10271                           S.PDiag(diag::warn_shift_gt_typewidth)
10272                             << RHS.get()->getSourceRange());
10273     return;
10274   }
10275   if (Opc != BO_Shl)
10276     return;
10277 
10278   // When left shifting an ICE which is signed, we can check for overflow which
10279   // according to C++ standards prior to C++2a has undefined behavior
10280   // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one
10281   // more than the maximum value representable in the result type, so never
10282   // warn for those. (FIXME: Unsigned left-shift overflow in a constant
10283   // expression is still probably a bug.)
10284   Expr::EvalResult LHSResult;
10285   if (LHS.get()->isValueDependent() ||
10286       LHSType->hasUnsignedIntegerRepresentation() ||
10287       !LHS.get()->EvaluateAsInt(LHSResult, S.Context))
10288     return;
10289   llvm::APSInt Left = LHSResult.Val.getInt();
10290 
10291   // If LHS does not have a signed type and non-negative value
10292   // then, the behavior is undefined before C++2a. Warn about it.
10293   if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined() &&
10294       !S.getLangOpts().CPlusPlus2a) {
10295     S.DiagRuntimeBehavior(Loc, LHS.get(),
10296                           S.PDiag(diag::warn_shift_lhs_negative)
10297                             << LHS.get()->getSourceRange());
10298     return;
10299   }
10300 
10301   llvm::APInt ResultBits =
10302       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
10303   if (LeftBits.uge(ResultBits))
10304     return;
10305   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
10306   Result = Result.shl(Right);
10307 
10308   // Print the bit representation of the signed integer as an unsigned
10309   // hexadecimal number.
10310   SmallString<40> HexResult;
10311   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
10312 
10313   // If we are only missing a sign bit, this is less likely to result in actual
10314   // bugs -- if the result is cast back to an unsigned type, it will have the
10315   // expected value. Thus we place this behind a different warning that can be
10316   // turned off separately if needed.
10317   if (LeftBits == ResultBits - 1) {
10318     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
10319         << HexResult << LHSType
10320         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10321     return;
10322   }
10323 
10324   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
10325     << HexResult.str() << Result.getMinSignedBits() << LHSType
10326     << Left.getBitWidth() << LHS.get()->getSourceRange()
10327     << RHS.get()->getSourceRange();
10328 }
10329 
10330 /// Return the resulting type when a vector is shifted
10331 ///        by a scalar or vector shift amount.
10332 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
10333                                  SourceLocation Loc, bool IsCompAssign) {
10334   // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
10335   if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
10336       !LHS.get()->getType()->isVectorType()) {
10337     S.Diag(Loc, diag::err_shift_rhs_only_vector)
10338       << RHS.get()->getType() << LHS.get()->getType()
10339       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10340     return QualType();
10341   }
10342 
10343   if (!IsCompAssign) {
10344     LHS = S.UsualUnaryConversions(LHS.get());
10345     if (LHS.isInvalid()) return QualType();
10346   }
10347 
10348   RHS = S.UsualUnaryConversions(RHS.get());
10349   if (RHS.isInvalid()) return QualType();
10350 
10351   QualType LHSType = LHS.get()->getType();
10352   // Note that LHS might be a scalar because the routine calls not only in
10353   // OpenCL case.
10354   const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
10355   QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
10356 
10357   // Note that RHS might not be a vector.
10358   QualType RHSType = RHS.get()->getType();
10359   const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
10360   QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
10361 
10362   // The operands need to be integers.
10363   if (!LHSEleType->isIntegerType()) {
10364     S.Diag(Loc, diag::err_typecheck_expect_int)
10365       << LHS.get()->getType() << LHS.get()->getSourceRange();
10366     return QualType();
10367   }
10368 
10369   if (!RHSEleType->isIntegerType()) {
10370     S.Diag(Loc, diag::err_typecheck_expect_int)
10371       << RHS.get()->getType() << RHS.get()->getSourceRange();
10372     return QualType();
10373   }
10374 
10375   if (!LHSVecTy) {
10376     assert(RHSVecTy);
10377     if (IsCompAssign)
10378       return RHSType;
10379     if (LHSEleType != RHSEleType) {
10380       LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
10381       LHSEleType = RHSEleType;
10382     }
10383     QualType VecTy =
10384         S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
10385     LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
10386     LHSType = VecTy;
10387   } else if (RHSVecTy) {
10388     // OpenCL v1.1 s6.3.j says that for vector types, the operators
10389     // are applied component-wise. So if RHS is a vector, then ensure
10390     // that the number of elements is the same as LHS...
10391     if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
10392       S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
10393         << LHS.get()->getType() << RHS.get()->getType()
10394         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10395       return QualType();
10396     }
10397     if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
10398       const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
10399       const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
10400       if (LHSBT != RHSBT &&
10401           S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
10402         S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
10403             << LHS.get()->getType() << RHS.get()->getType()
10404             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10405       }
10406     }
10407   } else {
10408     // ...else expand RHS to match the number of elements in LHS.
10409     QualType VecTy =
10410       S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
10411     RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
10412   }
10413 
10414   return LHSType;
10415 }
10416 
10417 // C99 6.5.7
10418 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
10419                                   SourceLocation Loc, BinaryOperatorKind Opc,
10420                                   bool IsCompAssign) {
10421   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10422 
10423   // Vector shifts promote their scalar inputs to vector type.
10424   if (LHS.get()->getType()->isVectorType() ||
10425       RHS.get()->getType()->isVectorType()) {
10426     if (LangOpts.ZVector) {
10427       // The shift operators for the z vector extensions work basically
10428       // like general shifts, except that neither the LHS nor the RHS is
10429       // allowed to be a "vector bool".
10430       if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
10431         if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
10432           return InvalidOperands(Loc, LHS, RHS);
10433       if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
10434         if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
10435           return InvalidOperands(Loc, LHS, RHS);
10436     }
10437     return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
10438   }
10439 
10440   // Shifts don't perform usual arithmetic conversions, they just do integer
10441   // promotions on each operand. C99 6.5.7p3
10442 
10443   // For the LHS, do usual unary conversions, but then reset them away
10444   // if this is a compound assignment.
10445   ExprResult OldLHS = LHS;
10446   LHS = UsualUnaryConversions(LHS.get());
10447   if (LHS.isInvalid())
10448     return QualType();
10449   QualType LHSType = LHS.get()->getType();
10450   if (IsCompAssign) LHS = OldLHS;
10451 
10452   // The RHS is simpler.
10453   RHS = UsualUnaryConversions(RHS.get());
10454   if (RHS.isInvalid())
10455     return QualType();
10456   QualType RHSType = RHS.get()->getType();
10457 
10458   // C99 6.5.7p2: Each of the operands shall have integer type.
10459   if (!LHSType->hasIntegerRepresentation() ||
10460       !RHSType->hasIntegerRepresentation())
10461     return InvalidOperands(Loc, LHS, RHS);
10462 
10463   // C++0x: Don't allow scoped enums. FIXME: Use something better than
10464   // hasIntegerRepresentation() above instead of this.
10465   if (isScopedEnumerationType(LHSType) ||
10466       isScopedEnumerationType(RHSType)) {
10467     return InvalidOperands(Loc, LHS, RHS);
10468   }
10469   // Sanity-check shift operands
10470   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
10471 
10472   // "The type of the result is that of the promoted left operand."
10473   return LHSType;
10474 }
10475 
10476 /// Diagnose bad pointer comparisons.
10477 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
10478                                               ExprResult &LHS, ExprResult &RHS,
10479                                               bool IsError) {
10480   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
10481                       : diag::ext_typecheck_comparison_of_distinct_pointers)
10482     << LHS.get()->getType() << RHS.get()->getType()
10483     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10484 }
10485 
10486 /// Returns false if the pointers are converted to a composite type,
10487 /// true otherwise.
10488 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
10489                                            ExprResult &LHS, ExprResult &RHS) {
10490   // C++ [expr.rel]p2:
10491   //   [...] Pointer conversions (4.10) and qualification
10492   //   conversions (4.4) are performed on pointer operands (or on
10493   //   a pointer operand and a null pointer constant) to bring
10494   //   them to their composite pointer type. [...]
10495   //
10496   // C++ [expr.eq]p1 uses the same notion for (in)equality
10497   // comparisons of pointers.
10498 
10499   QualType LHSType = LHS.get()->getType();
10500   QualType RHSType = RHS.get()->getType();
10501   assert(LHSType->isPointerType() || RHSType->isPointerType() ||
10502          LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
10503 
10504   QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
10505   if (T.isNull()) {
10506     if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) &&
10507         (RHSType->isAnyPointerType() || RHSType->isMemberPointerType()))
10508       diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
10509     else
10510       S.InvalidOperands(Loc, LHS, RHS);
10511     return true;
10512   }
10513 
10514   return false;
10515 }
10516 
10517 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
10518                                                     ExprResult &LHS,
10519                                                     ExprResult &RHS,
10520                                                     bool IsError) {
10521   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
10522                       : diag::ext_typecheck_comparison_of_fptr_to_void)
10523     << LHS.get()->getType() << RHS.get()->getType()
10524     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10525 }
10526 
10527 static bool isObjCObjectLiteral(ExprResult &E) {
10528   switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
10529   case Stmt::ObjCArrayLiteralClass:
10530   case Stmt::ObjCDictionaryLiteralClass:
10531   case Stmt::ObjCStringLiteralClass:
10532   case Stmt::ObjCBoxedExprClass:
10533     return true;
10534   default:
10535     // Note that ObjCBoolLiteral is NOT an object literal!
10536     return false;
10537   }
10538 }
10539 
10540 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
10541   const ObjCObjectPointerType *Type =
10542     LHS->getType()->getAs<ObjCObjectPointerType>();
10543 
10544   // If this is not actually an Objective-C object, bail out.
10545   if (!Type)
10546     return false;
10547 
10548   // Get the LHS object's interface type.
10549   QualType InterfaceType = Type->getPointeeType();
10550 
10551   // If the RHS isn't an Objective-C object, bail out.
10552   if (!RHS->getType()->isObjCObjectPointerType())
10553     return false;
10554 
10555   // Try to find the -isEqual: method.
10556   Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
10557   ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
10558                                                       InterfaceType,
10559                                                       /*IsInstance=*/true);
10560   if (!Method) {
10561     if (Type->isObjCIdType()) {
10562       // For 'id', just check the global pool.
10563       Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
10564                                                   /*receiverId=*/true);
10565     } else {
10566       // Check protocols.
10567       Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
10568                                              /*IsInstance=*/true);
10569     }
10570   }
10571 
10572   if (!Method)
10573     return false;
10574 
10575   QualType T = Method->parameters()[0]->getType();
10576   if (!T->isObjCObjectPointerType())
10577     return false;
10578 
10579   QualType R = Method->getReturnType();
10580   if (!R->isScalarType())
10581     return false;
10582 
10583   return true;
10584 }
10585 
10586 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
10587   FromE = FromE->IgnoreParenImpCasts();
10588   switch (FromE->getStmtClass()) {
10589     default:
10590       break;
10591     case Stmt::ObjCStringLiteralClass:
10592       // "string literal"
10593       return LK_String;
10594     case Stmt::ObjCArrayLiteralClass:
10595       // "array literal"
10596       return LK_Array;
10597     case Stmt::ObjCDictionaryLiteralClass:
10598       // "dictionary literal"
10599       return LK_Dictionary;
10600     case Stmt::BlockExprClass:
10601       return LK_Block;
10602     case Stmt::ObjCBoxedExprClass: {
10603       Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
10604       switch (Inner->getStmtClass()) {
10605         case Stmt::IntegerLiteralClass:
10606         case Stmt::FloatingLiteralClass:
10607         case Stmt::CharacterLiteralClass:
10608         case Stmt::ObjCBoolLiteralExprClass:
10609         case Stmt::CXXBoolLiteralExprClass:
10610           // "numeric literal"
10611           return LK_Numeric;
10612         case Stmt::ImplicitCastExprClass: {
10613           CastKind CK = cast<CastExpr>(Inner)->getCastKind();
10614           // Boolean literals can be represented by implicit casts.
10615           if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
10616             return LK_Numeric;
10617           break;
10618         }
10619         default:
10620           break;
10621       }
10622       return LK_Boxed;
10623     }
10624   }
10625   return LK_None;
10626 }
10627 
10628 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
10629                                           ExprResult &LHS, ExprResult &RHS,
10630                                           BinaryOperator::Opcode Opc){
10631   Expr *Literal;
10632   Expr *Other;
10633   if (isObjCObjectLiteral(LHS)) {
10634     Literal = LHS.get();
10635     Other = RHS.get();
10636   } else {
10637     Literal = RHS.get();
10638     Other = LHS.get();
10639   }
10640 
10641   // Don't warn on comparisons against nil.
10642   Other = Other->IgnoreParenCasts();
10643   if (Other->isNullPointerConstant(S.getASTContext(),
10644                                    Expr::NPC_ValueDependentIsNotNull))
10645     return;
10646 
10647   // This should be kept in sync with warn_objc_literal_comparison.
10648   // LK_String should always be after the other literals, since it has its own
10649   // warning flag.
10650   Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
10651   assert(LiteralKind != Sema::LK_Block);
10652   if (LiteralKind == Sema::LK_None) {
10653     llvm_unreachable("Unknown Objective-C object literal kind");
10654   }
10655 
10656   if (LiteralKind == Sema::LK_String)
10657     S.Diag(Loc, diag::warn_objc_string_literal_comparison)
10658       << Literal->getSourceRange();
10659   else
10660     S.Diag(Loc, diag::warn_objc_literal_comparison)
10661       << LiteralKind << Literal->getSourceRange();
10662 
10663   if (BinaryOperator::isEqualityOp(Opc) &&
10664       hasIsEqualMethod(S, LHS.get(), RHS.get())) {
10665     SourceLocation Start = LHS.get()->getBeginLoc();
10666     SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc());
10667     CharSourceRange OpRange =
10668       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
10669 
10670     S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
10671       << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
10672       << FixItHint::CreateReplacement(OpRange, " isEqual:")
10673       << FixItHint::CreateInsertion(End, "]");
10674   }
10675 }
10676 
10677 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
10678 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
10679                                            ExprResult &RHS, SourceLocation Loc,
10680                                            BinaryOperatorKind Opc) {
10681   // Check that left hand side is !something.
10682   UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
10683   if (!UO || UO->getOpcode() != UO_LNot) return;
10684 
10685   // Only check if the right hand side is non-bool arithmetic type.
10686   if (RHS.get()->isKnownToHaveBooleanValue()) return;
10687 
10688   // Make sure that the something in !something is not bool.
10689   Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
10690   if (SubExpr->isKnownToHaveBooleanValue()) return;
10691 
10692   // Emit warning.
10693   bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
10694   S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
10695       << Loc << IsBitwiseOp;
10696 
10697   // First note suggest !(x < y)
10698   SourceLocation FirstOpen = SubExpr->getBeginLoc();
10699   SourceLocation FirstClose = RHS.get()->getEndLoc();
10700   FirstClose = S.getLocForEndOfToken(FirstClose);
10701   if (FirstClose.isInvalid())
10702     FirstOpen = SourceLocation();
10703   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
10704       << IsBitwiseOp
10705       << FixItHint::CreateInsertion(FirstOpen, "(")
10706       << FixItHint::CreateInsertion(FirstClose, ")");
10707 
10708   // Second note suggests (!x) < y
10709   SourceLocation SecondOpen = LHS.get()->getBeginLoc();
10710   SourceLocation SecondClose = LHS.get()->getEndLoc();
10711   SecondClose = S.getLocForEndOfToken(SecondClose);
10712   if (SecondClose.isInvalid())
10713     SecondOpen = SourceLocation();
10714   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
10715       << FixItHint::CreateInsertion(SecondOpen, "(")
10716       << FixItHint::CreateInsertion(SecondClose, ")");
10717 }
10718 
10719 // Returns true if E refers to a non-weak array.
10720 static bool checkForArray(const Expr *E) {
10721   const ValueDecl *D = nullptr;
10722   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
10723     D = DR->getDecl();
10724   } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
10725     if (Mem->isImplicitAccess())
10726       D = Mem->getMemberDecl();
10727   }
10728   if (!D)
10729     return false;
10730   return D->getType()->isArrayType() && !D->isWeak();
10731 }
10732 
10733 /// Diagnose some forms of syntactically-obvious tautological comparison.
10734 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc,
10735                                            Expr *LHS, Expr *RHS,
10736                                            BinaryOperatorKind Opc) {
10737   Expr *LHSStripped = LHS->IgnoreParenImpCasts();
10738   Expr *RHSStripped = RHS->IgnoreParenImpCasts();
10739 
10740   QualType LHSType = LHS->getType();
10741   QualType RHSType = RHS->getType();
10742   if (LHSType->hasFloatingRepresentation() ||
10743       (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
10744       S.inTemplateInstantiation())
10745     return;
10746 
10747   // Comparisons between two array types are ill-formed for operator<=>, so
10748   // we shouldn't emit any additional warnings about it.
10749   if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
10750     return;
10751 
10752   // For non-floating point types, check for self-comparisons of the form
10753   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
10754   // often indicate logic errors in the program.
10755   //
10756   // NOTE: Don't warn about comparison expressions resulting from macro
10757   // expansion. Also don't warn about comparisons which are only self
10758   // comparisons within a template instantiation. The warnings should catch
10759   // obvious cases in the definition of the template anyways. The idea is to
10760   // warn when the typed comparison operator will always evaluate to the same
10761   // result.
10762 
10763   // Used for indexing into %select in warn_comparison_always
10764   enum {
10765     AlwaysConstant,
10766     AlwaysTrue,
10767     AlwaysFalse,
10768     AlwaysEqual, // std::strong_ordering::equal from operator<=>
10769   };
10770 
10771   // C++2a [depr.array.comp]:
10772   //   Equality and relational comparisons ([expr.eq], [expr.rel]) between two
10773   //   operands of array type are deprecated.
10774   if (S.getLangOpts().CPlusPlus2a && LHSStripped->getType()->isArrayType() &&
10775       RHSStripped->getType()->isArrayType()) {
10776     S.Diag(Loc, diag::warn_depr_array_comparison)
10777         << LHS->getSourceRange() << RHS->getSourceRange()
10778         << LHSStripped->getType() << RHSStripped->getType();
10779     // Carry on to produce the tautological comparison warning, if this
10780     // expression is potentially-evaluated, we can resolve the array to a
10781     // non-weak declaration, and so on.
10782   }
10783 
10784   if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) {
10785     if (Expr::isSameComparisonOperand(LHS, RHS)) {
10786       unsigned Result;
10787       switch (Opc) {
10788       case BO_EQ:
10789       case BO_LE:
10790       case BO_GE:
10791         Result = AlwaysTrue;
10792         break;
10793       case BO_NE:
10794       case BO_LT:
10795       case BO_GT:
10796         Result = AlwaysFalse;
10797         break;
10798       case BO_Cmp:
10799         Result = AlwaysEqual;
10800         break;
10801       default:
10802         Result = AlwaysConstant;
10803         break;
10804       }
10805       S.DiagRuntimeBehavior(Loc, nullptr,
10806                             S.PDiag(diag::warn_comparison_always)
10807                                 << 0 /*self-comparison*/
10808                                 << Result);
10809     } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) {
10810       // What is it always going to evaluate to?
10811       unsigned Result;
10812       switch (Opc) {
10813       case BO_EQ: // e.g. array1 == array2
10814         Result = AlwaysFalse;
10815         break;
10816       case BO_NE: // e.g. array1 != array2
10817         Result = AlwaysTrue;
10818         break;
10819       default: // e.g. array1 <= array2
10820         // The best we can say is 'a constant'
10821         Result = AlwaysConstant;
10822         break;
10823       }
10824       S.DiagRuntimeBehavior(Loc, nullptr,
10825                             S.PDiag(diag::warn_comparison_always)
10826                                 << 1 /*array comparison*/
10827                                 << Result);
10828     }
10829   }
10830 
10831   if (isa<CastExpr>(LHSStripped))
10832     LHSStripped = LHSStripped->IgnoreParenCasts();
10833   if (isa<CastExpr>(RHSStripped))
10834     RHSStripped = RHSStripped->IgnoreParenCasts();
10835 
10836   // Warn about comparisons against a string constant (unless the other
10837   // operand is null); the user probably wants string comparison function.
10838   Expr *LiteralString = nullptr;
10839   Expr *LiteralStringStripped = nullptr;
10840   if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
10841       !RHSStripped->isNullPointerConstant(S.Context,
10842                                           Expr::NPC_ValueDependentIsNull)) {
10843     LiteralString = LHS;
10844     LiteralStringStripped = LHSStripped;
10845   } else if ((isa<StringLiteral>(RHSStripped) ||
10846               isa<ObjCEncodeExpr>(RHSStripped)) &&
10847              !LHSStripped->isNullPointerConstant(S.Context,
10848                                           Expr::NPC_ValueDependentIsNull)) {
10849     LiteralString = RHS;
10850     LiteralStringStripped = RHSStripped;
10851   }
10852 
10853   if (LiteralString) {
10854     S.DiagRuntimeBehavior(Loc, nullptr,
10855                           S.PDiag(diag::warn_stringcompare)
10856                               << isa<ObjCEncodeExpr>(LiteralStringStripped)
10857                               << LiteralString->getSourceRange());
10858   }
10859 }
10860 
10861 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) {
10862   switch (CK) {
10863   default: {
10864 #ifndef NDEBUG
10865     llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
10866                  << "\n";
10867 #endif
10868     llvm_unreachable("unhandled cast kind");
10869   }
10870   case CK_UserDefinedConversion:
10871     return ICK_Identity;
10872   case CK_LValueToRValue:
10873     return ICK_Lvalue_To_Rvalue;
10874   case CK_ArrayToPointerDecay:
10875     return ICK_Array_To_Pointer;
10876   case CK_FunctionToPointerDecay:
10877     return ICK_Function_To_Pointer;
10878   case CK_IntegralCast:
10879     return ICK_Integral_Conversion;
10880   case CK_FloatingCast:
10881     return ICK_Floating_Conversion;
10882   case CK_IntegralToFloating:
10883   case CK_FloatingToIntegral:
10884     return ICK_Floating_Integral;
10885   case CK_IntegralComplexCast:
10886   case CK_FloatingComplexCast:
10887   case CK_FloatingComplexToIntegralComplex:
10888   case CK_IntegralComplexToFloatingComplex:
10889     return ICK_Complex_Conversion;
10890   case CK_FloatingComplexToReal:
10891   case CK_FloatingRealToComplex:
10892   case CK_IntegralComplexToReal:
10893   case CK_IntegralRealToComplex:
10894     return ICK_Complex_Real;
10895   }
10896 }
10897 
10898 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E,
10899                                              QualType FromType,
10900                                              SourceLocation Loc) {
10901   // Check for a narrowing implicit conversion.
10902   StandardConversionSequence SCS;
10903   SCS.setAsIdentityConversion();
10904   SCS.setToType(0, FromType);
10905   SCS.setToType(1, ToType);
10906   if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
10907     SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
10908 
10909   APValue PreNarrowingValue;
10910   QualType PreNarrowingType;
10911   switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
10912                                PreNarrowingType,
10913                                /*IgnoreFloatToIntegralConversion*/ true)) {
10914   case NK_Dependent_Narrowing:
10915     // Implicit conversion to a narrower type, but the expression is
10916     // value-dependent so we can't tell whether it's actually narrowing.
10917   case NK_Not_Narrowing:
10918     return false;
10919 
10920   case NK_Constant_Narrowing:
10921     // Implicit conversion to a narrower type, and the value is not a constant
10922     // expression.
10923     S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
10924         << /*Constant*/ 1
10925         << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
10926     return true;
10927 
10928   case NK_Variable_Narrowing:
10929     // Implicit conversion to a narrower type, and the value is not a constant
10930     // expression.
10931   case NK_Type_Narrowing:
10932     S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
10933         << /*Constant*/ 0 << FromType << ToType;
10934     // TODO: It's not a constant expression, but what if the user intended it
10935     // to be? Can we produce notes to help them figure out why it isn't?
10936     return true;
10937   }
10938   llvm_unreachable("unhandled case in switch");
10939 }
10940 
10941 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S,
10942                                                          ExprResult &LHS,
10943                                                          ExprResult &RHS,
10944                                                          SourceLocation Loc) {
10945   QualType LHSType = LHS.get()->getType();
10946   QualType RHSType = RHS.get()->getType();
10947   // Dig out the original argument type and expression before implicit casts
10948   // were applied. These are the types/expressions we need to check the
10949   // [expr.spaceship] requirements against.
10950   ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
10951   ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
10952   QualType LHSStrippedType = LHSStripped.get()->getType();
10953   QualType RHSStrippedType = RHSStripped.get()->getType();
10954 
10955   // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
10956   // other is not, the program is ill-formed.
10957   if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
10958     S.InvalidOperands(Loc, LHSStripped, RHSStripped);
10959     return QualType();
10960   }
10961 
10962   // FIXME: Consider combining this with checkEnumArithmeticConversions.
10963   int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
10964                     RHSStrippedType->isEnumeralType();
10965   if (NumEnumArgs == 1) {
10966     bool LHSIsEnum = LHSStrippedType->isEnumeralType();
10967     QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
10968     if (OtherTy->hasFloatingRepresentation()) {
10969       S.InvalidOperands(Loc, LHSStripped, RHSStripped);
10970       return QualType();
10971     }
10972   }
10973   if (NumEnumArgs == 2) {
10974     // C++2a [expr.spaceship]p5: If both operands have the same enumeration
10975     // type E, the operator yields the result of converting the operands
10976     // to the underlying type of E and applying <=> to the converted operands.
10977     if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
10978       S.InvalidOperands(Loc, LHS, RHS);
10979       return QualType();
10980     }
10981     QualType IntType =
10982         LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType();
10983     assert(IntType->isArithmeticType());
10984 
10985     // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
10986     // promote the boolean type, and all other promotable integer types, to
10987     // avoid this.
10988     if (IntType->isPromotableIntegerType())
10989       IntType = S.Context.getPromotedIntegerType(IntType);
10990 
10991     LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
10992     RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
10993     LHSType = RHSType = IntType;
10994   }
10995 
10996   // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
10997   // usual arithmetic conversions are applied to the operands.
10998   QualType Type =
10999       S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison);
11000   if (LHS.isInvalid() || RHS.isInvalid())
11001     return QualType();
11002   if (Type.isNull())
11003     return S.InvalidOperands(Loc, LHS, RHS);
11004 
11005   Optional<ComparisonCategoryType> CCT =
11006       getComparisonCategoryForBuiltinCmp(Type);
11007   if (!CCT)
11008     return S.InvalidOperands(Loc, LHS, RHS);
11009 
11010   bool HasNarrowing = checkThreeWayNarrowingConversion(
11011       S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc());
11012   HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType,
11013                                                    RHS.get()->getBeginLoc());
11014   if (HasNarrowing)
11015     return QualType();
11016 
11017   assert(!Type.isNull() && "composite type for <=> has not been set");
11018 
11019   return S.CheckComparisonCategoryType(
11020       *CCT, Loc, Sema::ComparisonCategoryUsage::OperatorInExpression);
11021 }
11022 
11023 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS,
11024                                                  ExprResult &RHS,
11025                                                  SourceLocation Loc,
11026                                                  BinaryOperatorKind Opc) {
11027   if (Opc == BO_Cmp)
11028     return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
11029 
11030   // C99 6.5.8p3 / C99 6.5.9p4
11031   QualType Type =
11032       S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison);
11033   if (LHS.isInvalid() || RHS.isInvalid())
11034     return QualType();
11035   if (Type.isNull())
11036     return S.InvalidOperands(Loc, LHS, RHS);
11037   assert(Type->isArithmeticType() || Type->isEnumeralType());
11038 
11039   if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc))
11040     return S.InvalidOperands(Loc, LHS, RHS);
11041 
11042   // Check for comparisons of floating point operands using != and ==.
11043   if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc))
11044     S.CheckFloatComparison(Loc, LHS.get(), RHS.get());
11045 
11046   // The result of comparisons is 'bool' in C++, 'int' in C.
11047   return S.Context.getLogicalOperationType();
11048 }
11049 
11050 void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) {
11051   if (!NullE.get()->getType()->isAnyPointerType())
11052     return;
11053   int NullValue = PP.isMacroDefined("NULL") ? 0 : 1;
11054   if (!E.get()->getType()->isAnyPointerType() &&
11055       E.get()->isNullPointerConstant(Context,
11056                                      Expr::NPC_ValueDependentIsNotNull) ==
11057         Expr::NPCK_ZeroExpression) {
11058     if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) {
11059       if (CL->getValue() == 0)
11060         Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
11061             << NullValue
11062             << FixItHint::CreateReplacement(E.get()->getExprLoc(),
11063                                             NullValue ? "NULL" : "(void *)0");
11064     } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) {
11065         TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
11066         QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType();
11067         if (T == Context.CharTy)
11068           Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
11069               << NullValue
11070               << FixItHint::CreateReplacement(E.get()->getExprLoc(),
11071                                               NullValue ? "NULL" : "(void *)0");
11072       }
11073   }
11074 }
11075 
11076 // C99 6.5.8, C++ [expr.rel]
11077 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
11078                                     SourceLocation Loc,
11079                                     BinaryOperatorKind Opc) {
11080   bool IsRelational = BinaryOperator::isRelationalOp(Opc);
11081   bool IsThreeWay = Opc == BO_Cmp;
11082   bool IsOrdered = IsRelational || IsThreeWay;
11083   auto IsAnyPointerType = [](ExprResult E) {
11084     QualType Ty = E.get()->getType();
11085     return Ty->isPointerType() || Ty->isMemberPointerType();
11086   };
11087 
11088   // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
11089   // type, array-to-pointer, ..., conversions are performed on both operands to
11090   // bring them to their composite type.
11091   // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
11092   // any type-related checks.
11093   if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
11094     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
11095     if (LHS.isInvalid())
11096       return QualType();
11097     RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
11098     if (RHS.isInvalid())
11099       return QualType();
11100   } else {
11101     LHS = DefaultLvalueConversion(LHS.get());
11102     if (LHS.isInvalid())
11103       return QualType();
11104     RHS = DefaultLvalueConversion(RHS.get());
11105     if (RHS.isInvalid())
11106       return QualType();
11107   }
11108 
11109   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true);
11110   if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) {
11111     CheckPtrComparisonWithNullChar(LHS, RHS);
11112     CheckPtrComparisonWithNullChar(RHS, LHS);
11113   }
11114 
11115   // Handle vector comparisons separately.
11116   if (LHS.get()->getType()->isVectorType() ||
11117       RHS.get()->getType()->isVectorType())
11118     return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
11119 
11120   diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
11121   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
11122 
11123   QualType LHSType = LHS.get()->getType();
11124   QualType RHSType = RHS.get()->getType();
11125   if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
11126       (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
11127     return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
11128 
11129   const Expr::NullPointerConstantKind LHSNullKind =
11130       LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
11131   const Expr::NullPointerConstantKind RHSNullKind =
11132       RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
11133   bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
11134   bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
11135 
11136   auto computeResultTy = [&]() {
11137     if (Opc != BO_Cmp)
11138       return Context.getLogicalOperationType();
11139     assert(getLangOpts().CPlusPlus);
11140     assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
11141 
11142     QualType CompositeTy = LHS.get()->getType();
11143     assert(!CompositeTy->isReferenceType());
11144 
11145     Optional<ComparisonCategoryType> CCT =
11146         getComparisonCategoryForBuiltinCmp(CompositeTy);
11147     if (!CCT)
11148       return InvalidOperands(Loc, LHS, RHS);
11149 
11150     if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) {
11151       // P0946R0: Comparisons between a null pointer constant and an object
11152       // pointer result in std::strong_equality, which is ill-formed under
11153       // P1959R0.
11154       Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero)
11155           << (LHSIsNull ? LHS.get()->getSourceRange()
11156                         : RHS.get()->getSourceRange());
11157       return QualType();
11158     }
11159 
11160     return CheckComparisonCategoryType(
11161         *CCT, Loc, ComparisonCategoryUsage::OperatorInExpression);
11162   };
11163 
11164   if (!IsOrdered && LHSIsNull != RHSIsNull) {
11165     bool IsEquality = Opc == BO_EQ;
11166     if (RHSIsNull)
11167       DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
11168                                    RHS.get()->getSourceRange());
11169     else
11170       DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
11171                                    LHS.get()->getSourceRange());
11172   }
11173 
11174   if ((LHSType->isIntegerType() && !LHSIsNull) ||
11175       (RHSType->isIntegerType() && !RHSIsNull)) {
11176     // Skip normal pointer conversion checks in this case; we have better
11177     // diagnostics for this below.
11178   } else if (getLangOpts().CPlusPlus) {
11179     // Equality comparison of a function pointer to a void pointer is invalid,
11180     // but we allow it as an extension.
11181     // FIXME: If we really want to allow this, should it be part of composite
11182     // pointer type computation so it works in conditionals too?
11183     if (!IsOrdered &&
11184         ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
11185          (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
11186       // This is a gcc extension compatibility comparison.
11187       // In a SFINAE context, we treat this as a hard error to maintain
11188       // conformance with the C++ standard.
11189       diagnoseFunctionPointerToVoidComparison(
11190           *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
11191 
11192       if (isSFINAEContext())
11193         return QualType();
11194 
11195       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
11196       return computeResultTy();
11197     }
11198 
11199     // C++ [expr.eq]p2:
11200     //   If at least one operand is a pointer [...] bring them to their
11201     //   composite pointer type.
11202     // C++ [expr.spaceship]p6
11203     //  If at least one of the operands is of pointer type, [...] bring them
11204     //  to their composite pointer type.
11205     // C++ [expr.rel]p2:
11206     //   If both operands are pointers, [...] bring them to their composite
11207     //   pointer type.
11208     // For <=>, the only valid non-pointer types are arrays and functions, and
11209     // we already decayed those, so this is really the same as the relational
11210     // comparison rule.
11211     if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
11212             (IsOrdered ? 2 : 1) &&
11213         (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
11214                                          RHSType->isObjCObjectPointerType()))) {
11215       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
11216         return QualType();
11217       return computeResultTy();
11218     }
11219   } else if (LHSType->isPointerType() &&
11220              RHSType->isPointerType()) { // C99 6.5.8p2
11221     // All of the following pointer-related warnings are GCC extensions, except
11222     // when handling null pointer constants.
11223     QualType LCanPointeeTy =
11224       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
11225     QualType RCanPointeeTy =
11226       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
11227 
11228     // C99 6.5.9p2 and C99 6.5.8p2
11229     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
11230                                    RCanPointeeTy.getUnqualifiedType())) {
11231       // Valid unless a relational comparison of function pointers
11232       if (IsRelational && LCanPointeeTy->isFunctionType()) {
11233         Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
11234           << LHSType << RHSType << LHS.get()->getSourceRange()
11235           << RHS.get()->getSourceRange();
11236       }
11237     } else if (!IsRelational &&
11238                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
11239       // Valid unless comparison between non-null pointer and function pointer
11240       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
11241           && !LHSIsNull && !RHSIsNull)
11242         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
11243                                                 /*isError*/false);
11244     } else {
11245       // Invalid
11246       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
11247     }
11248     if (LCanPointeeTy != RCanPointeeTy) {
11249       // Treat NULL constant as a special case in OpenCL.
11250       if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
11251         const PointerType *LHSPtr = LHSType->castAs<PointerType>();
11252         if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->castAs<PointerType>())) {
11253           Diag(Loc,
11254                diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
11255               << LHSType << RHSType << 0 /* comparison */
11256               << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11257         }
11258       }
11259       LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
11260       LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
11261       CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
11262                                                : CK_BitCast;
11263       if (LHSIsNull && !RHSIsNull)
11264         LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
11265       else
11266         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
11267     }
11268     return computeResultTy();
11269   }
11270 
11271   if (getLangOpts().CPlusPlus) {
11272     // C++ [expr.eq]p4:
11273     //   Two operands of type std::nullptr_t or one operand of type
11274     //   std::nullptr_t and the other a null pointer constant compare equal.
11275     if (!IsOrdered && LHSIsNull && RHSIsNull) {
11276       if (LHSType->isNullPtrType()) {
11277         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11278         return computeResultTy();
11279       }
11280       if (RHSType->isNullPtrType()) {
11281         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11282         return computeResultTy();
11283       }
11284     }
11285 
11286     // Comparison of Objective-C pointers and block pointers against nullptr_t.
11287     // These aren't covered by the composite pointer type rules.
11288     if (!IsOrdered && RHSType->isNullPtrType() &&
11289         (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
11290       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11291       return computeResultTy();
11292     }
11293     if (!IsOrdered && LHSType->isNullPtrType() &&
11294         (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
11295       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11296       return computeResultTy();
11297     }
11298 
11299     if (IsRelational &&
11300         ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
11301          (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
11302       // HACK: Relational comparison of nullptr_t against a pointer type is
11303       // invalid per DR583, but we allow it within std::less<> and friends,
11304       // since otherwise common uses of it break.
11305       // FIXME: Consider removing this hack once LWG fixes std::less<> and
11306       // friends to have std::nullptr_t overload candidates.
11307       DeclContext *DC = CurContext;
11308       if (isa<FunctionDecl>(DC))
11309         DC = DC->getParent();
11310       if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
11311         if (CTSD->isInStdNamespace() &&
11312             llvm::StringSwitch<bool>(CTSD->getName())
11313                 .Cases("less", "less_equal", "greater", "greater_equal", true)
11314                 .Default(false)) {
11315           if (RHSType->isNullPtrType())
11316             RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11317           else
11318             LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11319           return computeResultTy();
11320         }
11321       }
11322     }
11323 
11324     // C++ [expr.eq]p2:
11325     //   If at least one operand is a pointer to member, [...] bring them to
11326     //   their composite pointer type.
11327     if (!IsOrdered &&
11328         (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
11329       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
11330         return QualType();
11331       else
11332         return computeResultTy();
11333     }
11334   }
11335 
11336   // Handle block pointer types.
11337   if (!IsOrdered && LHSType->isBlockPointerType() &&
11338       RHSType->isBlockPointerType()) {
11339     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
11340     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
11341 
11342     if (!LHSIsNull && !RHSIsNull &&
11343         !Context.typesAreCompatible(lpointee, rpointee)) {
11344       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
11345         << LHSType << RHSType << LHS.get()->getSourceRange()
11346         << RHS.get()->getSourceRange();
11347     }
11348     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
11349     return computeResultTy();
11350   }
11351 
11352   // Allow block pointers to be compared with null pointer constants.
11353   if (!IsOrdered
11354       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
11355           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
11356     if (!LHSIsNull && !RHSIsNull) {
11357       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
11358              ->getPointeeType()->isVoidType())
11359             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
11360                 ->getPointeeType()->isVoidType())))
11361         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
11362           << LHSType << RHSType << LHS.get()->getSourceRange()
11363           << RHS.get()->getSourceRange();
11364     }
11365     if (LHSIsNull && !RHSIsNull)
11366       LHS = ImpCastExprToType(LHS.get(), RHSType,
11367                               RHSType->isPointerType() ? CK_BitCast
11368                                 : CK_AnyPointerToBlockPointerCast);
11369     else
11370       RHS = ImpCastExprToType(RHS.get(), LHSType,
11371                               LHSType->isPointerType() ? CK_BitCast
11372                                 : CK_AnyPointerToBlockPointerCast);
11373     return computeResultTy();
11374   }
11375 
11376   if (LHSType->isObjCObjectPointerType() ||
11377       RHSType->isObjCObjectPointerType()) {
11378     const PointerType *LPT = LHSType->getAs<PointerType>();
11379     const PointerType *RPT = RHSType->getAs<PointerType>();
11380     if (LPT || RPT) {
11381       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
11382       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
11383 
11384       if (!LPtrToVoid && !RPtrToVoid &&
11385           !Context.typesAreCompatible(LHSType, RHSType)) {
11386         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
11387                                           /*isError*/false);
11388       }
11389       // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than
11390       // the RHS, but we have test coverage for this behavior.
11391       // FIXME: Consider using convertPointersToCompositeType in C++.
11392       if (LHSIsNull && !RHSIsNull) {
11393         Expr *E = LHS.get();
11394         if (getLangOpts().ObjCAutoRefCount)
11395           CheckObjCConversion(SourceRange(), RHSType, E,
11396                               CCK_ImplicitConversion);
11397         LHS = ImpCastExprToType(E, RHSType,
11398                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
11399       }
11400       else {
11401         Expr *E = RHS.get();
11402         if (getLangOpts().ObjCAutoRefCount)
11403           CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion,
11404                               /*Diagnose=*/true,
11405                               /*DiagnoseCFAudited=*/false, Opc);
11406         RHS = ImpCastExprToType(E, LHSType,
11407                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
11408       }
11409       return computeResultTy();
11410     }
11411     if (LHSType->isObjCObjectPointerType() &&
11412         RHSType->isObjCObjectPointerType()) {
11413       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
11414         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
11415                                           /*isError*/false);
11416       if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
11417         diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
11418 
11419       if (LHSIsNull && !RHSIsNull)
11420         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
11421       else
11422         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
11423       return computeResultTy();
11424     }
11425 
11426     if (!IsOrdered && LHSType->isBlockPointerType() &&
11427         RHSType->isBlockCompatibleObjCPointerType(Context)) {
11428       LHS = ImpCastExprToType(LHS.get(), RHSType,
11429                               CK_BlockPointerToObjCPointerCast);
11430       return computeResultTy();
11431     } else if (!IsOrdered &&
11432                LHSType->isBlockCompatibleObjCPointerType(Context) &&
11433                RHSType->isBlockPointerType()) {
11434       RHS = ImpCastExprToType(RHS.get(), LHSType,
11435                               CK_BlockPointerToObjCPointerCast);
11436       return computeResultTy();
11437     }
11438   }
11439   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
11440       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
11441     unsigned DiagID = 0;
11442     bool isError = false;
11443     if (LangOpts.DebuggerSupport) {
11444       // Under a debugger, allow the comparison of pointers to integers,
11445       // since users tend to want to compare addresses.
11446     } else if ((LHSIsNull && LHSType->isIntegerType()) ||
11447                (RHSIsNull && RHSType->isIntegerType())) {
11448       if (IsOrdered) {
11449         isError = getLangOpts().CPlusPlus;
11450         DiagID =
11451           isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
11452                   : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
11453       }
11454     } else if (getLangOpts().CPlusPlus) {
11455       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
11456       isError = true;
11457     } else if (IsOrdered)
11458       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
11459     else
11460       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
11461 
11462     if (DiagID) {
11463       Diag(Loc, DiagID)
11464         << LHSType << RHSType << LHS.get()->getSourceRange()
11465         << RHS.get()->getSourceRange();
11466       if (isError)
11467         return QualType();
11468     }
11469 
11470     if (LHSType->isIntegerType())
11471       LHS = ImpCastExprToType(LHS.get(), RHSType,
11472                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
11473     else
11474       RHS = ImpCastExprToType(RHS.get(), LHSType,
11475                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
11476     return computeResultTy();
11477   }
11478 
11479   // Handle block pointers.
11480   if (!IsOrdered && RHSIsNull
11481       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
11482     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11483     return computeResultTy();
11484   }
11485   if (!IsOrdered && LHSIsNull
11486       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
11487     LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11488     return computeResultTy();
11489   }
11490 
11491   if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) {
11492     if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
11493       return computeResultTy();
11494     }
11495 
11496     if (LHSType->isQueueT() && RHSType->isQueueT()) {
11497       return computeResultTy();
11498     }
11499 
11500     if (LHSIsNull && RHSType->isQueueT()) {
11501       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11502       return computeResultTy();
11503     }
11504 
11505     if (LHSType->isQueueT() && RHSIsNull) {
11506       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11507       return computeResultTy();
11508     }
11509   }
11510 
11511   return InvalidOperands(Loc, LHS, RHS);
11512 }
11513 
11514 // Return a signed ext_vector_type that is of identical size and number of
11515 // elements. For floating point vectors, return an integer type of identical
11516 // size and number of elements. In the non ext_vector_type case, search from
11517 // the largest type to the smallest type to avoid cases where long long == long,
11518 // where long gets picked over long long.
11519 QualType Sema::GetSignedVectorType(QualType V) {
11520   const VectorType *VTy = V->castAs<VectorType>();
11521   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
11522 
11523   if (isa<ExtVectorType>(VTy)) {
11524     if (TypeSize == Context.getTypeSize(Context.CharTy))
11525       return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
11526     else if (TypeSize == Context.getTypeSize(Context.ShortTy))
11527       return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
11528     else if (TypeSize == Context.getTypeSize(Context.IntTy))
11529       return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
11530     else if (TypeSize == Context.getTypeSize(Context.LongTy))
11531       return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
11532     assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
11533            "Unhandled vector element size in vector compare");
11534     return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
11535   }
11536 
11537   if (TypeSize == Context.getTypeSize(Context.LongLongTy))
11538     return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
11539                                  VectorType::GenericVector);
11540   else if (TypeSize == Context.getTypeSize(Context.LongTy))
11541     return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
11542                                  VectorType::GenericVector);
11543   else if (TypeSize == Context.getTypeSize(Context.IntTy))
11544     return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
11545                                  VectorType::GenericVector);
11546   else if (TypeSize == Context.getTypeSize(Context.ShortTy))
11547     return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
11548                                  VectorType::GenericVector);
11549   assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
11550          "Unhandled vector element size in vector compare");
11551   return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
11552                                VectorType::GenericVector);
11553 }
11554 
11555 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
11556 /// operates on extended vector types.  Instead of producing an IntTy result,
11557 /// like a scalar comparison, a vector comparison produces a vector of integer
11558 /// types.
11559 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
11560                                           SourceLocation Loc,
11561                                           BinaryOperatorKind Opc) {
11562   if (Opc == BO_Cmp) {
11563     Diag(Loc, diag::err_three_way_vector_comparison);
11564     return QualType();
11565   }
11566 
11567   // Check to make sure we're operating on vectors of the same type and width,
11568   // Allowing one side to be a scalar of element type.
11569   QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
11570                               /*AllowBothBool*/true,
11571                               /*AllowBoolConversions*/getLangOpts().ZVector);
11572   if (vType.isNull())
11573     return vType;
11574 
11575   QualType LHSType = LHS.get()->getType();
11576 
11577   // If AltiVec, the comparison results in a numeric type, i.e.
11578   // bool for C++, int for C
11579   if (getLangOpts().AltiVec &&
11580       vType->castAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
11581     return Context.getLogicalOperationType();
11582 
11583   // For non-floating point types, check for self-comparisons of the form
11584   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
11585   // often indicate logic errors in the program.
11586   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
11587 
11588   // Check for comparisons of floating point operands using != and ==.
11589   if (BinaryOperator::isEqualityOp(Opc) &&
11590       LHSType->hasFloatingRepresentation()) {
11591     assert(RHS.get()->getType()->hasFloatingRepresentation());
11592     CheckFloatComparison(Loc, LHS.get(), RHS.get());
11593   }
11594 
11595   // Return a signed type for the vector.
11596   return GetSignedVectorType(vType);
11597 }
11598 
11599 static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS,
11600                                     const ExprResult &XorRHS,
11601                                     const SourceLocation Loc) {
11602   // Do not diagnose macros.
11603   if (Loc.isMacroID())
11604     return;
11605 
11606   bool Negative = false;
11607   bool ExplicitPlus = false;
11608   const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get());
11609   const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get());
11610 
11611   if (!LHSInt)
11612     return;
11613   if (!RHSInt) {
11614     // Check negative literals.
11615     if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) {
11616       UnaryOperatorKind Opc = UO->getOpcode();
11617       if (Opc != UO_Minus && Opc != UO_Plus)
11618         return;
11619       RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr());
11620       if (!RHSInt)
11621         return;
11622       Negative = (Opc == UO_Minus);
11623       ExplicitPlus = !Negative;
11624     } else {
11625       return;
11626     }
11627   }
11628 
11629   const llvm::APInt &LeftSideValue = LHSInt->getValue();
11630   llvm::APInt RightSideValue = RHSInt->getValue();
11631   if (LeftSideValue != 2 && LeftSideValue != 10)
11632     return;
11633 
11634   if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth())
11635     return;
11636 
11637   CharSourceRange ExprRange = CharSourceRange::getCharRange(
11638       LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation()));
11639   llvm::StringRef ExprStr =
11640       Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts());
11641 
11642   CharSourceRange XorRange =
11643       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
11644   llvm::StringRef XorStr =
11645       Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts());
11646   // Do not diagnose if xor keyword/macro is used.
11647   if (XorStr == "xor")
11648     return;
11649 
11650   std::string LHSStr = std::string(Lexer::getSourceText(
11651       CharSourceRange::getTokenRange(LHSInt->getSourceRange()),
11652       S.getSourceManager(), S.getLangOpts()));
11653   std::string RHSStr = std::string(Lexer::getSourceText(
11654       CharSourceRange::getTokenRange(RHSInt->getSourceRange()),
11655       S.getSourceManager(), S.getLangOpts()));
11656 
11657   if (Negative) {
11658     RightSideValue = -RightSideValue;
11659     RHSStr = "-" + RHSStr;
11660   } else if (ExplicitPlus) {
11661     RHSStr = "+" + RHSStr;
11662   }
11663 
11664   StringRef LHSStrRef = LHSStr;
11665   StringRef RHSStrRef = RHSStr;
11666   // Do not diagnose literals with digit separators, binary, hexadecimal, octal
11667   // literals.
11668   if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") ||
11669       RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") ||
11670       LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") ||
11671       RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") ||
11672       (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) ||
11673       (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) ||
11674       LHSStrRef.find('\'') != StringRef::npos ||
11675       RHSStrRef.find('\'') != StringRef::npos)
11676     return;
11677 
11678   bool SuggestXor = S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor");
11679   const llvm::APInt XorValue = LeftSideValue ^ RightSideValue;
11680   int64_t RightSideIntValue = RightSideValue.getSExtValue();
11681   if (LeftSideValue == 2 && RightSideIntValue >= 0) {
11682     std::string SuggestedExpr = "1 << " + RHSStr;
11683     bool Overflow = false;
11684     llvm::APInt One = (LeftSideValue - 1);
11685     llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow);
11686     if (Overflow) {
11687       if (RightSideIntValue < 64)
11688         S.Diag(Loc, diag::warn_xor_used_as_pow_base)
11689             << ExprStr << XorValue.toString(10, true) << ("1LL << " + RHSStr)
11690             << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr);
11691       else if (RightSideIntValue == 64)
11692         S.Diag(Loc, diag::warn_xor_used_as_pow) << ExprStr << XorValue.toString(10, true);
11693       else
11694         return;
11695     } else {
11696       S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra)
11697           << ExprStr << XorValue.toString(10, true) << SuggestedExpr
11698           << PowValue.toString(10, true)
11699           << FixItHint::CreateReplacement(
11700                  ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr);
11701     }
11702 
11703     S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0x2 ^ " + RHSStr) << SuggestXor;
11704   } else if (LeftSideValue == 10) {
11705     std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue);
11706     S.Diag(Loc, diag::warn_xor_used_as_pow_base)
11707         << ExprStr << XorValue.toString(10, true) << SuggestedValue
11708         << FixItHint::CreateReplacement(ExprRange, SuggestedValue);
11709     S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0xA ^ " + RHSStr) << SuggestXor;
11710   }
11711 }
11712 
11713 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
11714                                           SourceLocation Loc) {
11715   // Ensure that either both operands are of the same vector type, or
11716   // one operand is of a vector type and the other is of its element type.
11717   QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
11718                                        /*AllowBothBool*/true,
11719                                        /*AllowBoolConversions*/false);
11720   if (vType.isNull())
11721     return InvalidOperands(Loc, LHS, RHS);
11722   if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
11723       !getLangOpts().OpenCLCPlusPlus && vType->hasFloatingRepresentation())
11724     return InvalidOperands(Loc, LHS, RHS);
11725   // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
11726   //        usage of the logical operators && and || with vectors in C. This
11727   //        check could be notionally dropped.
11728   if (!getLangOpts().CPlusPlus &&
11729       !(isa<ExtVectorType>(vType->getAs<VectorType>())))
11730     return InvalidLogicalVectorOperands(Loc, LHS, RHS);
11731 
11732   return GetSignedVectorType(LHS.get()->getType());
11733 }
11734 
11735 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
11736                                            SourceLocation Loc,
11737                                            BinaryOperatorKind Opc) {
11738   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11739 
11740   bool IsCompAssign =
11741       Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
11742 
11743   if (LHS.get()->getType()->isVectorType() ||
11744       RHS.get()->getType()->isVectorType()) {
11745     if (LHS.get()->getType()->hasIntegerRepresentation() &&
11746         RHS.get()->getType()->hasIntegerRepresentation())
11747       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
11748                         /*AllowBothBool*/true,
11749                         /*AllowBoolConversions*/getLangOpts().ZVector);
11750     return InvalidOperands(Loc, LHS, RHS);
11751   }
11752 
11753   if (Opc == BO_And)
11754     diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
11755 
11756   if (LHS.get()->getType()->hasFloatingRepresentation() ||
11757       RHS.get()->getType()->hasFloatingRepresentation())
11758     return InvalidOperands(Loc, LHS, RHS);
11759 
11760   ExprResult LHSResult = LHS, RHSResult = RHS;
11761   QualType compType = UsualArithmeticConversions(
11762       LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp);
11763   if (LHSResult.isInvalid() || RHSResult.isInvalid())
11764     return QualType();
11765   LHS = LHSResult.get();
11766   RHS = RHSResult.get();
11767 
11768   if (Opc == BO_Xor)
11769     diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc);
11770 
11771   if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
11772     return compType;
11773   return InvalidOperands(Loc, LHS, RHS);
11774 }
11775 
11776 // C99 6.5.[13,14]
11777 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
11778                                            SourceLocation Loc,
11779                                            BinaryOperatorKind Opc) {
11780   // Check vector operands differently.
11781   if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
11782     return CheckVectorLogicalOperands(LHS, RHS, Loc);
11783 
11784   bool EnumConstantInBoolContext = false;
11785   for (const ExprResult &HS : {LHS, RHS}) {
11786     if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) {
11787       const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl());
11788       if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1)
11789         EnumConstantInBoolContext = true;
11790     }
11791   }
11792 
11793   if (EnumConstantInBoolContext)
11794     Diag(Loc, diag::warn_enum_constant_in_bool_context);
11795 
11796   // Diagnose cases where the user write a logical and/or but probably meant a
11797   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
11798   // is a constant.
11799   if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() &&
11800       !LHS.get()->getType()->isBooleanType() &&
11801       RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
11802       // Don't warn in macros or template instantiations.
11803       !Loc.isMacroID() && !inTemplateInstantiation()) {
11804     // If the RHS can be constant folded, and if it constant folds to something
11805     // that isn't 0 or 1 (which indicate a potential logical operation that
11806     // happened to fold to true/false) then warn.
11807     // Parens on the RHS are ignored.
11808     Expr::EvalResult EVResult;
11809     if (RHS.get()->EvaluateAsInt(EVResult, Context)) {
11810       llvm::APSInt Result = EVResult.Val.getInt();
11811       if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
11812            !RHS.get()->getExprLoc().isMacroID()) ||
11813           (Result != 0 && Result != 1)) {
11814         Diag(Loc, diag::warn_logical_instead_of_bitwise)
11815           << RHS.get()->getSourceRange()
11816           << (Opc == BO_LAnd ? "&&" : "||");
11817         // Suggest replacing the logical operator with the bitwise version
11818         Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
11819             << (Opc == BO_LAnd ? "&" : "|")
11820             << FixItHint::CreateReplacement(SourceRange(
11821                                                  Loc, getLocForEndOfToken(Loc)),
11822                                             Opc == BO_LAnd ? "&" : "|");
11823         if (Opc == BO_LAnd)
11824           // Suggest replacing "Foo() && kNonZero" with "Foo()"
11825           Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
11826               << FixItHint::CreateRemoval(
11827                      SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()),
11828                                  RHS.get()->getEndLoc()));
11829       }
11830     }
11831   }
11832 
11833   if (!Context.getLangOpts().CPlusPlus) {
11834     // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
11835     // not operate on the built-in scalar and vector float types.
11836     if (Context.getLangOpts().OpenCL &&
11837         Context.getLangOpts().OpenCLVersion < 120) {
11838       if (LHS.get()->getType()->isFloatingType() ||
11839           RHS.get()->getType()->isFloatingType())
11840         return InvalidOperands(Loc, LHS, RHS);
11841     }
11842 
11843     LHS = UsualUnaryConversions(LHS.get());
11844     if (LHS.isInvalid())
11845       return QualType();
11846 
11847     RHS = UsualUnaryConversions(RHS.get());
11848     if (RHS.isInvalid())
11849       return QualType();
11850 
11851     if (!LHS.get()->getType()->isScalarType() ||
11852         !RHS.get()->getType()->isScalarType())
11853       return InvalidOperands(Loc, LHS, RHS);
11854 
11855     return Context.IntTy;
11856   }
11857 
11858   // The following is safe because we only use this method for
11859   // non-overloadable operands.
11860 
11861   // C++ [expr.log.and]p1
11862   // C++ [expr.log.or]p1
11863   // The operands are both contextually converted to type bool.
11864   ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
11865   if (LHSRes.isInvalid())
11866     return InvalidOperands(Loc, LHS, RHS);
11867   LHS = LHSRes;
11868 
11869   ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
11870   if (RHSRes.isInvalid())
11871     return InvalidOperands(Loc, LHS, RHS);
11872   RHS = RHSRes;
11873 
11874   // C++ [expr.log.and]p2
11875   // C++ [expr.log.or]p2
11876   // The result is a bool.
11877   return Context.BoolTy;
11878 }
11879 
11880 static bool IsReadonlyMessage(Expr *E, Sema &S) {
11881   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
11882   if (!ME) return false;
11883   if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
11884   ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
11885       ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
11886   if (!Base) return false;
11887   return Base->getMethodDecl() != nullptr;
11888 }
11889 
11890 /// Is the given expression (which must be 'const') a reference to a
11891 /// variable which was originally non-const, but which has become
11892 /// 'const' due to being captured within a block?
11893 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
11894 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
11895   assert(E->isLValue() && E->getType().isConstQualified());
11896   E = E->IgnoreParens();
11897 
11898   // Must be a reference to a declaration from an enclosing scope.
11899   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
11900   if (!DRE) return NCCK_None;
11901   if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
11902 
11903   // The declaration must be a variable which is not declared 'const'.
11904   VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
11905   if (!var) return NCCK_None;
11906   if (var->getType().isConstQualified()) return NCCK_None;
11907   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
11908 
11909   // Decide whether the first capture was for a block or a lambda.
11910   DeclContext *DC = S.CurContext, *Prev = nullptr;
11911   // Decide whether the first capture was for a block or a lambda.
11912   while (DC) {
11913     // For init-capture, it is possible that the variable belongs to the
11914     // template pattern of the current context.
11915     if (auto *FD = dyn_cast<FunctionDecl>(DC))
11916       if (var->isInitCapture() &&
11917           FD->getTemplateInstantiationPattern() == var->getDeclContext())
11918         break;
11919     if (DC == var->getDeclContext())
11920       break;
11921     Prev = DC;
11922     DC = DC->getParent();
11923   }
11924   // Unless we have an init-capture, we've gone one step too far.
11925   if (!var->isInitCapture())
11926     DC = Prev;
11927   return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
11928 }
11929 
11930 static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
11931   Ty = Ty.getNonReferenceType();
11932   if (IsDereference && Ty->isPointerType())
11933     Ty = Ty->getPointeeType();
11934   return !Ty.isConstQualified();
11935 }
11936 
11937 // Update err_typecheck_assign_const and note_typecheck_assign_const
11938 // when this enum is changed.
11939 enum {
11940   ConstFunction,
11941   ConstVariable,
11942   ConstMember,
11943   ConstMethod,
11944   NestedConstMember,
11945   ConstUnknown,  // Keep as last element
11946 };
11947 
11948 /// Emit the "read-only variable not assignable" error and print notes to give
11949 /// more information about why the variable is not assignable, such as pointing
11950 /// to the declaration of a const variable, showing that a method is const, or
11951 /// that the function is returning a const reference.
11952 static void DiagnoseConstAssignment(Sema &S, const Expr *E,
11953                                     SourceLocation Loc) {
11954   SourceRange ExprRange = E->getSourceRange();
11955 
11956   // Only emit one error on the first const found.  All other consts will emit
11957   // a note to the error.
11958   bool DiagnosticEmitted = false;
11959 
11960   // Track if the current expression is the result of a dereference, and if the
11961   // next checked expression is the result of a dereference.
11962   bool IsDereference = false;
11963   bool NextIsDereference = false;
11964 
11965   // Loop to process MemberExpr chains.
11966   while (true) {
11967     IsDereference = NextIsDereference;
11968 
11969     E = E->IgnoreImplicit()->IgnoreParenImpCasts();
11970     if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
11971       NextIsDereference = ME->isArrow();
11972       const ValueDecl *VD = ME->getMemberDecl();
11973       if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
11974         // Mutable fields can be modified even if the class is const.
11975         if (Field->isMutable()) {
11976           assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
11977           break;
11978         }
11979 
11980         if (!IsTypeModifiable(Field->getType(), IsDereference)) {
11981           if (!DiagnosticEmitted) {
11982             S.Diag(Loc, diag::err_typecheck_assign_const)
11983                 << ExprRange << ConstMember << false /*static*/ << Field
11984                 << Field->getType();
11985             DiagnosticEmitted = true;
11986           }
11987           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
11988               << ConstMember << false /*static*/ << Field << Field->getType()
11989               << Field->getSourceRange();
11990         }
11991         E = ME->getBase();
11992         continue;
11993       } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
11994         if (VDecl->getType().isConstQualified()) {
11995           if (!DiagnosticEmitted) {
11996             S.Diag(Loc, diag::err_typecheck_assign_const)
11997                 << ExprRange << ConstMember << true /*static*/ << VDecl
11998                 << VDecl->getType();
11999             DiagnosticEmitted = true;
12000           }
12001           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
12002               << ConstMember << true /*static*/ << VDecl << VDecl->getType()
12003               << VDecl->getSourceRange();
12004         }
12005         // Static fields do not inherit constness from parents.
12006         break;
12007       }
12008       break; // End MemberExpr
12009     } else if (const ArraySubscriptExpr *ASE =
12010                    dyn_cast<ArraySubscriptExpr>(E)) {
12011       E = ASE->getBase()->IgnoreParenImpCasts();
12012       continue;
12013     } else if (const ExtVectorElementExpr *EVE =
12014                    dyn_cast<ExtVectorElementExpr>(E)) {
12015       E = EVE->getBase()->IgnoreParenImpCasts();
12016       continue;
12017     }
12018     break;
12019   }
12020 
12021   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
12022     // Function calls
12023     const FunctionDecl *FD = CE->getDirectCallee();
12024     if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
12025       if (!DiagnosticEmitted) {
12026         S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
12027                                                       << ConstFunction << FD;
12028         DiagnosticEmitted = true;
12029       }
12030       S.Diag(FD->getReturnTypeSourceRange().getBegin(),
12031              diag::note_typecheck_assign_const)
12032           << ConstFunction << FD << FD->getReturnType()
12033           << FD->getReturnTypeSourceRange();
12034     }
12035   } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
12036     // Point to variable declaration.
12037     if (const ValueDecl *VD = DRE->getDecl()) {
12038       if (!IsTypeModifiable(VD->getType(), IsDereference)) {
12039         if (!DiagnosticEmitted) {
12040           S.Diag(Loc, diag::err_typecheck_assign_const)
12041               << ExprRange << ConstVariable << VD << VD->getType();
12042           DiagnosticEmitted = true;
12043         }
12044         S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
12045             << ConstVariable << VD << VD->getType() << VD->getSourceRange();
12046       }
12047     }
12048   } else if (isa<CXXThisExpr>(E)) {
12049     if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
12050       if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
12051         if (MD->isConst()) {
12052           if (!DiagnosticEmitted) {
12053             S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
12054                                                           << ConstMethod << MD;
12055             DiagnosticEmitted = true;
12056           }
12057           S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
12058               << ConstMethod << MD << MD->getSourceRange();
12059         }
12060       }
12061     }
12062   }
12063 
12064   if (DiagnosticEmitted)
12065     return;
12066 
12067   // Can't determine a more specific message, so display the generic error.
12068   S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
12069 }
12070 
12071 enum OriginalExprKind {
12072   OEK_Variable,
12073   OEK_Member,
12074   OEK_LValue
12075 };
12076 
12077 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD,
12078                                          const RecordType *Ty,
12079                                          SourceLocation Loc, SourceRange Range,
12080                                          OriginalExprKind OEK,
12081                                          bool &DiagnosticEmitted) {
12082   std::vector<const RecordType *> RecordTypeList;
12083   RecordTypeList.push_back(Ty);
12084   unsigned NextToCheckIndex = 0;
12085   // We walk the record hierarchy breadth-first to ensure that we print
12086   // diagnostics in field nesting order.
12087   while (RecordTypeList.size() > NextToCheckIndex) {
12088     bool IsNested = NextToCheckIndex > 0;
12089     for (const FieldDecl *Field :
12090          RecordTypeList[NextToCheckIndex]->getDecl()->fields()) {
12091       // First, check every field for constness.
12092       QualType FieldTy = Field->getType();
12093       if (FieldTy.isConstQualified()) {
12094         if (!DiagnosticEmitted) {
12095           S.Diag(Loc, diag::err_typecheck_assign_const)
12096               << Range << NestedConstMember << OEK << VD
12097               << IsNested << Field;
12098           DiagnosticEmitted = true;
12099         }
12100         S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
12101             << NestedConstMember << IsNested << Field
12102             << FieldTy << Field->getSourceRange();
12103       }
12104 
12105       // Then we append it to the list to check next in order.
12106       FieldTy = FieldTy.getCanonicalType();
12107       if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) {
12108         if (llvm::find(RecordTypeList, FieldRecTy) == RecordTypeList.end())
12109           RecordTypeList.push_back(FieldRecTy);
12110       }
12111     }
12112     ++NextToCheckIndex;
12113   }
12114 }
12115 
12116 /// Emit an error for the case where a record we are trying to assign to has a
12117 /// const-qualified field somewhere in its hierarchy.
12118 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
12119                                          SourceLocation Loc) {
12120   QualType Ty = E->getType();
12121   assert(Ty->isRecordType() && "lvalue was not record?");
12122   SourceRange Range = E->getSourceRange();
12123   const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>();
12124   bool DiagEmitted = false;
12125 
12126   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
12127     DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
12128             Range, OEK_Member, DiagEmitted);
12129   else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
12130     DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
12131             Range, OEK_Variable, DiagEmitted);
12132   else
12133     DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
12134             Range, OEK_LValue, DiagEmitted);
12135   if (!DiagEmitted)
12136     DiagnoseConstAssignment(S, E, Loc);
12137 }
12138 
12139 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
12140 /// emit an error and return true.  If so, return false.
12141 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
12142   assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
12143 
12144   S.CheckShadowingDeclModification(E, Loc);
12145 
12146   SourceLocation OrigLoc = Loc;
12147   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
12148                                                               &Loc);
12149   if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
12150     IsLV = Expr::MLV_InvalidMessageExpression;
12151   if (IsLV == Expr::MLV_Valid)
12152     return false;
12153 
12154   unsigned DiagID = 0;
12155   bool NeedType = false;
12156   switch (IsLV) { // C99 6.5.16p2
12157   case Expr::MLV_ConstQualified:
12158     // Use a specialized diagnostic when we're assigning to an object
12159     // from an enclosing function or block.
12160     if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
12161       if (NCCK == NCCK_Block)
12162         DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
12163       else
12164         DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
12165       break;
12166     }
12167 
12168     // In ARC, use some specialized diagnostics for occasions where we
12169     // infer 'const'.  These are always pseudo-strong variables.
12170     if (S.getLangOpts().ObjCAutoRefCount) {
12171       DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
12172       if (declRef && isa<VarDecl>(declRef->getDecl())) {
12173         VarDecl *var = cast<VarDecl>(declRef->getDecl());
12174 
12175         // Use the normal diagnostic if it's pseudo-__strong but the
12176         // user actually wrote 'const'.
12177         if (var->isARCPseudoStrong() &&
12178             (!var->getTypeSourceInfo() ||
12179              !var->getTypeSourceInfo()->getType().isConstQualified())) {
12180           // There are three pseudo-strong cases:
12181           //  - self
12182           ObjCMethodDecl *method = S.getCurMethodDecl();
12183           if (method && var == method->getSelfDecl()) {
12184             DiagID = method->isClassMethod()
12185               ? diag::err_typecheck_arc_assign_self_class_method
12186               : diag::err_typecheck_arc_assign_self;
12187 
12188           //  - Objective-C externally_retained attribute.
12189           } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
12190                      isa<ParmVarDecl>(var)) {
12191             DiagID = diag::err_typecheck_arc_assign_externally_retained;
12192 
12193           //  - fast enumeration variables
12194           } else {
12195             DiagID = diag::err_typecheck_arr_assign_enumeration;
12196           }
12197 
12198           SourceRange Assign;
12199           if (Loc != OrigLoc)
12200             Assign = SourceRange(OrigLoc, OrigLoc);
12201           S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
12202           // We need to preserve the AST regardless, so migration tool
12203           // can do its job.
12204           return false;
12205         }
12206       }
12207     }
12208 
12209     // If none of the special cases above are triggered, then this is a
12210     // simple const assignment.
12211     if (DiagID == 0) {
12212       DiagnoseConstAssignment(S, E, Loc);
12213       return true;
12214     }
12215 
12216     break;
12217   case Expr::MLV_ConstAddrSpace:
12218     DiagnoseConstAssignment(S, E, Loc);
12219     return true;
12220   case Expr::MLV_ConstQualifiedField:
12221     DiagnoseRecursiveConstFields(S, E, Loc);
12222     return true;
12223   case Expr::MLV_ArrayType:
12224   case Expr::MLV_ArrayTemporary:
12225     DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
12226     NeedType = true;
12227     break;
12228   case Expr::MLV_NotObjectType:
12229     DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
12230     NeedType = true;
12231     break;
12232   case Expr::MLV_LValueCast:
12233     DiagID = diag::err_typecheck_lvalue_casts_not_supported;
12234     break;
12235   case Expr::MLV_Valid:
12236     llvm_unreachable("did not take early return for MLV_Valid");
12237   case Expr::MLV_InvalidExpression:
12238   case Expr::MLV_MemberFunction:
12239   case Expr::MLV_ClassTemporary:
12240     DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
12241     break;
12242   case Expr::MLV_IncompleteType:
12243   case Expr::MLV_IncompleteVoidType:
12244     return S.RequireCompleteType(Loc, E->getType(),
12245              diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
12246   case Expr::MLV_DuplicateVectorComponents:
12247     DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
12248     break;
12249   case Expr::MLV_NoSetterProperty:
12250     llvm_unreachable("readonly properties should be processed differently");
12251   case Expr::MLV_InvalidMessageExpression:
12252     DiagID = diag::err_readonly_message_assignment;
12253     break;
12254   case Expr::MLV_SubObjCPropertySetting:
12255     DiagID = diag::err_no_subobject_property_setting;
12256     break;
12257   }
12258 
12259   SourceRange Assign;
12260   if (Loc != OrigLoc)
12261     Assign = SourceRange(OrigLoc, OrigLoc);
12262   if (NeedType)
12263     S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
12264   else
12265     S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
12266   return true;
12267 }
12268 
12269 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
12270                                          SourceLocation Loc,
12271                                          Sema &Sema) {
12272   if (Sema.inTemplateInstantiation())
12273     return;
12274   if (Sema.isUnevaluatedContext())
12275     return;
12276   if (Loc.isInvalid() || Loc.isMacroID())
12277     return;
12278   if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
12279     return;
12280 
12281   // C / C++ fields
12282   MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
12283   MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
12284   if (ML && MR) {
12285     if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
12286       return;
12287     const ValueDecl *LHSDecl =
12288         cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl());
12289     const ValueDecl *RHSDecl =
12290         cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl());
12291     if (LHSDecl != RHSDecl)
12292       return;
12293     if (LHSDecl->getType().isVolatileQualified())
12294       return;
12295     if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
12296       if (RefTy->getPointeeType().isVolatileQualified())
12297         return;
12298 
12299     Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
12300   }
12301 
12302   // Objective-C instance variables
12303   ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
12304   ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
12305   if (OL && OR && OL->getDecl() == OR->getDecl()) {
12306     DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
12307     DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
12308     if (RL && RR && RL->getDecl() == RR->getDecl())
12309       Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
12310   }
12311 }
12312 
12313 // C99 6.5.16.1
12314 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
12315                                        SourceLocation Loc,
12316                                        QualType CompoundType) {
12317   assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
12318 
12319   // Verify that LHS is a modifiable lvalue, and emit error if not.
12320   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
12321     return QualType();
12322 
12323   QualType LHSType = LHSExpr->getType();
12324   QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
12325                                              CompoundType;
12326   // OpenCL v1.2 s6.1.1.1 p2:
12327   // The half data type can only be used to declare a pointer to a buffer that
12328   // contains half values
12329   if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
12330     LHSType->isHalfType()) {
12331     Diag(Loc, diag::err_opencl_half_load_store) << 1
12332         << LHSType.getUnqualifiedType();
12333     return QualType();
12334   }
12335 
12336   AssignConvertType ConvTy;
12337   if (CompoundType.isNull()) {
12338     Expr *RHSCheck = RHS.get();
12339 
12340     CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
12341 
12342     QualType LHSTy(LHSType);
12343     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
12344     if (RHS.isInvalid())
12345       return QualType();
12346     // Special case of NSObject attributes on c-style pointer types.
12347     if (ConvTy == IncompatiblePointer &&
12348         ((Context.isObjCNSObjectType(LHSType) &&
12349           RHSType->isObjCObjectPointerType()) ||
12350          (Context.isObjCNSObjectType(RHSType) &&
12351           LHSType->isObjCObjectPointerType())))
12352       ConvTy = Compatible;
12353 
12354     if (ConvTy == Compatible &&
12355         LHSType->isObjCObjectType())
12356         Diag(Loc, diag::err_objc_object_assignment)
12357           << LHSType;
12358 
12359     // If the RHS is a unary plus or minus, check to see if they = and + are
12360     // right next to each other.  If so, the user may have typo'd "x =+ 4"
12361     // instead of "x += 4".
12362     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
12363       RHSCheck = ICE->getSubExpr();
12364     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
12365       if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
12366           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
12367           // Only if the two operators are exactly adjacent.
12368           Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
12369           // And there is a space or other character before the subexpr of the
12370           // unary +/-.  We don't want to warn on "x=-1".
12371           Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() &&
12372           UO->getSubExpr()->getBeginLoc().isFileID()) {
12373         Diag(Loc, diag::warn_not_compound_assign)
12374           << (UO->getOpcode() == UO_Plus ? "+" : "-")
12375           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
12376       }
12377     }
12378 
12379     if (ConvTy == Compatible) {
12380       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
12381         // Warn about retain cycles where a block captures the LHS, but
12382         // not if the LHS is a simple variable into which the block is
12383         // being stored...unless that variable can be captured by reference!
12384         const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
12385         const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
12386         if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
12387           checkRetainCycles(LHSExpr, RHS.get());
12388       }
12389 
12390       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
12391           LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
12392         // It is safe to assign a weak reference into a strong variable.
12393         // Although this code can still have problems:
12394         //   id x = self.weakProp;
12395         //   id y = self.weakProp;
12396         // we do not warn to warn spuriously when 'x' and 'y' are on separate
12397         // paths through the function. This should be revisited if
12398         // -Wrepeated-use-of-weak is made flow-sensitive.
12399         // For ObjCWeak only, we do not warn if the assign is to a non-weak
12400         // variable, which will be valid for the current autorelease scope.
12401         if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
12402                              RHS.get()->getBeginLoc()))
12403           getCurFunction()->markSafeWeakUse(RHS.get());
12404 
12405       } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
12406         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
12407       }
12408     }
12409   } else {
12410     // Compound assignment "x += y"
12411     ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
12412   }
12413 
12414   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
12415                                RHS.get(), AA_Assigning))
12416     return QualType();
12417 
12418   CheckForNullPointerDereference(*this, LHSExpr);
12419 
12420   if (getLangOpts().CPlusPlus2a && LHSType.isVolatileQualified()) {
12421     if (CompoundType.isNull()) {
12422       // C++2a [expr.ass]p5:
12423       //   A simple-assignment whose left operand is of a volatile-qualified
12424       //   type is deprecated unless the assignment is either a discarded-value
12425       //   expression or an unevaluated operand
12426       ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr);
12427     } else {
12428       // C++2a [expr.ass]p6:
12429       //   [Compound-assignment] expressions are deprecated if E1 has
12430       //   volatile-qualified type
12431       Diag(Loc, diag::warn_deprecated_compound_assign_volatile) << LHSType;
12432     }
12433   }
12434 
12435   // C99 6.5.16p3: The type of an assignment expression is the type of the
12436   // left operand unless the left operand has qualified type, in which case
12437   // it is the unqualified version of the type of the left operand.
12438   // C99 6.5.16.1p2: In simple assignment, the value of the right operand
12439   // is converted to the type of the assignment expression (above).
12440   // C++ 5.17p1: the type of the assignment expression is that of its left
12441   // operand.
12442   return (getLangOpts().CPlusPlus
12443           ? LHSType : LHSType.getUnqualifiedType());
12444 }
12445 
12446 // Only ignore explicit casts to void.
12447 static bool IgnoreCommaOperand(const Expr *E) {
12448   E = E->IgnoreParens();
12449 
12450   if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
12451     if (CE->getCastKind() == CK_ToVoid) {
12452       return true;
12453     }
12454 
12455     // static_cast<void> on a dependent type will not show up as CK_ToVoid.
12456     if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
12457         CE->getSubExpr()->getType()->isDependentType()) {
12458       return true;
12459     }
12460   }
12461 
12462   return false;
12463 }
12464 
12465 // Look for instances where it is likely the comma operator is confused with
12466 // another operator.  There is a whitelist of acceptable expressions for the
12467 // left hand side of the comma operator, otherwise emit a warning.
12468 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
12469   // No warnings in macros
12470   if (Loc.isMacroID())
12471     return;
12472 
12473   // Don't warn in template instantiations.
12474   if (inTemplateInstantiation())
12475     return;
12476 
12477   // Scope isn't fine-grained enough to whitelist the specific cases, so
12478   // instead, skip more than needed, then call back into here with the
12479   // CommaVisitor in SemaStmt.cpp.
12480   // The whitelisted locations are the initialization and increment portions
12481   // of a for loop.  The additional checks are on the condition of
12482   // if statements, do/while loops, and for loops.
12483   // Differences in scope flags for C89 mode requires the extra logic.
12484   const unsigned ForIncrementFlags =
12485       getLangOpts().C99 || getLangOpts().CPlusPlus
12486           ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope
12487           : Scope::ContinueScope | Scope::BreakScope;
12488   const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
12489   const unsigned ScopeFlags = getCurScope()->getFlags();
12490   if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
12491       (ScopeFlags & ForInitFlags) == ForInitFlags)
12492     return;
12493 
12494   // If there are multiple comma operators used together, get the RHS of the
12495   // of the comma operator as the LHS.
12496   while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
12497     if (BO->getOpcode() != BO_Comma)
12498       break;
12499     LHS = BO->getRHS();
12500   }
12501 
12502   // Only allow some expressions on LHS to not warn.
12503   if (IgnoreCommaOperand(LHS))
12504     return;
12505 
12506   Diag(Loc, diag::warn_comma_operator);
12507   Diag(LHS->getBeginLoc(), diag::note_cast_to_void)
12508       << LHS->getSourceRange()
12509       << FixItHint::CreateInsertion(LHS->getBeginLoc(),
12510                                     LangOpts.CPlusPlus ? "static_cast<void>("
12511                                                        : "(void)(")
12512       << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()),
12513                                     ")");
12514 }
12515 
12516 // C99 6.5.17
12517 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
12518                                    SourceLocation Loc) {
12519   LHS = S.CheckPlaceholderExpr(LHS.get());
12520   RHS = S.CheckPlaceholderExpr(RHS.get());
12521   if (LHS.isInvalid() || RHS.isInvalid())
12522     return QualType();
12523 
12524   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
12525   // operands, but not unary promotions.
12526   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
12527 
12528   // So we treat the LHS as a ignored value, and in C++ we allow the
12529   // containing site to determine what should be done with the RHS.
12530   LHS = S.IgnoredValueConversions(LHS.get());
12531   if (LHS.isInvalid())
12532     return QualType();
12533 
12534   S.DiagnoseUnusedExprResult(LHS.get());
12535 
12536   if (!S.getLangOpts().CPlusPlus) {
12537     RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
12538     if (RHS.isInvalid())
12539       return QualType();
12540     if (!RHS.get()->getType()->isVoidType())
12541       S.RequireCompleteType(Loc, RHS.get()->getType(),
12542                             diag::err_incomplete_type);
12543   }
12544 
12545   if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
12546     S.DiagnoseCommaOperator(LHS.get(), Loc);
12547 
12548   return RHS.get()->getType();
12549 }
12550 
12551 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
12552 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
12553 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
12554                                                ExprValueKind &VK,
12555                                                ExprObjectKind &OK,
12556                                                SourceLocation OpLoc,
12557                                                bool IsInc, bool IsPrefix) {
12558   if (Op->isTypeDependent())
12559     return S.Context.DependentTy;
12560 
12561   QualType ResType = Op->getType();
12562   // Atomic types can be used for increment / decrement where the non-atomic
12563   // versions can, so ignore the _Atomic() specifier for the purpose of
12564   // checking.
12565   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
12566     ResType = ResAtomicType->getValueType();
12567 
12568   assert(!ResType.isNull() && "no type for increment/decrement expression");
12569 
12570   if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
12571     // Decrement of bool is not allowed.
12572     if (!IsInc) {
12573       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
12574       return QualType();
12575     }
12576     // Increment of bool sets it to true, but is deprecated.
12577     S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
12578                                               : diag::warn_increment_bool)
12579       << Op->getSourceRange();
12580   } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
12581     // Error on enum increments and decrements in C++ mode
12582     S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
12583     return QualType();
12584   } else if (ResType->isRealType()) {
12585     // OK!
12586   } else if (ResType->isPointerType()) {
12587     // C99 6.5.2.4p2, 6.5.6p2
12588     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
12589       return QualType();
12590   } else if (ResType->isObjCObjectPointerType()) {
12591     // On modern runtimes, ObjC pointer arithmetic is forbidden.
12592     // Otherwise, we just need a complete type.
12593     if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
12594         checkArithmeticOnObjCPointer(S, OpLoc, Op))
12595       return QualType();
12596   } else if (ResType->isAnyComplexType()) {
12597     // C99 does not support ++/-- on complex types, we allow as an extension.
12598     S.Diag(OpLoc, diag::ext_integer_increment_complex)
12599       << ResType << Op->getSourceRange();
12600   } else if (ResType->isPlaceholderType()) {
12601     ExprResult PR = S.CheckPlaceholderExpr(Op);
12602     if (PR.isInvalid()) return QualType();
12603     return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
12604                                           IsInc, IsPrefix);
12605   } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
12606     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
12607   } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
12608              (ResType->castAs<VectorType>()->getVectorKind() !=
12609               VectorType::AltiVecBool)) {
12610     // The z vector extensions allow ++ and -- for non-bool vectors.
12611   } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
12612             ResType->castAs<VectorType>()->getElementType()->isIntegerType()) {
12613     // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
12614   } else {
12615     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
12616       << ResType << int(IsInc) << Op->getSourceRange();
12617     return QualType();
12618   }
12619   // At this point, we know we have a real, complex or pointer type.
12620   // Now make sure the operand is a modifiable lvalue.
12621   if (CheckForModifiableLvalue(Op, OpLoc, S))
12622     return QualType();
12623   if (S.getLangOpts().CPlusPlus2a && ResType.isVolatileQualified()) {
12624     // C++2a [expr.pre.inc]p1, [expr.post.inc]p1:
12625     //   An operand with volatile-qualified type is deprecated
12626     S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile)
12627         << IsInc << ResType;
12628   }
12629   // In C++, a prefix increment is the same type as the operand. Otherwise
12630   // (in C or with postfix), the increment is the unqualified type of the
12631   // operand.
12632   if (IsPrefix && S.getLangOpts().CPlusPlus) {
12633     VK = VK_LValue;
12634     OK = Op->getObjectKind();
12635     return ResType;
12636   } else {
12637     VK = VK_RValue;
12638     return ResType.getUnqualifiedType();
12639   }
12640 }
12641 
12642 
12643 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
12644 /// This routine allows us to typecheck complex/recursive expressions
12645 /// where the declaration is needed for type checking. We only need to
12646 /// handle cases when the expression references a function designator
12647 /// or is an lvalue. Here are some examples:
12648 ///  - &(x) => x
12649 ///  - &*****f => f for f a function designator.
12650 ///  - &s.xx => s
12651 ///  - &s.zz[1].yy -> s, if zz is an array
12652 ///  - *(x + 1) -> x, if x is an array
12653 ///  - &"123"[2] -> 0
12654 ///  - & __real__ x -> x
12655 static ValueDecl *getPrimaryDecl(Expr *E) {
12656   switch (E->getStmtClass()) {
12657   case Stmt::DeclRefExprClass:
12658     return cast<DeclRefExpr>(E)->getDecl();
12659   case Stmt::MemberExprClass:
12660     // If this is an arrow operator, the address is an offset from
12661     // the base's value, so the object the base refers to is
12662     // irrelevant.
12663     if (cast<MemberExpr>(E)->isArrow())
12664       return nullptr;
12665     // Otherwise, the expression refers to a part of the base
12666     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
12667   case Stmt::ArraySubscriptExprClass: {
12668     // FIXME: This code shouldn't be necessary!  We should catch the implicit
12669     // promotion of register arrays earlier.
12670     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
12671     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
12672       if (ICE->getSubExpr()->getType()->isArrayType())
12673         return getPrimaryDecl(ICE->getSubExpr());
12674     }
12675     return nullptr;
12676   }
12677   case Stmt::UnaryOperatorClass: {
12678     UnaryOperator *UO = cast<UnaryOperator>(E);
12679 
12680     switch(UO->getOpcode()) {
12681     case UO_Real:
12682     case UO_Imag:
12683     case UO_Extension:
12684       return getPrimaryDecl(UO->getSubExpr());
12685     default:
12686       return nullptr;
12687     }
12688   }
12689   case Stmt::ParenExprClass:
12690     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
12691   case Stmt::ImplicitCastExprClass:
12692     // If the result of an implicit cast is an l-value, we care about
12693     // the sub-expression; otherwise, the result here doesn't matter.
12694     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
12695   default:
12696     return nullptr;
12697   }
12698 }
12699 
12700 namespace {
12701   enum {
12702     AO_Bit_Field = 0,
12703     AO_Vector_Element = 1,
12704     AO_Property_Expansion = 2,
12705     AO_Register_Variable = 3,
12706     AO_No_Error = 4
12707   };
12708 }
12709 /// Diagnose invalid operand for address of operations.
12710 ///
12711 /// \param Type The type of operand which cannot have its address taken.
12712 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
12713                                          Expr *E, unsigned Type) {
12714   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
12715 }
12716 
12717 /// CheckAddressOfOperand - The operand of & must be either a function
12718 /// designator or an lvalue designating an object. If it is an lvalue, the
12719 /// object cannot be declared with storage class register or be a bit field.
12720 /// Note: The usual conversions are *not* applied to the operand of the &
12721 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
12722 /// In C++, the operand might be an overloaded function name, in which case
12723 /// we allow the '&' but retain the overloaded-function type.
12724 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
12725   if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
12726     if (PTy->getKind() == BuiltinType::Overload) {
12727       Expr *E = OrigOp.get()->IgnoreParens();
12728       if (!isa<OverloadExpr>(E)) {
12729         assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
12730         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
12731           << OrigOp.get()->getSourceRange();
12732         return QualType();
12733       }
12734 
12735       OverloadExpr *Ovl = cast<OverloadExpr>(E);
12736       if (isa<UnresolvedMemberExpr>(Ovl))
12737         if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
12738           Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
12739             << OrigOp.get()->getSourceRange();
12740           return QualType();
12741         }
12742 
12743       return Context.OverloadTy;
12744     }
12745 
12746     if (PTy->getKind() == BuiltinType::UnknownAny)
12747       return Context.UnknownAnyTy;
12748 
12749     if (PTy->getKind() == BuiltinType::BoundMember) {
12750       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
12751         << OrigOp.get()->getSourceRange();
12752       return QualType();
12753     }
12754 
12755     OrigOp = CheckPlaceholderExpr(OrigOp.get());
12756     if (OrigOp.isInvalid()) return QualType();
12757   }
12758 
12759   if (OrigOp.get()->isTypeDependent())
12760     return Context.DependentTy;
12761 
12762   assert(!OrigOp.get()->getType()->isPlaceholderType());
12763 
12764   // Make sure to ignore parentheses in subsequent checks
12765   Expr *op = OrigOp.get()->IgnoreParens();
12766 
12767   // In OpenCL captures for blocks called as lambda functions
12768   // are located in the private address space. Blocks used in
12769   // enqueue_kernel can be located in a different address space
12770   // depending on a vendor implementation. Thus preventing
12771   // taking an address of the capture to avoid invalid AS casts.
12772   if (LangOpts.OpenCL) {
12773     auto* VarRef = dyn_cast<DeclRefExpr>(op);
12774     if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
12775       Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
12776       return QualType();
12777     }
12778   }
12779 
12780   if (getLangOpts().C99) {
12781     // Implement C99-only parts of addressof rules.
12782     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
12783       if (uOp->getOpcode() == UO_Deref)
12784         // Per C99 6.5.3.2, the address of a deref always returns a valid result
12785         // (assuming the deref expression is valid).
12786         return uOp->getSubExpr()->getType();
12787     }
12788     // Technically, there should be a check for array subscript
12789     // expressions here, but the result of one is always an lvalue anyway.
12790   }
12791   ValueDecl *dcl = getPrimaryDecl(op);
12792 
12793   if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
12794     if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
12795                                            op->getBeginLoc()))
12796       return QualType();
12797 
12798   Expr::LValueClassification lval = op->ClassifyLValue(Context);
12799   unsigned AddressOfError = AO_No_Error;
12800 
12801   if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
12802     bool sfinae = (bool)isSFINAEContext();
12803     Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
12804                                   : diag::ext_typecheck_addrof_temporary)
12805       << op->getType() << op->getSourceRange();
12806     if (sfinae)
12807       return QualType();
12808     // Materialize the temporary as an lvalue so that we can take its address.
12809     OrigOp = op =
12810         CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
12811   } else if (isa<ObjCSelectorExpr>(op)) {
12812     return Context.getPointerType(op->getType());
12813   } else if (lval == Expr::LV_MemberFunction) {
12814     // If it's an instance method, make a member pointer.
12815     // The expression must have exactly the form &A::foo.
12816 
12817     // If the underlying expression isn't a decl ref, give up.
12818     if (!isa<DeclRefExpr>(op)) {
12819       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
12820         << OrigOp.get()->getSourceRange();
12821       return QualType();
12822     }
12823     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
12824     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
12825 
12826     // The id-expression was parenthesized.
12827     if (OrigOp.get() != DRE) {
12828       Diag(OpLoc, diag::err_parens_pointer_member_function)
12829         << OrigOp.get()->getSourceRange();
12830 
12831     // The method was named without a qualifier.
12832     } else if (!DRE->getQualifier()) {
12833       if (MD->getParent()->getName().empty())
12834         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
12835           << op->getSourceRange();
12836       else {
12837         SmallString<32> Str;
12838         StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
12839         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
12840           << op->getSourceRange()
12841           << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
12842       }
12843     }
12844 
12845     // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
12846     if (isa<CXXDestructorDecl>(MD))
12847       Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
12848 
12849     QualType MPTy = Context.getMemberPointerType(
12850         op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
12851     // Under the MS ABI, lock down the inheritance model now.
12852     if (Context.getTargetInfo().getCXXABI().isMicrosoft())
12853       (void)isCompleteType(OpLoc, MPTy);
12854     return MPTy;
12855   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
12856     // C99 6.5.3.2p1
12857     // The operand must be either an l-value or a function designator
12858     if (!op->getType()->isFunctionType()) {
12859       // Use a special diagnostic for loads from property references.
12860       if (isa<PseudoObjectExpr>(op)) {
12861         AddressOfError = AO_Property_Expansion;
12862       } else {
12863         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
12864           << op->getType() << op->getSourceRange();
12865         return QualType();
12866       }
12867     }
12868   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
12869     // The operand cannot be a bit-field
12870     AddressOfError = AO_Bit_Field;
12871   } else if (op->getObjectKind() == OK_VectorComponent) {
12872     // The operand cannot be an element of a vector
12873     AddressOfError = AO_Vector_Element;
12874   } else if (dcl) { // C99 6.5.3.2p1
12875     // We have an lvalue with a decl. Make sure the decl is not declared
12876     // with the register storage-class specifier.
12877     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
12878       // in C++ it is not error to take address of a register
12879       // variable (c++03 7.1.1P3)
12880       if (vd->getStorageClass() == SC_Register &&
12881           !getLangOpts().CPlusPlus) {
12882         AddressOfError = AO_Register_Variable;
12883       }
12884     } else if (isa<MSPropertyDecl>(dcl)) {
12885       AddressOfError = AO_Property_Expansion;
12886     } else if (isa<FunctionTemplateDecl>(dcl)) {
12887       return Context.OverloadTy;
12888     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
12889       // Okay: we can take the address of a field.
12890       // Could be a pointer to member, though, if there is an explicit
12891       // scope qualifier for the class.
12892       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
12893         DeclContext *Ctx = dcl->getDeclContext();
12894         if (Ctx && Ctx->isRecord()) {
12895           if (dcl->getType()->isReferenceType()) {
12896             Diag(OpLoc,
12897                  diag::err_cannot_form_pointer_to_member_of_reference_type)
12898               << dcl->getDeclName() << dcl->getType();
12899             return QualType();
12900           }
12901 
12902           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
12903             Ctx = Ctx->getParent();
12904 
12905           QualType MPTy = Context.getMemberPointerType(
12906               op->getType(),
12907               Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
12908           // Under the MS ABI, lock down the inheritance model now.
12909           if (Context.getTargetInfo().getCXXABI().isMicrosoft())
12910             (void)isCompleteType(OpLoc, MPTy);
12911           return MPTy;
12912         }
12913       }
12914     } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) &&
12915                !isa<BindingDecl>(dcl))
12916       llvm_unreachable("Unknown/unexpected decl type");
12917   }
12918 
12919   if (AddressOfError != AO_No_Error) {
12920     diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
12921     return QualType();
12922   }
12923 
12924   if (lval == Expr::LV_IncompleteVoidType) {
12925     // Taking the address of a void variable is technically illegal, but we
12926     // allow it in cases which are otherwise valid.
12927     // Example: "extern void x; void* y = &x;".
12928     Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
12929   }
12930 
12931   // If the operand has type "type", the result has type "pointer to type".
12932   if (op->getType()->isObjCObjectType())
12933     return Context.getObjCObjectPointerType(op->getType());
12934 
12935   CheckAddressOfPackedMember(op);
12936 
12937   return Context.getPointerType(op->getType());
12938 }
12939 
12940 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
12941   const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
12942   if (!DRE)
12943     return;
12944   const Decl *D = DRE->getDecl();
12945   if (!D)
12946     return;
12947   const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
12948   if (!Param)
12949     return;
12950   if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
12951     if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
12952       return;
12953   if (FunctionScopeInfo *FD = S.getCurFunction())
12954     if (!FD->ModifiedNonNullParams.count(Param))
12955       FD->ModifiedNonNullParams.insert(Param);
12956 }
12957 
12958 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
12959 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
12960                                         SourceLocation OpLoc) {
12961   if (Op->isTypeDependent())
12962     return S.Context.DependentTy;
12963 
12964   ExprResult ConvResult = S.UsualUnaryConversions(Op);
12965   if (ConvResult.isInvalid())
12966     return QualType();
12967   Op = ConvResult.get();
12968   QualType OpTy = Op->getType();
12969   QualType Result;
12970 
12971   if (isa<CXXReinterpretCastExpr>(Op)) {
12972     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
12973     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
12974                                      Op->getSourceRange());
12975   }
12976 
12977   if (const PointerType *PT = OpTy->getAs<PointerType>())
12978   {
12979     Result = PT->getPointeeType();
12980   }
12981   else if (const ObjCObjectPointerType *OPT =
12982              OpTy->getAs<ObjCObjectPointerType>())
12983     Result = OPT->getPointeeType();
12984   else {
12985     ExprResult PR = S.CheckPlaceholderExpr(Op);
12986     if (PR.isInvalid()) return QualType();
12987     if (PR.get() != Op)
12988       return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
12989   }
12990 
12991   if (Result.isNull()) {
12992     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
12993       << OpTy << Op->getSourceRange();
12994     return QualType();
12995   }
12996 
12997   // Note that per both C89 and C99, indirection is always legal, even if Result
12998   // is an incomplete type or void.  It would be possible to warn about
12999   // dereferencing a void pointer, but it's completely well-defined, and such a
13000   // warning is unlikely to catch any mistakes. In C++, indirection is not valid
13001   // for pointers to 'void' but is fine for any other pointer type:
13002   //
13003   // C++ [expr.unary.op]p1:
13004   //   [...] the expression to which [the unary * operator] is applied shall
13005   //   be a pointer to an object type, or a pointer to a function type
13006   if (S.getLangOpts().CPlusPlus && Result->isVoidType())
13007     S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
13008       << OpTy << Op->getSourceRange();
13009 
13010   // Dereferences are usually l-values...
13011   VK = VK_LValue;
13012 
13013   // ...except that certain expressions are never l-values in C.
13014   if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
13015     VK = VK_RValue;
13016 
13017   return Result;
13018 }
13019 
13020 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
13021   BinaryOperatorKind Opc;
13022   switch (Kind) {
13023   default: llvm_unreachable("Unknown binop!");
13024   case tok::periodstar:           Opc = BO_PtrMemD; break;
13025   case tok::arrowstar:            Opc = BO_PtrMemI; break;
13026   case tok::star:                 Opc = BO_Mul; break;
13027   case tok::slash:                Opc = BO_Div; break;
13028   case tok::percent:              Opc = BO_Rem; break;
13029   case tok::plus:                 Opc = BO_Add; break;
13030   case tok::minus:                Opc = BO_Sub; break;
13031   case tok::lessless:             Opc = BO_Shl; break;
13032   case tok::greatergreater:       Opc = BO_Shr; break;
13033   case tok::lessequal:            Opc = BO_LE; break;
13034   case tok::less:                 Opc = BO_LT; break;
13035   case tok::greaterequal:         Opc = BO_GE; break;
13036   case tok::greater:              Opc = BO_GT; break;
13037   case tok::exclaimequal:         Opc = BO_NE; break;
13038   case tok::equalequal:           Opc = BO_EQ; break;
13039   case tok::spaceship:            Opc = BO_Cmp; break;
13040   case tok::amp:                  Opc = BO_And; break;
13041   case tok::caret:                Opc = BO_Xor; break;
13042   case tok::pipe:                 Opc = BO_Or; break;
13043   case tok::ampamp:               Opc = BO_LAnd; break;
13044   case tok::pipepipe:             Opc = BO_LOr; break;
13045   case tok::equal:                Opc = BO_Assign; break;
13046   case tok::starequal:            Opc = BO_MulAssign; break;
13047   case tok::slashequal:           Opc = BO_DivAssign; break;
13048   case tok::percentequal:         Opc = BO_RemAssign; break;
13049   case tok::plusequal:            Opc = BO_AddAssign; break;
13050   case tok::minusequal:           Opc = BO_SubAssign; break;
13051   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
13052   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
13053   case tok::ampequal:             Opc = BO_AndAssign; break;
13054   case tok::caretequal:           Opc = BO_XorAssign; break;
13055   case tok::pipeequal:            Opc = BO_OrAssign; break;
13056   case tok::comma:                Opc = BO_Comma; break;
13057   }
13058   return Opc;
13059 }
13060 
13061 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
13062   tok::TokenKind Kind) {
13063   UnaryOperatorKind Opc;
13064   switch (Kind) {
13065   default: llvm_unreachable("Unknown unary op!");
13066   case tok::plusplus:     Opc = UO_PreInc; break;
13067   case tok::minusminus:   Opc = UO_PreDec; break;
13068   case tok::amp:          Opc = UO_AddrOf; break;
13069   case tok::star:         Opc = UO_Deref; break;
13070   case tok::plus:         Opc = UO_Plus; break;
13071   case tok::minus:        Opc = UO_Minus; break;
13072   case tok::tilde:        Opc = UO_Not; break;
13073   case tok::exclaim:      Opc = UO_LNot; break;
13074   case tok::kw___real:    Opc = UO_Real; break;
13075   case tok::kw___imag:    Opc = UO_Imag; break;
13076   case tok::kw___extension__: Opc = UO_Extension; break;
13077   }
13078   return Opc;
13079 }
13080 
13081 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
13082 /// This warning suppressed in the event of macro expansions.
13083 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
13084                                    SourceLocation OpLoc, bool IsBuiltin) {
13085   if (S.inTemplateInstantiation())
13086     return;
13087   if (S.isUnevaluatedContext())
13088     return;
13089   if (OpLoc.isInvalid() || OpLoc.isMacroID())
13090     return;
13091   LHSExpr = LHSExpr->IgnoreParenImpCasts();
13092   RHSExpr = RHSExpr->IgnoreParenImpCasts();
13093   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
13094   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
13095   if (!LHSDeclRef || !RHSDeclRef ||
13096       LHSDeclRef->getLocation().isMacroID() ||
13097       RHSDeclRef->getLocation().isMacroID())
13098     return;
13099   const ValueDecl *LHSDecl =
13100     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
13101   const ValueDecl *RHSDecl =
13102     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
13103   if (LHSDecl != RHSDecl)
13104     return;
13105   if (LHSDecl->getType().isVolatileQualified())
13106     return;
13107   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
13108     if (RefTy->getPointeeType().isVolatileQualified())
13109       return;
13110 
13111   S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
13112                           : diag::warn_self_assignment_overloaded)
13113       << LHSDeclRef->getType() << LHSExpr->getSourceRange()
13114       << RHSExpr->getSourceRange();
13115 }
13116 
13117 /// Check if a bitwise-& is performed on an Objective-C pointer.  This
13118 /// is usually indicative of introspection within the Objective-C pointer.
13119 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
13120                                           SourceLocation OpLoc) {
13121   if (!S.getLangOpts().ObjC)
13122     return;
13123 
13124   const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
13125   const Expr *LHS = L.get();
13126   const Expr *RHS = R.get();
13127 
13128   if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
13129     ObjCPointerExpr = LHS;
13130     OtherExpr = RHS;
13131   }
13132   else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
13133     ObjCPointerExpr = RHS;
13134     OtherExpr = LHS;
13135   }
13136 
13137   // This warning is deliberately made very specific to reduce false
13138   // positives with logic that uses '&' for hashing.  This logic mainly
13139   // looks for code trying to introspect into tagged pointers, which
13140   // code should generally never do.
13141   if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
13142     unsigned Diag = diag::warn_objc_pointer_masking;
13143     // Determine if we are introspecting the result of performSelectorXXX.
13144     const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
13145     // Special case messages to -performSelector and friends, which
13146     // can return non-pointer values boxed in a pointer value.
13147     // Some clients may wish to silence warnings in this subcase.
13148     if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
13149       Selector S = ME->getSelector();
13150       StringRef SelArg0 = S.getNameForSlot(0);
13151       if (SelArg0.startswith("performSelector"))
13152         Diag = diag::warn_objc_pointer_masking_performSelector;
13153     }
13154 
13155     S.Diag(OpLoc, Diag)
13156       << ObjCPointerExpr->getSourceRange();
13157   }
13158 }
13159 
13160 static NamedDecl *getDeclFromExpr(Expr *E) {
13161   if (!E)
13162     return nullptr;
13163   if (auto *DRE = dyn_cast<DeclRefExpr>(E))
13164     return DRE->getDecl();
13165   if (auto *ME = dyn_cast<MemberExpr>(E))
13166     return ME->getMemberDecl();
13167   if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
13168     return IRE->getDecl();
13169   return nullptr;
13170 }
13171 
13172 // This helper function promotes a binary operator's operands (which are of a
13173 // half vector type) to a vector of floats and then truncates the result to
13174 // a vector of either half or short.
13175 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS,
13176                                       BinaryOperatorKind Opc, QualType ResultTy,
13177                                       ExprValueKind VK, ExprObjectKind OK,
13178                                       bool IsCompAssign, SourceLocation OpLoc,
13179                                       FPOptions FPFeatures) {
13180   auto &Context = S.getASTContext();
13181   assert((isVector(ResultTy, Context.HalfTy) ||
13182           isVector(ResultTy, Context.ShortTy)) &&
13183          "Result must be a vector of half or short");
13184   assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
13185          isVector(RHS.get()->getType(), Context.HalfTy) &&
13186          "both operands expected to be a half vector");
13187 
13188   RHS = convertVector(RHS.get(), Context.FloatTy, S);
13189   QualType BinOpResTy = RHS.get()->getType();
13190 
13191   // If Opc is a comparison, ResultType is a vector of shorts. In that case,
13192   // change BinOpResTy to a vector of ints.
13193   if (isVector(ResultTy, Context.ShortTy))
13194     BinOpResTy = S.GetSignedVectorType(BinOpResTy);
13195 
13196   if (IsCompAssign)
13197     return new (Context) CompoundAssignOperator(
13198         LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, BinOpResTy, BinOpResTy,
13199         OpLoc, FPFeatures);
13200 
13201   LHS = convertVector(LHS.get(), Context.FloatTy, S);
13202   auto *BO = new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, BinOpResTy,
13203                                           VK, OK, OpLoc, FPFeatures);
13204   return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S);
13205 }
13206 
13207 static std::pair<ExprResult, ExprResult>
13208 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr,
13209                            Expr *RHSExpr) {
13210   ExprResult LHS = LHSExpr, RHS = RHSExpr;
13211   if (!S.getLangOpts().CPlusPlus) {
13212     // C cannot handle TypoExpr nodes on either side of a binop because it
13213     // doesn't handle dependent types properly, so make sure any TypoExprs have
13214     // been dealt with before checking the operands.
13215     LHS = S.CorrectDelayedTyposInExpr(LHS);
13216     RHS = S.CorrectDelayedTyposInExpr(RHS, [Opc, LHS](Expr *E) {
13217       if (Opc != BO_Assign)
13218         return ExprResult(E);
13219       // Avoid correcting the RHS to the same Expr as the LHS.
13220       Decl *D = getDeclFromExpr(E);
13221       return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
13222     });
13223   }
13224   return std::make_pair(LHS, RHS);
13225 }
13226 
13227 /// Returns true if conversion between vectors of halfs and vectors of floats
13228 /// is needed.
13229 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
13230                                      Expr *E0, Expr *E1 = nullptr) {
13231   if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType ||
13232       Ctx.getTargetInfo().useFP16ConversionIntrinsics())
13233     return false;
13234 
13235   auto HasVectorOfHalfType = [&Ctx](Expr *E) {
13236     QualType Ty = E->IgnoreImplicit()->getType();
13237 
13238     // Don't promote half precision neon vectors like float16x4_t in arm_neon.h
13239     // to vectors of floats. Although the element type of the vectors is __fp16,
13240     // the vectors shouldn't be treated as storage-only types. See the
13241     // discussion here: https://reviews.llvm.org/rG825235c140e7
13242     if (const VectorType *VT = Ty->getAs<VectorType>()) {
13243       if (VT->getVectorKind() == VectorType::NeonVector)
13244         return false;
13245       return VT->getElementType().getCanonicalType() == Ctx.HalfTy;
13246     }
13247     return false;
13248   };
13249 
13250   return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1));
13251 }
13252 
13253 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
13254 /// operator @p Opc at location @c TokLoc. This routine only supports
13255 /// built-in operations; ActOnBinOp handles overloaded operators.
13256 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
13257                                     BinaryOperatorKind Opc,
13258                                     Expr *LHSExpr, Expr *RHSExpr) {
13259   if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
13260     // The syntax only allows initializer lists on the RHS of assignment,
13261     // so we don't need to worry about accepting invalid code for
13262     // non-assignment operators.
13263     // C++11 5.17p9:
13264     //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
13265     //   of x = {} is x = T().
13266     InitializationKind Kind = InitializationKind::CreateDirectList(
13267         RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
13268     InitializedEntity Entity =
13269         InitializedEntity::InitializeTemporary(LHSExpr->getType());
13270     InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
13271     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
13272     if (Init.isInvalid())
13273       return Init;
13274     RHSExpr = Init.get();
13275   }
13276 
13277   ExprResult LHS = LHSExpr, RHS = RHSExpr;
13278   QualType ResultTy;     // Result type of the binary operator.
13279   // The following two variables are used for compound assignment operators
13280   QualType CompLHSTy;    // Type of LHS after promotions for computation
13281   QualType CompResultTy; // Type of computation result
13282   ExprValueKind VK = VK_RValue;
13283   ExprObjectKind OK = OK_Ordinary;
13284   bool ConvertHalfVec = false;
13285 
13286   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
13287   if (!LHS.isUsable() || !RHS.isUsable())
13288     return ExprError();
13289 
13290   if (getLangOpts().OpenCL) {
13291     QualType LHSTy = LHSExpr->getType();
13292     QualType RHSTy = RHSExpr->getType();
13293     // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
13294     // the ATOMIC_VAR_INIT macro.
13295     if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
13296       SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
13297       if (BO_Assign == Opc)
13298         Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
13299       else
13300         ResultTy = InvalidOperands(OpLoc, LHS, RHS);
13301       return ExprError();
13302     }
13303 
13304     // OpenCL special types - image, sampler, pipe, and blocks are to be used
13305     // only with a builtin functions and therefore should be disallowed here.
13306     if (LHSTy->isImageType() || RHSTy->isImageType() ||
13307         LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
13308         LHSTy->isPipeType() || RHSTy->isPipeType() ||
13309         LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
13310       ResultTy = InvalidOperands(OpLoc, LHS, RHS);
13311       return ExprError();
13312     }
13313   }
13314 
13315   // Diagnose operations on the unsupported types for OpenMP device compilation.
13316   if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) {
13317     if (Opc != BO_Assign && Opc != BO_Comma) {
13318       checkOpenMPDeviceExpr(LHSExpr);
13319       checkOpenMPDeviceExpr(RHSExpr);
13320     }
13321   }
13322 
13323   switch (Opc) {
13324   case BO_Assign:
13325     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
13326     if (getLangOpts().CPlusPlus &&
13327         LHS.get()->getObjectKind() != OK_ObjCProperty) {
13328       VK = LHS.get()->getValueKind();
13329       OK = LHS.get()->getObjectKind();
13330     }
13331     if (!ResultTy.isNull()) {
13332       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
13333       DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
13334 
13335       // Avoid copying a block to the heap if the block is assigned to a local
13336       // auto variable that is declared in the same scope as the block. This
13337       // optimization is unsafe if the local variable is declared in an outer
13338       // scope. For example:
13339       //
13340       // BlockTy b;
13341       // {
13342       //   b = ^{...};
13343       // }
13344       // // It is unsafe to invoke the block here if it wasn't copied to the
13345       // // heap.
13346       // b();
13347 
13348       if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens()))
13349         if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
13350           if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
13351             if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD))
13352               BE->getBlockDecl()->setCanAvoidCopyToHeap();
13353 
13354       if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion())
13355         checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(),
13356                               NTCUC_Assignment, NTCUK_Copy);
13357     }
13358     RecordModifiableNonNullParam(*this, LHS.get());
13359     break;
13360   case BO_PtrMemD:
13361   case BO_PtrMemI:
13362     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
13363                                             Opc == BO_PtrMemI);
13364     break;
13365   case BO_Mul:
13366   case BO_Div:
13367     ConvertHalfVec = true;
13368     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
13369                                            Opc == BO_Div);
13370     break;
13371   case BO_Rem:
13372     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
13373     break;
13374   case BO_Add:
13375     ConvertHalfVec = true;
13376     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
13377     break;
13378   case BO_Sub:
13379     ConvertHalfVec = true;
13380     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
13381     break;
13382   case BO_Shl:
13383   case BO_Shr:
13384     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
13385     break;
13386   case BO_LE:
13387   case BO_LT:
13388   case BO_GE:
13389   case BO_GT:
13390     ConvertHalfVec = true;
13391     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
13392     break;
13393   case BO_EQ:
13394   case BO_NE:
13395     ConvertHalfVec = true;
13396     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
13397     break;
13398   case BO_Cmp:
13399     ConvertHalfVec = true;
13400     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
13401     assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
13402     break;
13403   case BO_And:
13404     checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
13405     LLVM_FALLTHROUGH;
13406   case BO_Xor:
13407   case BO_Or:
13408     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
13409     break;
13410   case BO_LAnd:
13411   case BO_LOr:
13412     ConvertHalfVec = true;
13413     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
13414     break;
13415   case BO_MulAssign:
13416   case BO_DivAssign:
13417     ConvertHalfVec = true;
13418     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
13419                                                Opc == BO_DivAssign);
13420     CompLHSTy = CompResultTy;
13421     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13422       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13423     break;
13424   case BO_RemAssign:
13425     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
13426     CompLHSTy = CompResultTy;
13427     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13428       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13429     break;
13430   case BO_AddAssign:
13431     ConvertHalfVec = true;
13432     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
13433     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13434       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13435     break;
13436   case BO_SubAssign:
13437     ConvertHalfVec = true;
13438     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
13439     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13440       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13441     break;
13442   case BO_ShlAssign:
13443   case BO_ShrAssign:
13444     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
13445     CompLHSTy = CompResultTy;
13446     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13447       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13448     break;
13449   case BO_AndAssign:
13450   case BO_OrAssign: // fallthrough
13451     DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
13452     LLVM_FALLTHROUGH;
13453   case BO_XorAssign:
13454     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
13455     CompLHSTy = CompResultTy;
13456     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13457       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13458     break;
13459   case BO_Comma:
13460     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
13461     if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
13462       VK = RHS.get()->getValueKind();
13463       OK = RHS.get()->getObjectKind();
13464     }
13465     break;
13466   }
13467   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
13468     return ExprError();
13469 
13470   if (ResultTy->isRealFloatingType() &&
13471       (getLangOpts().getFPRoundingMode() != LangOptions::FPR_ToNearest ||
13472        getLangOpts().getFPExceptionMode() != LangOptions::FPE_Ignore))
13473     // Mark the current function as usng floating point constrained intrinsics
13474     if (FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
13475       F->setUsesFPIntrin(true);
13476     }
13477 
13478   // Some of the binary operations require promoting operands of half vector to
13479   // float vectors and truncating the result back to half vector. For now, we do
13480   // this only when HalfArgsAndReturn is set (that is, when the target is arm or
13481   // arm64).
13482   assert(isVector(RHS.get()->getType(), Context.HalfTy) ==
13483          isVector(LHS.get()->getType(), Context.HalfTy) &&
13484          "both sides are half vectors or neither sides are");
13485   ConvertHalfVec =
13486       needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get());
13487 
13488   // Check for array bounds violations for both sides of the BinaryOperator
13489   CheckArrayAccess(LHS.get());
13490   CheckArrayAccess(RHS.get());
13491 
13492   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
13493     NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
13494                                                  &Context.Idents.get("object_setClass"),
13495                                                  SourceLocation(), LookupOrdinaryName);
13496     if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
13497       SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc());
13498       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign)
13499           << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(),
13500                                         "object_setClass(")
13501           << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc),
13502                                           ",")
13503           << FixItHint::CreateInsertion(RHSLocEnd, ")");
13504     }
13505     else
13506       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
13507   }
13508   else if (const ObjCIvarRefExpr *OIRE =
13509            dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
13510     DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
13511 
13512   // Opc is not a compound assignment if CompResultTy is null.
13513   if (CompResultTy.isNull()) {
13514     if (ConvertHalfVec)
13515       return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
13516                                  OpLoc, FPFeatures);
13517     return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK,
13518                                         OK, OpLoc, FPFeatures);
13519   }
13520 
13521   // Handle compound assignments.
13522   if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
13523       OK_ObjCProperty) {
13524     VK = VK_LValue;
13525     OK = LHS.get()->getObjectKind();
13526   }
13527 
13528   if (ConvertHalfVec)
13529     return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
13530                                OpLoc, FPFeatures);
13531 
13532   return new (Context) CompoundAssignOperator(
13533       LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy,
13534       OpLoc, FPFeatures);
13535 }
13536 
13537 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
13538 /// operators are mixed in a way that suggests that the programmer forgot that
13539 /// comparison operators have higher precedence. The most typical example of
13540 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
13541 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
13542                                       SourceLocation OpLoc, Expr *LHSExpr,
13543                                       Expr *RHSExpr) {
13544   BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
13545   BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
13546 
13547   // Check that one of the sides is a comparison operator and the other isn't.
13548   bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
13549   bool isRightComp = RHSBO && RHSBO->isComparisonOp();
13550   if (isLeftComp == isRightComp)
13551     return;
13552 
13553   // Bitwise operations are sometimes used as eager logical ops.
13554   // Don't diagnose this.
13555   bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
13556   bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
13557   if (isLeftBitwise || isRightBitwise)
13558     return;
13559 
13560   SourceRange DiagRange = isLeftComp
13561                               ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
13562                               : SourceRange(OpLoc, RHSExpr->getEndLoc());
13563   StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
13564   SourceRange ParensRange =
13565       isLeftComp
13566           ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
13567           : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
13568 
13569   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
13570     << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
13571   SuggestParentheses(Self, OpLoc,
13572     Self.PDiag(diag::note_precedence_silence) << OpStr,
13573     (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
13574   SuggestParentheses(Self, OpLoc,
13575     Self.PDiag(diag::note_precedence_bitwise_first)
13576       << BinaryOperator::getOpcodeStr(Opc),
13577     ParensRange);
13578 }
13579 
13580 /// It accepts a '&&' expr that is inside a '||' one.
13581 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
13582 /// in parentheses.
13583 static void
13584 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
13585                                        BinaryOperator *Bop) {
13586   assert(Bop->getOpcode() == BO_LAnd);
13587   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
13588       << Bop->getSourceRange() << OpLoc;
13589   SuggestParentheses(Self, Bop->getOperatorLoc(),
13590     Self.PDiag(diag::note_precedence_silence)
13591       << Bop->getOpcodeStr(),
13592     Bop->getSourceRange());
13593 }
13594 
13595 /// Returns true if the given expression can be evaluated as a constant
13596 /// 'true'.
13597 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
13598   bool Res;
13599   return !E->isValueDependent() &&
13600          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
13601 }
13602 
13603 /// Returns true if the given expression can be evaluated as a constant
13604 /// 'false'.
13605 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
13606   bool Res;
13607   return !E->isValueDependent() &&
13608          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
13609 }
13610 
13611 /// Look for '&&' in the left hand of a '||' expr.
13612 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
13613                                              Expr *LHSExpr, Expr *RHSExpr) {
13614   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
13615     if (Bop->getOpcode() == BO_LAnd) {
13616       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
13617       if (EvaluatesAsFalse(S, RHSExpr))
13618         return;
13619       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
13620       if (!EvaluatesAsTrue(S, Bop->getLHS()))
13621         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
13622     } else if (Bop->getOpcode() == BO_LOr) {
13623       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
13624         // If it's "a || b && 1 || c" we didn't warn earlier for
13625         // "a || b && 1", but warn now.
13626         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
13627           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
13628       }
13629     }
13630   }
13631 }
13632 
13633 /// Look for '&&' in the right hand of a '||' expr.
13634 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
13635                                              Expr *LHSExpr, Expr *RHSExpr) {
13636   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
13637     if (Bop->getOpcode() == BO_LAnd) {
13638       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
13639       if (EvaluatesAsFalse(S, LHSExpr))
13640         return;
13641       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
13642       if (!EvaluatesAsTrue(S, Bop->getRHS()))
13643         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
13644     }
13645   }
13646 }
13647 
13648 /// Look for bitwise op in the left or right hand of a bitwise op with
13649 /// lower precedence and emit a diagnostic together with a fixit hint that wraps
13650 /// the '&' expression in parentheses.
13651 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
13652                                          SourceLocation OpLoc, Expr *SubExpr) {
13653   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
13654     if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
13655       S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
13656         << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
13657         << Bop->getSourceRange() << OpLoc;
13658       SuggestParentheses(S, Bop->getOperatorLoc(),
13659         S.PDiag(diag::note_precedence_silence)
13660           << Bop->getOpcodeStr(),
13661         Bop->getSourceRange());
13662     }
13663   }
13664 }
13665 
13666 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
13667                                     Expr *SubExpr, StringRef Shift) {
13668   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
13669     if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
13670       StringRef Op = Bop->getOpcodeStr();
13671       S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
13672           << Bop->getSourceRange() << OpLoc << Shift << Op;
13673       SuggestParentheses(S, Bop->getOperatorLoc(),
13674           S.PDiag(diag::note_precedence_silence) << Op,
13675           Bop->getSourceRange());
13676     }
13677   }
13678 }
13679 
13680 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
13681                                  Expr *LHSExpr, Expr *RHSExpr) {
13682   CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
13683   if (!OCE)
13684     return;
13685 
13686   FunctionDecl *FD = OCE->getDirectCallee();
13687   if (!FD || !FD->isOverloadedOperator())
13688     return;
13689 
13690   OverloadedOperatorKind Kind = FD->getOverloadedOperator();
13691   if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
13692     return;
13693 
13694   S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
13695       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
13696       << (Kind == OO_LessLess);
13697   SuggestParentheses(S, OCE->getOperatorLoc(),
13698                      S.PDiag(diag::note_precedence_silence)
13699                          << (Kind == OO_LessLess ? "<<" : ">>"),
13700                      OCE->getSourceRange());
13701   SuggestParentheses(
13702       S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first),
13703       SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc()));
13704 }
13705 
13706 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
13707 /// precedence.
13708 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
13709                                     SourceLocation OpLoc, Expr *LHSExpr,
13710                                     Expr *RHSExpr){
13711   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
13712   if (BinaryOperator::isBitwiseOp(Opc))
13713     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
13714 
13715   // Diagnose "arg1 & arg2 | arg3"
13716   if ((Opc == BO_Or || Opc == BO_Xor) &&
13717       !OpLoc.isMacroID()/* Don't warn in macros. */) {
13718     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
13719     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
13720   }
13721 
13722   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
13723   // We don't warn for 'assert(a || b && "bad")' since this is safe.
13724   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
13725     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
13726     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
13727   }
13728 
13729   if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
13730       || Opc == BO_Shr) {
13731     StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
13732     DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
13733     DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
13734   }
13735 
13736   // Warn on overloaded shift operators and comparisons, such as:
13737   // cout << 5 == 4;
13738   if (BinaryOperator::isComparisonOp(Opc))
13739     DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
13740 }
13741 
13742 // Binary Operators.  'Tok' is the token for the operator.
13743 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
13744                             tok::TokenKind Kind,
13745                             Expr *LHSExpr, Expr *RHSExpr) {
13746   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
13747   assert(LHSExpr && "ActOnBinOp(): missing left expression");
13748   assert(RHSExpr && "ActOnBinOp(): missing right expression");
13749 
13750   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
13751   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
13752 
13753   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
13754 }
13755 
13756 /// Build an overloaded binary operator expression in the given scope.
13757 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
13758                                        BinaryOperatorKind Opc,
13759                                        Expr *LHS, Expr *RHS) {
13760   switch (Opc) {
13761   case BO_Assign:
13762   case BO_DivAssign:
13763   case BO_RemAssign:
13764   case BO_SubAssign:
13765   case BO_AndAssign:
13766   case BO_OrAssign:
13767   case BO_XorAssign:
13768     DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
13769     CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
13770     break;
13771   default:
13772     break;
13773   }
13774 
13775   // Find all of the overloaded operators visible from this
13776   // point. We perform both an operator-name lookup from the local
13777   // scope and an argument-dependent lookup based on the types of
13778   // the arguments.
13779   UnresolvedSet<16> Functions;
13780   OverloadedOperatorKind OverOp
13781     = BinaryOperator::getOverloadedOperator(Opc);
13782   if (Sc && OverOp != OO_None && OverOp != OO_Equal)
13783     S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
13784                                    RHS->getType(), Functions);
13785 
13786   // In C++20 onwards, we may have a second operator to look up.
13787   if (S.getLangOpts().CPlusPlus2a) {
13788     if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp))
13789       S.LookupOverloadedOperatorName(ExtraOp, Sc, LHS->getType(),
13790                                      RHS->getType(), Functions);
13791   }
13792 
13793   // Build the (potentially-overloaded, potentially-dependent)
13794   // binary operation.
13795   return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
13796 }
13797 
13798 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
13799                             BinaryOperatorKind Opc,
13800                             Expr *LHSExpr, Expr *RHSExpr) {
13801   ExprResult LHS, RHS;
13802   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
13803   if (!LHS.isUsable() || !RHS.isUsable())
13804     return ExprError();
13805   LHSExpr = LHS.get();
13806   RHSExpr = RHS.get();
13807 
13808   // We want to end up calling one of checkPseudoObjectAssignment
13809   // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
13810   // both expressions are overloadable or either is type-dependent),
13811   // or CreateBuiltinBinOp (in any other case).  We also want to get
13812   // any placeholder types out of the way.
13813 
13814   // Handle pseudo-objects in the LHS.
13815   if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
13816     // Assignments with a pseudo-object l-value need special analysis.
13817     if (pty->getKind() == BuiltinType::PseudoObject &&
13818         BinaryOperator::isAssignmentOp(Opc))
13819       return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
13820 
13821     // Don't resolve overloads if the other type is overloadable.
13822     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
13823       // We can't actually test that if we still have a placeholder,
13824       // though.  Fortunately, none of the exceptions we see in that
13825       // code below are valid when the LHS is an overload set.  Note
13826       // that an overload set can be dependently-typed, but it never
13827       // instantiates to having an overloadable type.
13828       ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
13829       if (resolvedRHS.isInvalid()) return ExprError();
13830       RHSExpr = resolvedRHS.get();
13831 
13832       if (RHSExpr->isTypeDependent() ||
13833           RHSExpr->getType()->isOverloadableType())
13834         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
13835     }
13836 
13837     // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
13838     // template, diagnose the missing 'template' keyword instead of diagnosing
13839     // an invalid use of a bound member function.
13840     //
13841     // Note that "A::x < b" might be valid if 'b' has an overloadable type due
13842     // to C++1z [over.over]/1.4, but we already checked for that case above.
13843     if (Opc == BO_LT && inTemplateInstantiation() &&
13844         (pty->getKind() == BuiltinType::BoundMember ||
13845          pty->getKind() == BuiltinType::Overload)) {
13846       auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
13847       if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
13848           std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) {
13849             return isa<FunctionTemplateDecl>(ND);
13850           })) {
13851         Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
13852                                 : OE->getNameLoc(),
13853              diag::err_template_kw_missing)
13854           << OE->getName().getAsString() << "";
13855         return ExprError();
13856       }
13857     }
13858 
13859     ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
13860     if (LHS.isInvalid()) return ExprError();
13861     LHSExpr = LHS.get();
13862   }
13863 
13864   // Handle pseudo-objects in the RHS.
13865   if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
13866     // An overload in the RHS can potentially be resolved by the type
13867     // being assigned to.
13868     if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
13869       if (getLangOpts().CPlusPlus &&
13870           (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
13871            LHSExpr->getType()->isOverloadableType()))
13872         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
13873 
13874       return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
13875     }
13876 
13877     // Don't resolve overloads if the other type is overloadable.
13878     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
13879         LHSExpr->getType()->isOverloadableType())
13880       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
13881 
13882     ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
13883     if (!resolvedRHS.isUsable()) return ExprError();
13884     RHSExpr = resolvedRHS.get();
13885   }
13886 
13887   if (getLangOpts().CPlusPlus) {
13888     // If either expression is type-dependent, always build an
13889     // overloaded op.
13890     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
13891       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
13892 
13893     // Otherwise, build an overloaded op if either expression has an
13894     // overloadable type.
13895     if (LHSExpr->getType()->isOverloadableType() ||
13896         RHSExpr->getType()->isOverloadableType())
13897       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
13898   }
13899 
13900   // Build a built-in binary operation.
13901   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
13902 }
13903 
13904 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
13905   if (T.isNull() || T->isDependentType())
13906     return false;
13907 
13908   if (!T->isPromotableIntegerType())
13909     return true;
13910 
13911   return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
13912 }
13913 
13914 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
13915                                       UnaryOperatorKind Opc,
13916                                       Expr *InputExpr) {
13917   ExprResult Input = InputExpr;
13918   ExprValueKind VK = VK_RValue;
13919   ExprObjectKind OK = OK_Ordinary;
13920   QualType resultType;
13921   bool CanOverflow = false;
13922 
13923   bool ConvertHalfVec = false;
13924   if (getLangOpts().OpenCL) {
13925     QualType Ty = InputExpr->getType();
13926     // The only legal unary operation for atomics is '&'.
13927     if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
13928     // OpenCL special types - image, sampler, pipe, and blocks are to be used
13929     // only with a builtin functions and therefore should be disallowed here.
13930         (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
13931         || Ty->isBlockPointerType())) {
13932       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13933                        << InputExpr->getType()
13934                        << Input.get()->getSourceRange());
13935     }
13936   }
13937   // Diagnose operations on the unsupported types for OpenMP device compilation.
13938   if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) {
13939     if (UnaryOperator::isIncrementDecrementOp(Opc) ||
13940         UnaryOperator::isArithmeticOp(Opc))
13941       checkOpenMPDeviceExpr(InputExpr);
13942   }
13943 
13944   switch (Opc) {
13945   case UO_PreInc:
13946   case UO_PreDec:
13947   case UO_PostInc:
13948   case UO_PostDec:
13949     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
13950                                                 OpLoc,
13951                                                 Opc == UO_PreInc ||
13952                                                 Opc == UO_PostInc,
13953                                                 Opc == UO_PreInc ||
13954                                                 Opc == UO_PreDec);
13955     CanOverflow = isOverflowingIntegerType(Context, resultType);
13956     break;
13957   case UO_AddrOf:
13958     resultType = CheckAddressOfOperand(Input, OpLoc);
13959     CheckAddressOfNoDeref(InputExpr);
13960     RecordModifiableNonNullParam(*this, InputExpr);
13961     break;
13962   case UO_Deref: {
13963     Input = DefaultFunctionArrayLvalueConversion(Input.get());
13964     if (Input.isInvalid()) return ExprError();
13965     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
13966     break;
13967   }
13968   case UO_Plus:
13969   case UO_Minus:
13970     CanOverflow = Opc == UO_Minus &&
13971                   isOverflowingIntegerType(Context, Input.get()->getType());
13972     Input = UsualUnaryConversions(Input.get());
13973     if (Input.isInvalid()) return ExprError();
13974     // Unary plus and minus require promoting an operand of half vector to a
13975     // float vector and truncating the result back to a half vector. For now, we
13976     // do this only when HalfArgsAndReturns is set (that is, when the target is
13977     // arm or arm64).
13978     ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get());
13979 
13980     // If the operand is a half vector, promote it to a float vector.
13981     if (ConvertHalfVec)
13982       Input = convertVector(Input.get(), Context.FloatTy, *this);
13983     resultType = Input.get()->getType();
13984     if (resultType->isDependentType())
13985       break;
13986     if (resultType->isArithmeticType()) // C99 6.5.3.3p1
13987       break;
13988     else if (resultType->isVectorType() &&
13989              // The z vector extensions don't allow + or - with bool vectors.
13990              (!Context.getLangOpts().ZVector ||
13991               resultType->castAs<VectorType>()->getVectorKind() !=
13992               VectorType::AltiVecBool))
13993       break;
13994     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
13995              Opc == UO_Plus &&
13996              resultType->isPointerType())
13997       break;
13998 
13999     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14000       << resultType << Input.get()->getSourceRange());
14001 
14002   case UO_Not: // bitwise complement
14003     Input = UsualUnaryConversions(Input.get());
14004     if (Input.isInvalid())
14005       return ExprError();
14006     resultType = Input.get()->getType();
14007     if (resultType->isDependentType())
14008       break;
14009     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
14010     if (resultType->isComplexType() || resultType->isComplexIntegerType())
14011       // C99 does not support '~' for complex conjugation.
14012       Diag(OpLoc, diag::ext_integer_complement_complex)
14013           << resultType << Input.get()->getSourceRange();
14014     else if (resultType->hasIntegerRepresentation())
14015       break;
14016     else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
14017       // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
14018       // on vector float types.
14019       QualType T = resultType->castAs<ExtVectorType>()->getElementType();
14020       if (!T->isIntegerType())
14021         return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14022                           << resultType << Input.get()->getSourceRange());
14023     } else {
14024       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14025                        << resultType << Input.get()->getSourceRange());
14026     }
14027     break;
14028 
14029   case UO_LNot: // logical negation
14030     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
14031     Input = DefaultFunctionArrayLvalueConversion(Input.get());
14032     if (Input.isInvalid()) return ExprError();
14033     resultType = Input.get()->getType();
14034 
14035     // Though we still have to promote half FP to float...
14036     if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
14037       Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
14038       resultType = Context.FloatTy;
14039     }
14040 
14041     if (resultType->isDependentType())
14042       break;
14043     if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
14044       // C99 6.5.3.3p1: ok, fallthrough;
14045       if (Context.getLangOpts().CPlusPlus) {
14046         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
14047         // operand contextually converted to bool.
14048         Input = ImpCastExprToType(Input.get(), Context.BoolTy,
14049                                   ScalarTypeToBooleanCastKind(resultType));
14050       } else if (Context.getLangOpts().OpenCL &&
14051                  Context.getLangOpts().OpenCLVersion < 120) {
14052         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
14053         // operate on scalar float types.
14054         if (!resultType->isIntegerType() && !resultType->isPointerType())
14055           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14056                            << resultType << Input.get()->getSourceRange());
14057       }
14058     } else if (resultType->isExtVectorType()) {
14059       if (Context.getLangOpts().OpenCL &&
14060           Context.getLangOpts().OpenCLVersion < 120 &&
14061           !Context.getLangOpts().OpenCLCPlusPlus) {
14062         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
14063         // operate on vector float types.
14064         QualType T = resultType->castAs<ExtVectorType>()->getElementType();
14065         if (!T->isIntegerType())
14066           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14067                            << resultType << Input.get()->getSourceRange());
14068       }
14069       // Vector logical not returns the signed variant of the operand type.
14070       resultType = GetSignedVectorType(resultType);
14071       break;
14072     } else {
14073       // FIXME: GCC's vector extension permits the usage of '!' with a vector
14074       //        type in C++. We should allow that here too.
14075       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14076         << resultType << Input.get()->getSourceRange());
14077     }
14078 
14079     // LNot always has type int. C99 6.5.3.3p5.
14080     // In C++, it's bool. C++ 5.3.1p8
14081     resultType = Context.getLogicalOperationType();
14082     break;
14083   case UO_Real:
14084   case UO_Imag:
14085     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
14086     // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
14087     // complex l-values to ordinary l-values and all other values to r-values.
14088     if (Input.isInvalid()) return ExprError();
14089     if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
14090       if (Input.get()->getValueKind() != VK_RValue &&
14091           Input.get()->getObjectKind() == OK_Ordinary)
14092         VK = Input.get()->getValueKind();
14093     } else if (!getLangOpts().CPlusPlus) {
14094       // In C, a volatile scalar is read by __imag. In C++, it is not.
14095       Input = DefaultLvalueConversion(Input.get());
14096     }
14097     break;
14098   case UO_Extension:
14099     resultType = Input.get()->getType();
14100     VK = Input.get()->getValueKind();
14101     OK = Input.get()->getObjectKind();
14102     break;
14103   case UO_Coawait:
14104     // It's unnecessary to represent the pass-through operator co_await in the
14105     // AST; just return the input expression instead.
14106     assert(!Input.get()->getType()->isDependentType() &&
14107                    "the co_await expression must be non-dependant before "
14108                    "building operator co_await");
14109     return Input;
14110   }
14111   if (resultType.isNull() || Input.isInvalid())
14112     return ExprError();
14113 
14114   // Check for array bounds violations in the operand of the UnaryOperator,
14115   // except for the '*' and '&' operators that have to be handled specially
14116   // by CheckArrayAccess (as there are special cases like &array[arraysize]
14117   // that are explicitly defined as valid by the standard).
14118   if (Opc != UO_AddrOf && Opc != UO_Deref)
14119     CheckArrayAccess(Input.get());
14120 
14121   auto *UO = new (Context)
14122       UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc, CanOverflow);
14123 
14124   if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) &&
14125       !isa<ArrayType>(UO->getType().getDesugaredType(Context)))
14126     ExprEvalContexts.back().PossibleDerefs.insert(UO);
14127 
14128   // Convert the result back to a half vector.
14129   if (ConvertHalfVec)
14130     return convertVector(UO, Context.HalfTy, *this);
14131   return UO;
14132 }
14133 
14134 /// Determine whether the given expression is a qualified member
14135 /// access expression, of a form that could be turned into a pointer to member
14136 /// with the address-of operator.
14137 bool Sema::isQualifiedMemberAccess(Expr *E) {
14138   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
14139     if (!DRE->getQualifier())
14140       return false;
14141 
14142     ValueDecl *VD = DRE->getDecl();
14143     if (!VD->isCXXClassMember())
14144       return false;
14145 
14146     if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
14147       return true;
14148     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
14149       return Method->isInstance();
14150 
14151     return false;
14152   }
14153 
14154   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
14155     if (!ULE->getQualifier())
14156       return false;
14157 
14158     for (NamedDecl *D : ULE->decls()) {
14159       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
14160         if (Method->isInstance())
14161           return true;
14162       } else {
14163         // Overload set does not contain methods.
14164         break;
14165       }
14166     }
14167 
14168     return false;
14169   }
14170 
14171   return false;
14172 }
14173 
14174 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
14175                               UnaryOperatorKind Opc, Expr *Input) {
14176   // First things first: handle placeholders so that the
14177   // overloaded-operator check considers the right type.
14178   if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
14179     // Increment and decrement of pseudo-object references.
14180     if (pty->getKind() == BuiltinType::PseudoObject &&
14181         UnaryOperator::isIncrementDecrementOp(Opc))
14182       return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
14183 
14184     // extension is always a builtin operator.
14185     if (Opc == UO_Extension)
14186       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
14187 
14188     // & gets special logic for several kinds of placeholder.
14189     // The builtin code knows what to do.
14190     if (Opc == UO_AddrOf &&
14191         (pty->getKind() == BuiltinType::Overload ||
14192          pty->getKind() == BuiltinType::UnknownAny ||
14193          pty->getKind() == BuiltinType::BoundMember))
14194       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
14195 
14196     // Anything else needs to be handled now.
14197     ExprResult Result = CheckPlaceholderExpr(Input);
14198     if (Result.isInvalid()) return ExprError();
14199     Input = Result.get();
14200   }
14201 
14202   if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
14203       UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
14204       !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
14205     // Find all of the overloaded operators visible from this
14206     // point. We perform both an operator-name lookup from the local
14207     // scope and an argument-dependent lookup based on the types of
14208     // the arguments.
14209     UnresolvedSet<16> Functions;
14210     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
14211     if (S && OverOp != OO_None)
14212       LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
14213                                    Functions);
14214 
14215     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
14216   }
14217 
14218   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
14219 }
14220 
14221 // Unary Operators.  'Tok' is the token for the operator.
14222 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
14223                               tok::TokenKind Op, Expr *Input) {
14224   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
14225 }
14226 
14227 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
14228 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
14229                                 LabelDecl *TheDecl) {
14230   TheDecl->markUsed(Context);
14231   // Create the AST node.  The address of a label always has type 'void*'.
14232   return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
14233                                      Context.getPointerType(Context.VoidTy));
14234 }
14235 
14236 void Sema::ActOnStartStmtExpr() {
14237   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
14238 }
14239 
14240 void Sema::ActOnStmtExprError() {
14241   // Note that function is also called by TreeTransform when leaving a
14242   // StmtExpr scope without rebuilding anything.
14243 
14244   DiscardCleanupsInEvaluationContext();
14245   PopExpressionEvaluationContext();
14246 }
14247 
14248 ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt,
14249                                SourceLocation RPLoc) {
14250   return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S));
14251 }
14252 
14253 ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
14254                                SourceLocation RPLoc, unsigned TemplateDepth) {
14255   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
14256   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
14257 
14258   if (hasAnyUnrecoverableErrorsInThisFunction())
14259     DiscardCleanupsInEvaluationContext();
14260   assert(!Cleanup.exprNeedsCleanups() &&
14261          "cleanups within StmtExpr not correctly bound!");
14262   PopExpressionEvaluationContext();
14263 
14264   // FIXME: there are a variety of strange constraints to enforce here, for
14265   // example, it is not possible to goto into a stmt expression apparently.
14266   // More semantic analysis is needed.
14267 
14268   // If there are sub-stmts in the compound stmt, take the type of the last one
14269   // as the type of the stmtexpr.
14270   QualType Ty = Context.VoidTy;
14271   bool StmtExprMayBindToTemp = false;
14272   if (!Compound->body_empty()) {
14273     // For GCC compatibility we get the last Stmt excluding trailing NullStmts.
14274     if (const auto *LastStmt =
14275             dyn_cast<ValueStmt>(Compound->getStmtExprResult())) {
14276       if (const Expr *Value = LastStmt->getExprStmt()) {
14277         StmtExprMayBindToTemp = true;
14278         Ty = Value->getType();
14279       }
14280     }
14281   }
14282 
14283   // FIXME: Check that expression type is complete/non-abstract; statement
14284   // expressions are not lvalues.
14285   Expr *ResStmtExpr =
14286       new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth);
14287   if (StmtExprMayBindToTemp)
14288     return MaybeBindToTemporary(ResStmtExpr);
14289   return ResStmtExpr;
14290 }
14291 
14292 ExprResult Sema::ActOnStmtExprResult(ExprResult ER) {
14293   if (ER.isInvalid())
14294     return ExprError();
14295 
14296   // Do function/array conversion on the last expression, but not
14297   // lvalue-to-rvalue.  However, initialize an unqualified type.
14298   ER = DefaultFunctionArrayConversion(ER.get());
14299   if (ER.isInvalid())
14300     return ExprError();
14301   Expr *E = ER.get();
14302 
14303   if (E->isTypeDependent())
14304     return E;
14305 
14306   // In ARC, if the final expression ends in a consume, splice
14307   // the consume out and bind it later.  In the alternate case
14308   // (when dealing with a retainable type), the result
14309   // initialization will create a produce.  In both cases the
14310   // result will be +1, and we'll need to balance that out with
14311   // a bind.
14312   auto *Cast = dyn_cast<ImplicitCastExpr>(E);
14313   if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
14314     return Cast->getSubExpr();
14315 
14316   // FIXME: Provide a better location for the initialization.
14317   return PerformCopyInitialization(
14318       InitializedEntity::InitializeStmtExprResult(
14319           E->getBeginLoc(), E->getType().getUnqualifiedType()),
14320       SourceLocation(), E);
14321 }
14322 
14323 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
14324                                       TypeSourceInfo *TInfo,
14325                                       ArrayRef<OffsetOfComponent> Components,
14326                                       SourceLocation RParenLoc) {
14327   QualType ArgTy = TInfo->getType();
14328   bool Dependent = ArgTy->isDependentType();
14329   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
14330 
14331   // We must have at least one component that refers to the type, and the first
14332   // one is known to be a field designator.  Verify that the ArgTy represents
14333   // a struct/union/class.
14334   if (!Dependent && !ArgTy->isRecordType())
14335     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
14336                        << ArgTy << TypeRange);
14337 
14338   // Type must be complete per C99 7.17p3 because a declaring a variable
14339   // with an incomplete type would be ill-formed.
14340   if (!Dependent
14341       && RequireCompleteType(BuiltinLoc, ArgTy,
14342                              diag::err_offsetof_incomplete_type, TypeRange))
14343     return ExprError();
14344 
14345   bool DidWarnAboutNonPOD = false;
14346   QualType CurrentType = ArgTy;
14347   SmallVector<OffsetOfNode, 4> Comps;
14348   SmallVector<Expr*, 4> Exprs;
14349   for (const OffsetOfComponent &OC : Components) {
14350     if (OC.isBrackets) {
14351       // Offset of an array sub-field.  TODO: Should we allow vector elements?
14352       if (!CurrentType->isDependentType()) {
14353         const ArrayType *AT = Context.getAsArrayType(CurrentType);
14354         if(!AT)
14355           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
14356                            << CurrentType);
14357         CurrentType = AT->getElementType();
14358       } else
14359         CurrentType = Context.DependentTy;
14360 
14361       ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
14362       if (IdxRval.isInvalid())
14363         return ExprError();
14364       Expr *Idx = IdxRval.get();
14365 
14366       // The expression must be an integral expression.
14367       // FIXME: An integral constant expression?
14368       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
14369           !Idx->getType()->isIntegerType())
14370         return ExprError(
14371             Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer)
14372             << Idx->getSourceRange());
14373 
14374       // Record this array index.
14375       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
14376       Exprs.push_back(Idx);
14377       continue;
14378     }
14379 
14380     // Offset of a field.
14381     if (CurrentType->isDependentType()) {
14382       // We have the offset of a field, but we can't look into the dependent
14383       // type. Just record the identifier of the field.
14384       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
14385       CurrentType = Context.DependentTy;
14386       continue;
14387     }
14388 
14389     // We need to have a complete type to look into.
14390     if (RequireCompleteType(OC.LocStart, CurrentType,
14391                             diag::err_offsetof_incomplete_type))
14392       return ExprError();
14393 
14394     // Look for the designated field.
14395     const RecordType *RC = CurrentType->getAs<RecordType>();
14396     if (!RC)
14397       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
14398                        << CurrentType);
14399     RecordDecl *RD = RC->getDecl();
14400 
14401     // C++ [lib.support.types]p5:
14402     //   The macro offsetof accepts a restricted set of type arguments in this
14403     //   International Standard. type shall be a POD structure or a POD union
14404     //   (clause 9).
14405     // C++11 [support.types]p4:
14406     //   If type is not a standard-layout class (Clause 9), the results are
14407     //   undefined.
14408     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
14409       bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
14410       unsigned DiagID =
14411         LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
14412                             : diag::ext_offsetof_non_pod_type;
14413 
14414       if (!IsSafe && !DidWarnAboutNonPOD &&
14415           DiagRuntimeBehavior(BuiltinLoc, nullptr,
14416                               PDiag(DiagID)
14417                               << SourceRange(Components[0].LocStart, OC.LocEnd)
14418                               << CurrentType))
14419         DidWarnAboutNonPOD = true;
14420     }
14421 
14422     // Look for the field.
14423     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
14424     LookupQualifiedName(R, RD);
14425     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
14426     IndirectFieldDecl *IndirectMemberDecl = nullptr;
14427     if (!MemberDecl) {
14428       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
14429         MemberDecl = IndirectMemberDecl->getAnonField();
14430     }
14431 
14432     if (!MemberDecl)
14433       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
14434                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
14435                                                               OC.LocEnd));
14436 
14437     // C99 7.17p3:
14438     //   (If the specified member is a bit-field, the behavior is undefined.)
14439     //
14440     // We diagnose this as an error.
14441     if (MemberDecl->isBitField()) {
14442       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
14443         << MemberDecl->getDeclName()
14444         << SourceRange(BuiltinLoc, RParenLoc);
14445       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
14446       return ExprError();
14447     }
14448 
14449     RecordDecl *Parent = MemberDecl->getParent();
14450     if (IndirectMemberDecl)
14451       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
14452 
14453     // If the member was found in a base class, introduce OffsetOfNodes for
14454     // the base class indirections.
14455     CXXBasePaths Paths;
14456     if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
14457                       Paths)) {
14458       if (Paths.getDetectedVirtual()) {
14459         Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
14460           << MemberDecl->getDeclName()
14461           << SourceRange(BuiltinLoc, RParenLoc);
14462         return ExprError();
14463       }
14464 
14465       CXXBasePath &Path = Paths.front();
14466       for (const CXXBasePathElement &B : Path)
14467         Comps.push_back(OffsetOfNode(B.Base));
14468     }
14469 
14470     if (IndirectMemberDecl) {
14471       for (auto *FI : IndirectMemberDecl->chain()) {
14472         assert(isa<FieldDecl>(FI));
14473         Comps.push_back(OffsetOfNode(OC.LocStart,
14474                                      cast<FieldDecl>(FI), OC.LocEnd));
14475       }
14476     } else
14477       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
14478 
14479     CurrentType = MemberDecl->getType().getNonReferenceType();
14480   }
14481 
14482   return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
14483                               Comps, Exprs, RParenLoc);
14484 }
14485 
14486 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
14487                                       SourceLocation BuiltinLoc,
14488                                       SourceLocation TypeLoc,
14489                                       ParsedType ParsedArgTy,
14490                                       ArrayRef<OffsetOfComponent> Components,
14491                                       SourceLocation RParenLoc) {
14492 
14493   TypeSourceInfo *ArgTInfo;
14494   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
14495   if (ArgTy.isNull())
14496     return ExprError();
14497 
14498   if (!ArgTInfo)
14499     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
14500 
14501   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
14502 }
14503 
14504 
14505 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
14506                                  Expr *CondExpr,
14507                                  Expr *LHSExpr, Expr *RHSExpr,
14508                                  SourceLocation RPLoc) {
14509   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
14510 
14511   ExprValueKind VK = VK_RValue;
14512   ExprObjectKind OK = OK_Ordinary;
14513   QualType resType;
14514   bool CondIsTrue = false;
14515   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
14516     resType = Context.DependentTy;
14517   } else {
14518     // The conditional expression is required to be a constant expression.
14519     llvm::APSInt condEval(32);
14520     ExprResult CondICE
14521       = VerifyIntegerConstantExpression(CondExpr, &condEval,
14522           diag::err_typecheck_choose_expr_requires_constant, false);
14523     if (CondICE.isInvalid())
14524       return ExprError();
14525     CondExpr = CondICE.get();
14526     CondIsTrue = condEval.getZExtValue();
14527 
14528     // If the condition is > zero, then the AST type is the same as the LHSExpr.
14529     Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
14530 
14531     resType = ActiveExpr->getType();
14532     VK = ActiveExpr->getValueKind();
14533     OK = ActiveExpr->getObjectKind();
14534   }
14535 
14536   return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
14537                                   resType, VK, OK, RPLoc, CondIsTrue);
14538 }
14539 
14540 //===----------------------------------------------------------------------===//
14541 // Clang Extensions.
14542 //===----------------------------------------------------------------------===//
14543 
14544 /// ActOnBlockStart - This callback is invoked when a block literal is started.
14545 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
14546   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
14547 
14548   if (LangOpts.CPlusPlus) {
14549     MangleNumberingContext *MCtx;
14550     Decl *ManglingContextDecl;
14551     std::tie(MCtx, ManglingContextDecl) =
14552         getCurrentMangleNumberContext(Block->getDeclContext());
14553     if (MCtx) {
14554       unsigned ManglingNumber = MCtx->getManglingNumber(Block);
14555       Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
14556     }
14557   }
14558 
14559   PushBlockScope(CurScope, Block);
14560   CurContext->addDecl(Block);
14561   if (CurScope)
14562     PushDeclContext(CurScope, Block);
14563   else
14564     CurContext = Block;
14565 
14566   getCurBlock()->HasImplicitReturnType = true;
14567 
14568   // Enter a new evaluation context to insulate the block from any
14569   // cleanups from the enclosing full-expression.
14570   PushExpressionEvaluationContext(
14571       ExpressionEvaluationContext::PotentiallyEvaluated);
14572 }
14573 
14574 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
14575                                Scope *CurScope) {
14576   assert(ParamInfo.getIdentifier() == nullptr &&
14577          "block-id should have no identifier!");
14578   assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteralContext);
14579   BlockScopeInfo *CurBlock = getCurBlock();
14580 
14581   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
14582   QualType T = Sig->getType();
14583 
14584   // FIXME: We should allow unexpanded parameter packs here, but that would,
14585   // in turn, make the block expression contain unexpanded parameter packs.
14586   if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
14587     // Drop the parameters.
14588     FunctionProtoType::ExtProtoInfo EPI;
14589     EPI.HasTrailingReturn = false;
14590     EPI.TypeQuals.addConst();
14591     T = Context.getFunctionType(Context.DependentTy, None, EPI);
14592     Sig = Context.getTrivialTypeSourceInfo(T);
14593   }
14594 
14595   // GetTypeForDeclarator always produces a function type for a block
14596   // literal signature.  Furthermore, it is always a FunctionProtoType
14597   // unless the function was written with a typedef.
14598   assert(T->isFunctionType() &&
14599          "GetTypeForDeclarator made a non-function block signature");
14600 
14601   // Look for an explicit signature in that function type.
14602   FunctionProtoTypeLoc ExplicitSignature;
14603 
14604   if ((ExplicitSignature = Sig->getTypeLoc()
14605                                .getAsAdjusted<FunctionProtoTypeLoc>())) {
14606 
14607     // Check whether that explicit signature was synthesized by
14608     // GetTypeForDeclarator.  If so, don't save that as part of the
14609     // written signature.
14610     if (ExplicitSignature.getLocalRangeBegin() ==
14611         ExplicitSignature.getLocalRangeEnd()) {
14612       // This would be much cheaper if we stored TypeLocs instead of
14613       // TypeSourceInfos.
14614       TypeLoc Result = ExplicitSignature.getReturnLoc();
14615       unsigned Size = Result.getFullDataSize();
14616       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
14617       Sig->getTypeLoc().initializeFullCopy(Result, Size);
14618 
14619       ExplicitSignature = FunctionProtoTypeLoc();
14620     }
14621   }
14622 
14623   CurBlock->TheDecl->setSignatureAsWritten(Sig);
14624   CurBlock->FunctionType = T;
14625 
14626   const FunctionType *Fn = T->getAs<FunctionType>();
14627   QualType RetTy = Fn->getReturnType();
14628   bool isVariadic =
14629     (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
14630 
14631   CurBlock->TheDecl->setIsVariadic(isVariadic);
14632 
14633   // Context.DependentTy is used as a placeholder for a missing block
14634   // return type.  TODO:  what should we do with declarators like:
14635   //   ^ * { ... }
14636   // If the answer is "apply template argument deduction"....
14637   if (RetTy != Context.DependentTy) {
14638     CurBlock->ReturnType = RetTy;
14639     CurBlock->TheDecl->setBlockMissingReturnType(false);
14640     CurBlock->HasImplicitReturnType = false;
14641   }
14642 
14643   // Push block parameters from the declarator if we had them.
14644   SmallVector<ParmVarDecl*, 8> Params;
14645   if (ExplicitSignature) {
14646     for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
14647       ParmVarDecl *Param = ExplicitSignature.getParam(I);
14648       if (Param->getIdentifier() == nullptr &&
14649           !Param->isImplicit() &&
14650           !Param->isInvalidDecl() &&
14651           !getLangOpts().CPlusPlus)
14652         Diag(Param->getLocation(), diag::err_parameter_name_omitted);
14653       Params.push_back(Param);
14654     }
14655 
14656   // Fake up parameter variables if we have a typedef, like
14657   //   ^ fntype { ... }
14658   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
14659     for (const auto &I : Fn->param_types()) {
14660       ParmVarDecl *Param = BuildParmVarDeclForTypedef(
14661           CurBlock->TheDecl, ParamInfo.getBeginLoc(), I);
14662       Params.push_back(Param);
14663     }
14664   }
14665 
14666   // Set the parameters on the block decl.
14667   if (!Params.empty()) {
14668     CurBlock->TheDecl->setParams(Params);
14669     CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
14670                              /*CheckParameterNames=*/false);
14671   }
14672 
14673   // Finally we can process decl attributes.
14674   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
14675 
14676   // Put the parameter variables in scope.
14677   for (auto AI : CurBlock->TheDecl->parameters()) {
14678     AI->setOwningFunction(CurBlock->TheDecl);
14679 
14680     // If this has an identifier, add it to the scope stack.
14681     if (AI->getIdentifier()) {
14682       CheckShadow(CurBlock->TheScope, AI);
14683 
14684       PushOnScopeChains(AI, CurBlock->TheScope);
14685     }
14686   }
14687 }
14688 
14689 /// ActOnBlockError - If there is an error parsing a block, this callback
14690 /// is invoked to pop the information about the block from the action impl.
14691 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
14692   // Leave the expression-evaluation context.
14693   DiscardCleanupsInEvaluationContext();
14694   PopExpressionEvaluationContext();
14695 
14696   // Pop off CurBlock, handle nested blocks.
14697   PopDeclContext();
14698   PopFunctionScopeInfo();
14699 }
14700 
14701 /// ActOnBlockStmtExpr - This is called when the body of a block statement
14702 /// literal was successfully completed.  ^(int x){...}
14703 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
14704                                     Stmt *Body, Scope *CurScope) {
14705   // If blocks are disabled, emit an error.
14706   if (!LangOpts.Blocks)
14707     Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
14708 
14709   // Leave the expression-evaluation context.
14710   if (hasAnyUnrecoverableErrorsInThisFunction())
14711     DiscardCleanupsInEvaluationContext();
14712   assert(!Cleanup.exprNeedsCleanups() &&
14713          "cleanups within block not correctly bound!");
14714   PopExpressionEvaluationContext();
14715 
14716   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
14717   BlockDecl *BD = BSI->TheDecl;
14718 
14719   if (BSI->HasImplicitReturnType)
14720     deduceClosureReturnType(*BSI);
14721 
14722   QualType RetTy = Context.VoidTy;
14723   if (!BSI->ReturnType.isNull())
14724     RetTy = BSI->ReturnType;
14725 
14726   bool NoReturn = BD->hasAttr<NoReturnAttr>();
14727   QualType BlockTy;
14728 
14729   // If the user wrote a function type in some form, try to use that.
14730   if (!BSI->FunctionType.isNull()) {
14731     const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>();
14732 
14733     FunctionType::ExtInfo Ext = FTy->getExtInfo();
14734     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
14735 
14736     // Turn protoless block types into nullary block types.
14737     if (isa<FunctionNoProtoType>(FTy)) {
14738       FunctionProtoType::ExtProtoInfo EPI;
14739       EPI.ExtInfo = Ext;
14740       BlockTy = Context.getFunctionType(RetTy, None, EPI);
14741 
14742     // Otherwise, if we don't need to change anything about the function type,
14743     // preserve its sugar structure.
14744     } else if (FTy->getReturnType() == RetTy &&
14745                (!NoReturn || FTy->getNoReturnAttr())) {
14746       BlockTy = BSI->FunctionType;
14747 
14748     // Otherwise, make the minimal modifications to the function type.
14749     } else {
14750       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
14751       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
14752       EPI.TypeQuals = Qualifiers();
14753       EPI.ExtInfo = Ext;
14754       BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
14755     }
14756 
14757   // If we don't have a function type, just build one from nothing.
14758   } else {
14759     FunctionProtoType::ExtProtoInfo EPI;
14760     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
14761     BlockTy = Context.getFunctionType(RetTy, None, EPI);
14762   }
14763 
14764   DiagnoseUnusedParameters(BD->parameters());
14765   BlockTy = Context.getBlockPointerType(BlockTy);
14766 
14767   // If needed, diagnose invalid gotos and switches in the block.
14768   if (getCurFunction()->NeedsScopeChecking() &&
14769       !PP.isCodeCompletionEnabled())
14770     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
14771 
14772   BD->setBody(cast<CompoundStmt>(Body));
14773 
14774   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
14775     DiagnoseUnguardedAvailabilityViolations(BD);
14776 
14777   // Try to apply the named return value optimization. We have to check again
14778   // if we can do this, though, because blocks keep return statements around
14779   // to deduce an implicit return type.
14780   if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
14781       !BD->isDependentContext())
14782     computeNRVO(Body, BSI);
14783 
14784   if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() ||
14785       RetTy.hasNonTrivialToPrimitiveCopyCUnion())
14786     checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn,
14787                           NTCUK_Destruct|NTCUK_Copy);
14788 
14789   PopDeclContext();
14790 
14791   // Pop the block scope now but keep it alive to the end of this function.
14792   AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
14793   PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy);
14794 
14795   // Set the captured variables on the block.
14796   SmallVector<BlockDecl::Capture, 4> Captures;
14797   for (Capture &Cap : BSI->Captures) {
14798     if (Cap.isInvalid() || Cap.isThisCapture())
14799       continue;
14800 
14801     VarDecl *Var = Cap.getVariable();
14802     Expr *CopyExpr = nullptr;
14803     if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) {
14804       if (const RecordType *Record =
14805               Cap.getCaptureType()->getAs<RecordType>()) {
14806         // The capture logic needs the destructor, so make sure we mark it.
14807         // Usually this is unnecessary because most local variables have
14808         // their destructors marked at declaration time, but parameters are
14809         // an exception because it's technically only the call site that
14810         // actually requires the destructor.
14811         if (isa<ParmVarDecl>(Var))
14812           FinalizeVarWithDestructor(Var, Record);
14813 
14814         // Enter a separate potentially-evaluated context while building block
14815         // initializers to isolate their cleanups from those of the block
14816         // itself.
14817         // FIXME: Is this appropriate even when the block itself occurs in an
14818         // unevaluated operand?
14819         EnterExpressionEvaluationContext EvalContext(
14820             *this, ExpressionEvaluationContext::PotentiallyEvaluated);
14821 
14822         SourceLocation Loc = Cap.getLocation();
14823 
14824         ExprResult Result = BuildDeclarationNameExpr(
14825             CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
14826 
14827         // According to the blocks spec, the capture of a variable from
14828         // the stack requires a const copy constructor.  This is not true
14829         // of the copy/move done to move a __block variable to the heap.
14830         if (!Result.isInvalid() &&
14831             !Result.get()->getType().isConstQualified()) {
14832           Result = ImpCastExprToType(Result.get(),
14833                                      Result.get()->getType().withConst(),
14834                                      CK_NoOp, VK_LValue);
14835         }
14836 
14837         if (!Result.isInvalid()) {
14838           Result = PerformCopyInitialization(
14839               InitializedEntity::InitializeBlock(Var->getLocation(),
14840                                                  Cap.getCaptureType(), false),
14841               Loc, Result.get());
14842         }
14843 
14844         // Build a full-expression copy expression if initialization
14845         // succeeded and used a non-trivial constructor.  Recover from
14846         // errors by pretending that the copy isn't necessary.
14847         if (!Result.isInvalid() &&
14848             !cast<CXXConstructExpr>(Result.get())->getConstructor()
14849                 ->isTrivial()) {
14850           Result = MaybeCreateExprWithCleanups(Result);
14851           CopyExpr = Result.get();
14852         }
14853       }
14854     }
14855 
14856     BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(),
14857                               CopyExpr);
14858     Captures.push_back(NewCap);
14859   }
14860   BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
14861 
14862   BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy);
14863 
14864   // If the block isn't obviously global, i.e. it captures anything at
14865   // all, then we need to do a few things in the surrounding context:
14866   if (Result->getBlockDecl()->hasCaptures()) {
14867     // First, this expression has a new cleanup object.
14868     ExprCleanupObjects.push_back(Result->getBlockDecl());
14869     Cleanup.setExprNeedsCleanups(true);
14870 
14871     // It also gets a branch-protected scope if any of the captured
14872     // variables needs destruction.
14873     for (const auto &CI : Result->getBlockDecl()->captures()) {
14874       const VarDecl *var = CI.getVariable();
14875       if (var->getType().isDestructedType() != QualType::DK_none) {
14876         setFunctionHasBranchProtectedScope();
14877         break;
14878       }
14879     }
14880   }
14881 
14882   if (getCurFunction())
14883     getCurFunction()->addBlock(BD);
14884 
14885   return Result;
14886 }
14887 
14888 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
14889                             SourceLocation RPLoc) {
14890   TypeSourceInfo *TInfo;
14891   GetTypeFromParser(Ty, &TInfo);
14892   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
14893 }
14894 
14895 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
14896                                 Expr *E, TypeSourceInfo *TInfo,
14897                                 SourceLocation RPLoc) {
14898   Expr *OrigExpr = E;
14899   bool IsMS = false;
14900 
14901   // CUDA device code does not support varargs.
14902   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
14903     if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
14904       CUDAFunctionTarget T = IdentifyCUDATarget(F);
14905       if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
14906         return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device));
14907     }
14908   }
14909 
14910   // NVPTX does not support va_arg expression.
14911   if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
14912       Context.getTargetInfo().getTriple().isNVPTX())
14913     targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device);
14914 
14915   // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
14916   // as Microsoft ABI on an actual Microsoft platform, where
14917   // __builtin_ms_va_list and __builtin_va_list are the same.)
14918   if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
14919       Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
14920     QualType MSVaListType = Context.getBuiltinMSVaListType();
14921     if (Context.hasSameType(MSVaListType, E->getType())) {
14922       if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
14923         return ExprError();
14924       IsMS = true;
14925     }
14926   }
14927 
14928   // Get the va_list type
14929   QualType VaListType = Context.getBuiltinVaListType();
14930   if (!IsMS) {
14931     if (VaListType->isArrayType()) {
14932       // Deal with implicit array decay; for example, on x86-64,
14933       // va_list is an array, but it's supposed to decay to
14934       // a pointer for va_arg.
14935       VaListType = Context.getArrayDecayedType(VaListType);
14936       // Make sure the input expression also decays appropriately.
14937       ExprResult Result = UsualUnaryConversions(E);
14938       if (Result.isInvalid())
14939         return ExprError();
14940       E = Result.get();
14941     } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
14942       // If va_list is a record type and we are compiling in C++ mode,
14943       // check the argument using reference binding.
14944       InitializedEntity Entity = InitializedEntity::InitializeParameter(
14945           Context, Context.getLValueReferenceType(VaListType), false);
14946       ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
14947       if (Init.isInvalid())
14948         return ExprError();
14949       E = Init.getAs<Expr>();
14950     } else {
14951       // Otherwise, the va_list argument must be an l-value because
14952       // it is modified by va_arg.
14953       if (!E->isTypeDependent() &&
14954           CheckForModifiableLvalue(E, BuiltinLoc, *this))
14955         return ExprError();
14956     }
14957   }
14958 
14959   if (!IsMS && !E->isTypeDependent() &&
14960       !Context.hasSameType(VaListType, E->getType()))
14961     return ExprError(
14962         Diag(E->getBeginLoc(),
14963              diag::err_first_argument_to_va_arg_not_of_type_va_list)
14964         << OrigExpr->getType() << E->getSourceRange());
14965 
14966   if (!TInfo->getType()->isDependentType()) {
14967     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
14968                             diag::err_second_parameter_to_va_arg_incomplete,
14969                             TInfo->getTypeLoc()))
14970       return ExprError();
14971 
14972     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
14973                                TInfo->getType(),
14974                                diag::err_second_parameter_to_va_arg_abstract,
14975                                TInfo->getTypeLoc()))
14976       return ExprError();
14977 
14978     if (!TInfo->getType().isPODType(Context)) {
14979       Diag(TInfo->getTypeLoc().getBeginLoc(),
14980            TInfo->getType()->isObjCLifetimeType()
14981              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
14982              : diag::warn_second_parameter_to_va_arg_not_pod)
14983         << TInfo->getType()
14984         << TInfo->getTypeLoc().getSourceRange();
14985     }
14986 
14987     // Check for va_arg where arguments of the given type will be promoted
14988     // (i.e. this va_arg is guaranteed to have undefined behavior).
14989     QualType PromoteType;
14990     if (TInfo->getType()->isPromotableIntegerType()) {
14991       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
14992       if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
14993         PromoteType = QualType();
14994     }
14995     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
14996       PromoteType = Context.DoubleTy;
14997     if (!PromoteType.isNull())
14998       DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
14999                   PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
15000                           << TInfo->getType()
15001                           << PromoteType
15002                           << TInfo->getTypeLoc().getSourceRange());
15003   }
15004 
15005   QualType T = TInfo->getType().getNonLValueExprType(Context);
15006   return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
15007 }
15008 
15009 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
15010   // The type of __null will be int or long, depending on the size of
15011   // pointers on the target.
15012   QualType Ty;
15013   unsigned pw = Context.getTargetInfo().getPointerWidth(0);
15014   if (pw == Context.getTargetInfo().getIntWidth())
15015     Ty = Context.IntTy;
15016   else if (pw == Context.getTargetInfo().getLongWidth())
15017     Ty = Context.LongTy;
15018   else if (pw == Context.getTargetInfo().getLongLongWidth())
15019     Ty = Context.LongLongTy;
15020   else {
15021     llvm_unreachable("I don't know size of pointer!");
15022   }
15023 
15024   return new (Context) GNUNullExpr(Ty, TokenLoc);
15025 }
15026 
15027 ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind,
15028                                     SourceLocation BuiltinLoc,
15029                                     SourceLocation RPLoc) {
15030   return BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, CurContext);
15031 }
15032 
15033 ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind,
15034                                     SourceLocation BuiltinLoc,
15035                                     SourceLocation RPLoc,
15036                                     DeclContext *ParentContext) {
15037   return new (Context)
15038       SourceLocExpr(Context, Kind, BuiltinLoc, RPLoc, ParentContext);
15039 }
15040 
15041 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp,
15042                                               bool Diagnose) {
15043   if (!getLangOpts().ObjC)
15044     return false;
15045 
15046   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
15047   if (!PT)
15048     return false;
15049 
15050   if (!PT->isObjCIdType()) {
15051     // Check if the destination is the 'NSString' interface.
15052     const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
15053     if (!ID || !ID->getIdentifier()->isStr("NSString"))
15054       return false;
15055   }
15056 
15057   // Ignore any parens, implicit casts (should only be
15058   // array-to-pointer decays), and not-so-opaque values.  The last is
15059   // important for making this trigger for property assignments.
15060   Expr *SrcExpr = Exp->IgnoreParenImpCasts();
15061   if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
15062     if (OV->getSourceExpr())
15063       SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
15064 
15065   StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
15066   if (!SL || !SL->isAscii())
15067     return false;
15068   if (Diagnose) {
15069     Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix)
15070         << FixItHint::CreateInsertion(SL->getBeginLoc(), "@");
15071     Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get();
15072   }
15073   return true;
15074 }
15075 
15076 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
15077                                               const Expr *SrcExpr) {
15078   if (!DstType->isFunctionPointerType() ||
15079       !SrcExpr->getType()->isFunctionType())
15080     return false;
15081 
15082   auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
15083   if (!DRE)
15084     return false;
15085 
15086   auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
15087   if (!FD)
15088     return false;
15089 
15090   return !S.checkAddressOfFunctionIsAvailable(FD,
15091                                               /*Complain=*/true,
15092                                               SrcExpr->getBeginLoc());
15093 }
15094 
15095 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
15096                                     SourceLocation Loc,
15097                                     QualType DstType, QualType SrcType,
15098                                     Expr *SrcExpr, AssignmentAction Action,
15099                                     bool *Complained) {
15100   if (Complained)
15101     *Complained = false;
15102 
15103   // Decode the result (notice that AST's are still created for extensions).
15104   bool CheckInferredResultType = false;
15105   bool isInvalid = false;
15106   unsigned DiagKind = 0;
15107   FixItHint Hint;
15108   ConversionFixItGenerator ConvHints;
15109   bool MayHaveConvFixit = false;
15110   bool MayHaveFunctionDiff = false;
15111   const ObjCInterfaceDecl *IFace = nullptr;
15112   const ObjCProtocolDecl *PDecl = nullptr;
15113 
15114   switch (ConvTy) {
15115   case Compatible:
15116       DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
15117       return false;
15118 
15119   case PointerToInt:
15120     if (getLangOpts().CPlusPlus) {
15121       DiagKind = diag::err_typecheck_convert_pointer_int;
15122       isInvalid = true;
15123     } else {
15124       DiagKind = diag::ext_typecheck_convert_pointer_int;
15125     }
15126     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15127     MayHaveConvFixit = true;
15128     break;
15129   case IntToPointer:
15130     if (getLangOpts().CPlusPlus) {
15131       DiagKind = diag::err_typecheck_convert_int_pointer;
15132       isInvalid = true;
15133     } else {
15134       DiagKind = diag::ext_typecheck_convert_int_pointer;
15135     }
15136     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15137     MayHaveConvFixit = true;
15138     break;
15139   case IncompatibleFunctionPointer:
15140     if (getLangOpts().CPlusPlus) {
15141       DiagKind = diag::err_typecheck_convert_incompatible_function_pointer;
15142       isInvalid = true;
15143     } else {
15144       DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
15145     }
15146     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15147     MayHaveConvFixit = true;
15148     break;
15149   case IncompatiblePointer:
15150     if (Action == AA_Passing_CFAudited) {
15151       DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
15152     } else if (getLangOpts().CPlusPlus) {
15153       DiagKind = diag::err_typecheck_convert_incompatible_pointer;
15154       isInvalid = true;
15155     } else {
15156       DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
15157     }
15158     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
15159       SrcType->isObjCObjectPointerType();
15160     if (Hint.isNull() && !CheckInferredResultType) {
15161       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15162     }
15163     else if (CheckInferredResultType) {
15164       SrcType = SrcType.getUnqualifiedType();
15165       DstType = DstType.getUnqualifiedType();
15166     }
15167     MayHaveConvFixit = true;
15168     break;
15169   case IncompatiblePointerSign:
15170     if (getLangOpts().CPlusPlus) {
15171       DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign;
15172       isInvalid = true;
15173     } else {
15174       DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
15175     }
15176     break;
15177   case FunctionVoidPointer:
15178     if (getLangOpts().CPlusPlus) {
15179       DiagKind = diag::err_typecheck_convert_pointer_void_func;
15180       isInvalid = true;
15181     } else {
15182       DiagKind = diag::ext_typecheck_convert_pointer_void_func;
15183     }
15184     break;
15185   case IncompatiblePointerDiscardsQualifiers: {
15186     // Perform array-to-pointer decay if necessary.
15187     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
15188 
15189     isInvalid = true;
15190 
15191     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
15192     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
15193     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
15194       DiagKind = diag::err_typecheck_incompatible_address_space;
15195       break;
15196 
15197     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
15198       DiagKind = diag::err_typecheck_incompatible_ownership;
15199       break;
15200     }
15201 
15202     llvm_unreachable("unknown error case for discarding qualifiers!");
15203     // fallthrough
15204   }
15205   case CompatiblePointerDiscardsQualifiers:
15206     // If the qualifiers lost were because we were applying the
15207     // (deprecated) C++ conversion from a string literal to a char*
15208     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
15209     // Ideally, this check would be performed in
15210     // checkPointerTypesForAssignment. However, that would require a
15211     // bit of refactoring (so that the second argument is an
15212     // expression, rather than a type), which should be done as part
15213     // of a larger effort to fix checkPointerTypesForAssignment for
15214     // C++ semantics.
15215     if (getLangOpts().CPlusPlus &&
15216         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
15217       return false;
15218     if (getLangOpts().CPlusPlus) {
15219       DiagKind =  diag::err_typecheck_convert_discards_qualifiers;
15220       isInvalid = true;
15221     } else {
15222       DiagKind =  diag::ext_typecheck_convert_discards_qualifiers;
15223     }
15224 
15225     break;
15226   case IncompatibleNestedPointerQualifiers:
15227     if (getLangOpts().CPlusPlus) {
15228       isInvalid = true;
15229       DiagKind = diag::err_nested_pointer_qualifier_mismatch;
15230     } else {
15231       DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
15232     }
15233     break;
15234   case IncompatibleNestedPointerAddressSpaceMismatch:
15235     DiagKind = diag::err_typecheck_incompatible_nested_address_space;
15236     isInvalid = true;
15237     break;
15238   case IntToBlockPointer:
15239     DiagKind = diag::err_int_to_block_pointer;
15240     isInvalid = true;
15241     break;
15242   case IncompatibleBlockPointer:
15243     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
15244     isInvalid = true;
15245     break;
15246   case IncompatibleObjCQualifiedId: {
15247     if (SrcType->isObjCQualifiedIdType()) {
15248       const ObjCObjectPointerType *srcOPT =
15249                 SrcType->castAs<ObjCObjectPointerType>();
15250       for (auto *srcProto : srcOPT->quals()) {
15251         PDecl = srcProto;
15252         break;
15253       }
15254       if (const ObjCInterfaceType *IFaceT =
15255             DstType->castAs<ObjCObjectPointerType>()->getInterfaceType())
15256         IFace = IFaceT->getDecl();
15257     }
15258     else if (DstType->isObjCQualifiedIdType()) {
15259       const ObjCObjectPointerType *dstOPT =
15260         DstType->castAs<ObjCObjectPointerType>();
15261       for (auto *dstProto : dstOPT->quals()) {
15262         PDecl = dstProto;
15263         break;
15264       }
15265       if (const ObjCInterfaceType *IFaceT =
15266             SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType())
15267         IFace = IFaceT->getDecl();
15268     }
15269     if (getLangOpts().CPlusPlus) {
15270       DiagKind = diag::err_incompatible_qualified_id;
15271       isInvalid = true;
15272     } else {
15273       DiagKind = diag::warn_incompatible_qualified_id;
15274     }
15275     break;
15276   }
15277   case IncompatibleVectors:
15278     if (getLangOpts().CPlusPlus) {
15279       DiagKind = diag::err_incompatible_vectors;
15280       isInvalid = true;
15281     } else {
15282       DiagKind = diag::warn_incompatible_vectors;
15283     }
15284     break;
15285   case IncompatibleObjCWeakRef:
15286     DiagKind = diag::err_arc_weak_unavailable_assign;
15287     isInvalid = true;
15288     break;
15289   case Incompatible:
15290     if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
15291       if (Complained)
15292         *Complained = true;
15293       return true;
15294     }
15295 
15296     DiagKind = diag::err_typecheck_convert_incompatible;
15297     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15298     MayHaveConvFixit = true;
15299     isInvalid = true;
15300     MayHaveFunctionDiff = true;
15301     break;
15302   }
15303 
15304   QualType FirstType, SecondType;
15305   switch (Action) {
15306   case AA_Assigning:
15307   case AA_Initializing:
15308     // The destination type comes first.
15309     FirstType = DstType;
15310     SecondType = SrcType;
15311     break;
15312 
15313   case AA_Returning:
15314   case AA_Passing:
15315   case AA_Passing_CFAudited:
15316   case AA_Converting:
15317   case AA_Sending:
15318   case AA_Casting:
15319     // The source type comes first.
15320     FirstType = SrcType;
15321     SecondType = DstType;
15322     break;
15323   }
15324 
15325   PartialDiagnostic FDiag = PDiag(DiagKind);
15326   if (Action == AA_Passing_CFAudited)
15327     FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
15328   else
15329     FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
15330 
15331   // If we can fix the conversion, suggest the FixIts.
15332   assert(ConvHints.isNull() || Hint.isNull());
15333   if (!ConvHints.isNull()) {
15334     for (FixItHint &H : ConvHints.Hints)
15335       FDiag << H;
15336   } else {
15337     FDiag << Hint;
15338   }
15339   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
15340 
15341   if (MayHaveFunctionDiff)
15342     HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
15343 
15344   Diag(Loc, FDiag);
15345   if ((DiagKind == diag::warn_incompatible_qualified_id ||
15346        DiagKind == diag::err_incompatible_qualified_id) &&
15347       PDecl && IFace && !IFace->hasDefinition())
15348     Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
15349         << IFace << PDecl;
15350 
15351   if (SecondType == Context.OverloadTy)
15352     NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
15353                               FirstType, /*TakingAddress=*/true);
15354 
15355   if (CheckInferredResultType)
15356     EmitRelatedResultTypeNote(SrcExpr);
15357 
15358   if (Action == AA_Returning && ConvTy == IncompatiblePointer)
15359     EmitRelatedResultTypeNoteForReturn(DstType);
15360 
15361   if (Complained)
15362     *Complained = true;
15363   return isInvalid;
15364 }
15365 
15366 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
15367                                                  llvm::APSInt *Result) {
15368   class SimpleICEDiagnoser : public VerifyICEDiagnoser {
15369   public:
15370     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
15371       S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
15372     }
15373   } Diagnoser;
15374 
15375   return VerifyIntegerConstantExpression(E, Result, Diagnoser);
15376 }
15377 
15378 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
15379                                                  llvm::APSInt *Result,
15380                                                  unsigned DiagID,
15381                                                  bool AllowFold) {
15382   class IDDiagnoser : public VerifyICEDiagnoser {
15383     unsigned DiagID;
15384 
15385   public:
15386     IDDiagnoser(unsigned DiagID)
15387       : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
15388 
15389     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
15390       S.Diag(Loc, DiagID) << SR;
15391     }
15392   } Diagnoser(DiagID);
15393 
15394   return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
15395 }
15396 
15397 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
15398                                             SourceRange SR) {
15399   S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
15400 }
15401 
15402 ExprResult
15403 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
15404                                       VerifyICEDiagnoser &Diagnoser,
15405                                       bool AllowFold) {
15406   SourceLocation DiagLoc = E->getBeginLoc();
15407 
15408   if (getLangOpts().CPlusPlus11) {
15409     // C++11 [expr.const]p5:
15410     //   If an expression of literal class type is used in a context where an
15411     //   integral constant expression is required, then that class type shall
15412     //   have a single non-explicit conversion function to an integral or
15413     //   unscoped enumeration type
15414     ExprResult Converted;
15415     class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
15416     public:
15417       CXX11ConvertDiagnoser(bool Silent)
15418           : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
15419                                 Silent, true) {}
15420 
15421       SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
15422                                            QualType T) override {
15423         return S.Diag(Loc, diag::err_ice_not_integral) << T;
15424       }
15425 
15426       SemaDiagnosticBuilder diagnoseIncomplete(
15427           Sema &S, SourceLocation Loc, QualType T) override {
15428         return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
15429       }
15430 
15431       SemaDiagnosticBuilder diagnoseExplicitConv(
15432           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
15433         return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
15434       }
15435 
15436       SemaDiagnosticBuilder noteExplicitConv(
15437           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
15438         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
15439                  << ConvTy->isEnumeralType() << ConvTy;
15440       }
15441 
15442       SemaDiagnosticBuilder diagnoseAmbiguous(
15443           Sema &S, SourceLocation Loc, QualType T) override {
15444         return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
15445       }
15446 
15447       SemaDiagnosticBuilder noteAmbiguous(
15448           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
15449         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
15450                  << ConvTy->isEnumeralType() << ConvTy;
15451       }
15452 
15453       SemaDiagnosticBuilder diagnoseConversion(
15454           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
15455         llvm_unreachable("conversion functions are permitted");
15456       }
15457     } ConvertDiagnoser(Diagnoser.Suppress);
15458 
15459     Converted = PerformContextualImplicitConversion(DiagLoc, E,
15460                                                     ConvertDiagnoser);
15461     if (Converted.isInvalid())
15462       return Converted;
15463     E = Converted.get();
15464     if (!E->getType()->isIntegralOrUnscopedEnumerationType())
15465       return ExprError();
15466   } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
15467     // An ICE must be of integral or unscoped enumeration type.
15468     if (!Diagnoser.Suppress)
15469       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
15470     return ExprError();
15471   }
15472 
15473   ExprResult RValueExpr = DefaultLvalueConversion(E);
15474   if (RValueExpr.isInvalid())
15475     return ExprError();
15476 
15477   E = RValueExpr.get();
15478 
15479   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
15480   // in the non-ICE case.
15481   if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
15482     if (Result)
15483       *Result = E->EvaluateKnownConstIntCheckOverflow(Context);
15484     if (!isa<ConstantExpr>(E))
15485       E = ConstantExpr::Create(Context, E);
15486     return E;
15487   }
15488 
15489   Expr::EvalResult EvalResult;
15490   SmallVector<PartialDiagnosticAt, 8> Notes;
15491   EvalResult.Diag = &Notes;
15492 
15493   // Try to evaluate the expression, and produce diagnostics explaining why it's
15494   // not a constant expression as a side-effect.
15495   bool Folded =
15496       E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) &&
15497       EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
15498 
15499   if (!isa<ConstantExpr>(E))
15500     E = ConstantExpr::Create(Context, E, EvalResult.Val);
15501 
15502   // In C++11, we can rely on diagnostics being produced for any expression
15503   // which is not a constant expression. If no diagnostics were produced, then
15504   // this is a constant expression.
15505   if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
15506     if (Result)
15507       *Result = EvalResult.Val.getInt();
15508     return E;
15509   }
15510 
15511   // If our only note is the usual "invalid subexpression" note, just point
15512   // the caret at its location rather than producing an essentially
15513   // redundant note.
15514   if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
15515         diag::note_invalid_subexpr_in_const_expr) {
15516     DiagLoc = Notes[0].first;
15517     Notes.clear();
15518   }
15519 
15520   if (!Folded || !AllowFold) {
15521     if (!Diagnoser.Suppress) {
15522       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
15523       for (const PartialDiagnosticAt &Note : Notes)
15524         Diag(Note.first, Note.second);
15525     }
15526 
15527     return ExprError();
15528   }
15529 
15530   Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
15531   for (const PartialDiagnosticAt &Note : Notes)
15532     Diag(Note.first, Note.second);
15533 
15534   if (Result)
15535     *Result = EvalResult.Val.getInt();
15536   return E;
15537 }
15538 
15539 namespace {
15540   // Handle the case where we conclude a expression which we speculatively
15541   // considered to be unevaluated is actually evaluated.
15542   class TransformToPE : public TreeTransform<TransformToPE> {
15543     typedef TreeTransform<TransformToPE> BaseTransform;
15544 
15545   public:
15546     TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
15547 
15548     // Make sure we redo semantic analysis
15549     bool AlwaysRebuild() { return true; }
15550     bool ReplacingOriginal() { return true; }
15551 
15552     // We need to special-case DeclRefExprs referring to FieldDecls which
15553     // are not part of a member pointer formation; normal TreeTransforming
15554     // doesn't catch this case because of the way we represent them in the AST.
15555     // FIXME: This is a bit ugly; is it really the best way to handle this
15556     // case?
15557     //
15558     // Error on DeclRefExprs referring to FieldDecls.
15559     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
15560       if (isa<FieldDecl>(E->getDecl()) &&
15561           !SemaRef.isUnevaluatedContext())
15562         return SemaRef.Diag(E->getLocation(),
15563                             diag::err_invalid_non_static_member_use)
15564             << E->getDecl() << E->getSourceRange();
15565 
15566       return BaseTransform::TransformDeclRefExpr(E);
15567     }
15568 
15569     // Exception: filter out member pointer formation
15570     ExprResult TransformUnaryOperator(UnaryOperator *E) {
15571       if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
15572         return E;
15573 
15574       return BaseTransform::TransformUnaryOperator(E);
15575     }
15576 
15577     // The body of a lambda-expression is in a separate expression evaluation
15578     // context so never needs to be transformed.
15579     // FIXME: Ideally we wouldn't transform the closure type either, and would
15580     // just recreate the capture expressions and lambda expression.
15581     StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
15582       return SkipLambdaBody(E, Body);
15583     }
15584   };
15585 }
15586 
15587 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
15588   assert(isUnevaluatedContext() &&
15589          "Should only transform unevaluated expressions");
15590   ExprEvalContexts.back().Context =
15591       ExprEvalContexts[ExprEvalContexts.size()-2].Context;
15592   if (isUnevaluatedContext())
15593     return E;
15594   return TransformToPE(*this).TransformExpr(E);
15595 }
15596 
15597 void
15598 Sema::PushExpressionEvaluationContext(
15599     ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
15600     ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
15601   ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
15602                                 LambdaContextDecl, ExprContext);
15603   Cleanup.reset();
15604   if (!MaybeODRUseExprs.empty())
15605     std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
15606 }
15607 
15608 void
15609 Sema::PushExpressionEvaluationContext(
15610     ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
15611     ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
15612   Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
15613   PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);
15614 }
15615 
15616 namespace {
15617 
15618 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
15619   PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
15620   if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) {
15621     if (E->getOpcode() == UO_Deref)
15622       return CheckPossibleDeref(S, E->getSubExpr());
15623   } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) {
15624     return CheckPossibleDeref(S, E->getBase());
15625   } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) {
15626     return CheckPossibleDeref(S, E->getBase());
15627   } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) {
15628     QualType Inner;
15629     QualType Ty = E->getType();
15630     if (const auto *Ptr = Ty->getAs<PointerType>())
15631       Inner = Ptr->getPointeeType();
15632     else if (const auto *Arr = S.Context.getAsArrayType(Ty))
15633       Inner = Arr->getElementType();
15634     else
15635       return nullptr;
15636 
15637     if (Inner->hasAttr(attr::NoDeref))
15638       return E;
15639   }
15640   return nullptr;
15641 }
15642 
15643 } // namespace
15644 
15645 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) {
15646   for (const Expr *E : Rec.PossibleDerefs) {
15647     const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E);
15648     if (DeclRef) {
15649       const ValueDecl *Decl = DeclRef->getDecl();
15650       Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type)
15651           << Decl->getName() << E->getSourceRange();
15652       Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName();
15653     } else {
15654       Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl)
15655           << E->getSourceRange();
15656     }
15657   }
15658   Rec.PossibleDerefs.clear();
15659 }
15660 
15661 /// Check whether E, which is either a discarded-value expression or an
15662 /// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue,
15663 /// and if so, remove it from the list of volatile-qualified assignments that
15664 /// we are going to warn are deprecated.
15665 void Sema::CheckUnusedVolatileAssignment(Expr *E) {
15666   if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus2a)
15667     return;
15668 
15669   // Note: ignoring parens here is not justified by the standard rules, but
15670   // ignoring parentheses seems like a more reasonable approach, and this only
15671   // drives a deprecation warning so doesn't affect conformance.
15672   if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) {
15673     if (BO->getOpcode() == BO_Assign) {
15674       auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs;
15675       LHSs.erase(std::remove(LHSs.begin(), LHSs.end(), BO->getLHS()),
15676                  LHSs.end());
15677     }
15678   }
15679 }
15680 
15681 ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) {
15682   if (!E.isUsable() || !Decl || !Decl->isConsteval() || isConstantEvaluated() ||
15683       RebuildingImmediateInvocation)
15684     return E;
15685 
15686   /// Opportunistically remove the callee from ReferencesToConsteval if we can.
15687   /// It's OK if this fails; we'll also remove this in
15688   /// HandleImmediateInvocations, but catching it here allows us to avoid
15689   /// walking the AST looking for it in simple cases.
15690   if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit()))
15691     if (auto *DeclRef =
15692             dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()))
15693       ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef);
15694 
15695   E = MaybeCreateExprWithCleanups(E);
15696 
15697   ConstantExpr *Res = ConstantExpr::Create(
15698       getASTContext(), E.get(),
15699       ConstantExpr::getStorageKind(E.get()->getType().getTypePtr(),
15700                                    getASTContext()),
15701       /*IsImmediateInvocation*/ true);
15702   ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0);
15703   return Res;
15704 }
15705 
15706 static void EvaluateAndDiagnoseImmediateInvocation(
15707     Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) {
15708   llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
15709   Expr::EvalResult Eval;
15710   Eval.Diag = &Notes;
15711   ConstantExpr *CE = Candidate.getPointer();
15712   bool Result = CE->EvaluateAsConstantExpr(Eval, Expr::EvaluateForCodeGen,
15713                                            SemaRef.getASTContext(), true);
15714   if (!Result || !Notes.empty()) {
15715     Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit();
15716     if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr))
15717       InnerExpr = FunctionalCast->getSubExpr();
15718     FunctionDecl *FD = nullptr;
15719     if (auto *Call = dyn_cast<CallExpr>(InnerExpr))
15720       FD = cast<FunctionDecl>(Call->getCalleeDecl());
15721     else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr))
15722       FD = Call->getConstructor();
15723     else
15724       llvm_unreachable("unhandled decl kind");
15725     assert(FD->isConsteval());
15726     SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call) << FD;
15727     for (auto &Note : Notes)
15728       SemaRef.Diag(Note.first, Note.second);
15729     return;
15730   }
15731   CE->MoveIntoResult(Eval.Val, SemaRef.getASTContext());
15732 }
15733 
15734 static void RemoveNestedImmediateInvocation(
15735     Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec,
15736     SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) {
15737   struct ComplexRemove : TreeTransform<ComplexRemove> {
15738     using Base = TreeTransform<ComplexRemove>;
15739     llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
15740     SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet;
15741     SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator
15742         CurrentII;
15743     ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR,
15744                   SmallVector<Sema::ImmediateInvocationCandidate, 4> &II,
15745                   SmallVector<Sema::ImmediateInvocationCandidate,
15746                               4>::reverse_iterator Current)
15747         : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {}
15748     void RemoveImmediateInvocation(ConstantExpr* E) {
15749       auto It = std::find_if(CurrentII, IISet.rend(),
15750                              [E](Sema::ImmediateInvocationCandidate Elem) {
15751                                return Elem.getPointer() == E;
15752                              });
15753       assert(It != IISet.rend() &&
15754              "ConstantExpr marked IsImmediateInvocation should "
15755              "be present");
15756       It->setInt(1); // Mark as deleted
15757     }
15758     ExprResult TransformConstantExpr(ConstantExpr *E) {
15759       if (!E->isImmediateInvocation())
15760         return Base::TransformConstantExpr(E);
15761       RemoveImmediateInvocation(E);
15762       return Base::TransformExpr(E->getSubExpr());
15763     }
15764     /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so
15765     /// we need to remove its DeclRefExpr from the DRSet.
15766     ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
15767       DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit()));
15768       return Base::TransformCXXOperatorCallExpr(E);
15769     }
15770     /// Base::TransformInitializer skip ConstantExpr so we need to visit them
15771     /// here.
15772     ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) {
15773       if (!Init)
15774         return Init;
15775       /// ConstantExpr are the first layer of implicit node to be removed so if
15776       /// Init isn't a ConstantExpr, no ConstantExpr will be skipped.
15777       if (auto *CE = dyn_cast<ConstantExpr>(Init))
15778         if (CE->isImmediateInvocation())
15779           RemoveImmediateInvocation(CE);
15780       return Base::TransformInitializer(Init, NotCopyInit);
15781     }
15782     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
15783       DRSet.erase(E);
15784       return E;
15785     }
15786     bool AlwaysRebuild() { return false; }
15787     bool ReplacingOriginal() { return true; }
15788     bool AllowSkippingCXXConstructExpr() {
15789       bool Res = AllowSkippingFirstCXXConstructExpr;
15790       AllowSkippingFirstCXXConstructExpr = true;
15791       return Res;
15792     }
15793     bool AllowSkippingFirstCXXConstructExpr = true;
15794   } Transformer(SemaRef, Rec.ReferenceToConsteval,
15795                 Rec.ImmediateInvocationCandidates, It);
15796 
15797   /// CXXConstructExpr with a single argument are getting skipped by
15798   /// TreeTransform in some situtation because they could be implicit. This
15799   /// can only occur for the top-level CXXConstructExpr because it is used
15800   /// nowhere in the expression being transformed therefore will not be rebuilt.
15801   /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from
15802   /// skipping the first CXXConstructExpr.
15803   if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit()))
15804     Transformer.AllowSkippingFirstCXXConstructExpr = false;
15805 
15806   ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr());
15807   assert(Res.isUsable());
15808   Res = SemaRef.MaybeCreateExprWithCleanups(Res);
15809   It->getPointer()->setSubExpr(Res.get());
15810 }
15811 
15812 static void
15813 HandleImmediateInvocations(Sema &SemaRef,
15814                            Sema::ExpressionEvaluationContextRecord &Rec) {
15815   if ((Rec.ImmediateInvocationCandidates.size() == 0 &&
15816        Rec.ReferenceToConsteval.size() == 0) ||
15817       SemaRef.RebuildingImmediateInvocation)
15818     return;
15819 
15820   /// When we have more then 1 ImmediateInvocationCandidates we need to check
15821   /// for nested ImmediateInvocationCandidates. when we have only 1 we only
15822   /// need to remove ReferenceToConsteval in the immediate invocation.
15823   if (Rec.ImmediateInvocationCandidates.size() > 1) {
15824 
15825     /// Prevent sema calls during the tree transform from adding pointers that
15826     /// are already in the sets.
15827     llvm::SaveAndRestore<bool> DisableIITracking(
15828         SemaRef.RebuildingImmediateInvocation, true);
15829 
15830     /// Prevent diagnostic during tree transfrom as they are duplicates
15831     Sema::TentativeAnalysisScope DisableDiag(SemaRef);
15832 
15833     for (auto It = Rec.ImmediateInvocationCandidates.rbegin();
15834          It != Rec.ImmediateInvocationCandidates.rend(); It++)
15835       if (!It->getInt())
15836         RemoveNestedImmediateInvocation(SemaRef, Rec, It);
15837   } else if (Rec.ImmediateInvocationCandidates.size() == 1 &&
15838              Rec.ReferenceToConsteval.size()) {
15839     struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> {
15840       llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
15841       SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {}
15842       bool VisitDeclRefExpr(DeclRefExpr *E) {
15843         DRSet.erase(E);
15844         return DRSet.size();
15845       }
15846     } Visitor(Rec.ReferenceToConsteval);
15847     Visitor.TraverseStmt(
15848         Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr());
15849   }
15850   for (auto CE : Rec.ImmediateInvocationCandidates)
15851     if (!CE.getInt())
15852       EvaluateAndDiagnoseImmediateInvocation(SemaRef, CE);
15853   for (auto DR : Rec.ReferenceToConsteval) {
15854     auto *FD = cast<FunctionDecl>(DR->getDecl());
15855     SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address)
15856         << FD;
15857     SemaRef.Diag(FD->getLocation(), diag::note_declared_at);
15858   }
15859 }
15860 
15861 void Sema::PopExpressionEvaluationContext() {
15862   ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
15863   unsigned NumTypos = Rec.NumTypos;
15864 
15865   if (!Rec.Lambdas.empty()) {
15866     using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind;
15867     if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || Rec.isUnevaluated() ||
15868         (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17)) {
15869       unsigned D;
15870       if (Rec.isUnevaluated()) {
15871         // C++11 [expr.prim.lambda]p2:
15872         //   A lambda-expression shall not appear in an unevaluated operand
15873         //   (Clause 5).
15874         D = diag::err_lambda_unevaluated_operand;
15875       } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
15876         // C++1y [expr.const]p2:
15877         //   A conditional-expression e is a core constant expression unless the
15878         //   evaluation of e, following the rules of the abstract machine, would
15879         //   evaluate [...] a lambda-expression.
15880         D = diag::err_lambda_in_constant_expression;
15881       } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
15882         // C++17 [expr.prim.lamda]p2:
15883         // A lambda-expression shall not appear [...] in a template-argument.
15884         D = diag::err_lambda_in_invalid_context;
15885       } else
15886         llvm_unreachable("Couldn't infer lambda error message.");
15887 
15888       for (const auto *L : Rec.Lambdas)
15889         Diag(L->getBeginLoc(), D);
15890     }
15891   }
15892 
15893   WarnOnPendingNoDerefs(Rec);
15894   HandleImmediateInvocations(*this, Rec);
15895 
15896   // Warn on any volatile-qualified simple-assignments that are not discarded-
15897   // value expressions nor unevaluated operands (those cases get removed from
15898   // this list by CheckUnusedVolatileAssignment).
15899   for (auto *BO : Rec.VolatileAssignmentLHSs)
15900     Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile)
15901         << BO->getType();
15902 
15903   // When are coming out of an unevaluated context, clear out any
15904   // temporaries that we may have created as part of the evaluation of
15905   // the expression in that context: they aren't relevant because they
15906   // will never be constructed.
15907   if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
15908     ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
15909                              ExprCleanupObjects.end());
15910     Cleanup = Rec.ParentCleanup;
15911     CleanupVarDeclMarking();
15912     std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
15913   // Otherwise, merge the contexts together.
15914   } else {
15915     Cleanup.mergeFrom(Rec.ParentCleanup);
15916     MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
15917                             Rec.SavedMaybeODRUseExprs.end());
15918   }
15919 
15920   // Pop the current expression evaluation context off the stack.
15921   ExprEvalContexts.pop_back();
15922 
15923   // The global expression evaluation context record is never popped.
15924   ExprEvalContexts.back().NumTypos += NumTypos;
15925 }
15926 
15927 void Sema::DiscardCleanupsInEvaluationContext() {
15928   ExprCleanupObjects.erase(
15929          ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
15930          ExprCleanupObjects.end());
15931   Cleanup.reset();
15932   MaybeODRUseExprs.clear();
15933 }
15934 
15935 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
15936   ExprResult Result = CheckPlaceholderExpr(E);
15937   if (Result.isInvalid())
15938     return ExprError();
15939   E = Result.get();
15940   if (!E->getType()->isVariablyModifiedType())
15941     return E;
15942   return TransformToPotentiallyEvaluated(E);
15943 }
15944 
15945 /// Are we in a context that is potentially constant evaluated per C++20
15946 /// [expr.const]p12?
15947 static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) {
15948   /// C++2a [expr.const]p12:
15949   //   An expression or conversion is potentially constant evaluated if it is
15950   switch (SemaRef.ExprEvalContexts.back().Context) {
15951     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
15952       // -- a manifestly constant-evaluated expression,
15953     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
15954     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
15955     case Sema::ExpressionEvaluationContext::DiscardedStatement:
15956       // -- a potentially-evaluated expression,
15957     case Sema::ExpressionEvaluationContext::UnevaluatedList:
15958       // -- an immediate subexpression of a braced-init-list,
15959 
15960       // -- [FIXME] an expression of the form & cast-expression that occurs
15961       //    within a templated entity
15962       // -- a subexpression of one of the above that is not a subexpression of
15963       // a nested unevaluated operand.
15964       return true;
15965 
15966     case Sema::ExpressionEvaluationContext::Unevaluated:
15967     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
15968       // Expressions in this context are never evaluated.
15969       return false;
15970   }
15971   llvm_unreachable("Invalid context");
15972 }
15973 
15974 /// Return true if this function has a calling convention that requires mangling
15975 /// in the size of the parameter pack.
15976 static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) {
15977   // These manglings don't do anything on non-Windows or non-x86 platforms, so
15978   // we don't need parameter type sizes.
15979   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
15980   if (!TT.isOSWindows() || !TT.isX86())
15981     return false;
15982 
15983   // If this is C++ and this isn't an extern "C" function, parameters do not
15984   // need to be complete. In this case, C++ mangling will apply, which doesn't
15985   // use the size of the parameters.
15986   if (S.getLangOpts().CPlusPlus && !FD->isExternC())
15987     return false;
15988 
15989   // Stdcall, fastcall, and vectorcall need this special treatment.
15990   CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
15991   switch (CC) {
15992   case CC_X86StdCall:
15993   case CC_X86FastCall:
15994   case CC_X86VectorCall:
15995     return true;
15996   default:
15997     break;
15998   }
15999   return false;
16000 }
16001 
16002 /// Require that all of the parameter types of function be complete. Normally,
16003 /// parameter types are only required to be complete when a function is called
16004 /// or defined, but to mangle functions with certain calling conventions, the
16005 /// mangler needs to know the size of the parameter list. In this situation,
16006 /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles
16007 /// the function as _foo@0, i.e. zero bytes of parameters, which will usually
16008 /// result in a linker error. Clang doesn't implement this behavior, and instead
16009 /// attempts to error at compile time.
16010 static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD,
16011                                                   SourceLocation Loc) {
16012   class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser {
16013     FunctionDecl *FD;
16014     ParmVarDecl *Param;
16015 
16016   public:
16017     ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param)
16018         : FD(FD), Param(Param) {}
16019 
16020     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
16021       CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
16022       StringRef CCName;
16023       switch (CC) {
16024       case CC_X86StdCall:
16025         CCName = "stdcall";
16026         break;
16027       case CC_X86FastCall:
16028         CCName = "fastcall";
16029         break;
16030       case CC_X86VectorCall:
16031         CCName = "vectorcall";
16032         break;
16033       default:
16034         llvm_unreachable("CC does not need mangling");
16035       }
16036 
16037       S.Diag(Loc, diag::err_cconv_incomplete_param_type)
16038           << Param->getDeclName() << FD->getDeclName() << CCName;
16039     }
16040   };
16041 
16042   for (ParmVarDecl *Param : FD->parameters()) {
16043     ParamIncompleteTypeDiagnoser Diagnoser(FD, Param);
16044     S.RequireCompleteType(Loc, Param->getType(), Diagnoser);
16045   }
16046 }
16047 
16048 namespace {
16049 enum class OdrUseContext {
16050   /// Declarations in this context are not odr-used.
16051   None,
16052   /// Declarations in this context are formally odr-used, but this is a
16053   /// dependent context.
16054   Dependent,
16055   /// Declarations in this context are odr-used but not actually used (yet).
16056   FormallyOdrUsed,
16057   /// Declarations in this context are used.
16058   Used
16059 };
16060 }
16061 
16062 /// Are we within a context in which references to resolved functions or to
16063 /// variables result in odr-use?
16064 static OdrUseContext isOdrUseContext(Sema &SemaRef) {
16065   OdrUseContext Result;
16066 
16067   switch (SemaRef.ExprEvalContexts.back().Context) {
16068     case Sema::ExpressionEvaluationContext::Unevaluated:
16069     case Sema::ExpressionEvaluationContext::UnevaluatedList:
16070     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
16071       return OdrUseContext::None;
16072 
16073     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
16074     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
16075       Result = OdrUseContext::Used;
16076       break;
16077 
16078     case Sema::ExpressionEvaluationContext::DiscardedStatement:
16079       Result = OdrUseContext::FormallyOdrUsed;
16080       break;
16081 
16082     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
16083       // A default argument formally results in odr-use, but doesn't actually
16084       // result in a use in any real sense until it itself is used.
16085       Result = OdrUseContext::FormallyOdrUsed;
16086       break;
16087   }
16088 
16089   if (SemaRef.CurContext->isDependentContext())
16090     return OdrUseContext::Dependent;
16091 
16092   return Result;
16093 }
16094 
16095 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
16096   return Func->isConstexpr() &&
16097          (Func->isImplicitlyInstantiable() || !Func->isUserProvided());
16098 }
16099 
16100 /// Mark a function referenced, and check whether it is odr-used
16101 /// (C++ [basic.def.odr]p2, C99 6.9p3)
16102 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
16103                                   bool MightBeOdrUse) {
16104   assert(Func && "No function?");
16105 
16106   Func->setReferenced();
16107 
16108   // Recursive functions aren't really used until they're used from some other
16109   // context.
16110   bool IsRecursiveCall = CurContext == Func;
16111 
16112   // C++11 [basic.def.odr]p3:
16113   //   A function whose name appears as a potentially-evaluated expression is
16114   //   odr-used if it is the unique lookup result or the selected member of a
16115   //   set of overloaded functions [...].
16116   //
16117   // We (incorrectly) mark overload resolution as an unevaluated context, so we
16118   // can just check that here.
16119   OdrUseContext OdrUse =
16120       MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None;
16121   if (IsRecursiveCall && OdrUse == OdrUseContext::Used)
16122     OdrUse = OdrUseContext::FormallyOdrUsed;
16123 
16124   // Trivial default constructors and destructors are never actually used.
16125   // FIXME: What about other special members?
16126   if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() &&
16127       OdrUse == OdrUseContext::Used) {
16128     if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func))
16129       if (Constructor->isDefaultConstructor())
16130         OdrUse = OdrUseContext::FormallyOdrUsed;
16131     if (isa<CXXDestructorDecl>(Func))
16132       OdrUse = OdrUseContext::FormallyOdrUsed;
16133   }
16134 
16135   // C++20 [expr.const]p12:
16136   //   A function [...] is needed for constant evaluation if it is [...] a
16137   //   constexpr function that is named by an expression that is potentially
16138   //   constant evaluated
16139   bool NeededForConstantEvaluation =
16140       isPotentiallyConstantEvaluatedContext(*this) &&
16141       isImplicitlyDefinableConstexprFunction(Func);
16142 
16143   // Determine whether we require a function definition to exist, per
16144   // C++11 [temp.inst]p3:
16145   //   Unless a function template specialization has been explicitly
16146   //   instantiated or explicitly specialized, the function template
16147   //   specialization is implicitly instantiated when the specialization is
16148   //   referenced in a context that requires a function definition to exist.
16149   // C++20 [temp.inst]p7:
16150   //   The existence of a definition of a [...] function is considered to
16151   //   affect the semantics of the program if the [...] function is needed for
16152   //   constant evaluation by an expression
16153   // C++20 [basic.def.odr]p10:
16154   //   Every program shall contain exactly one definition of every non-inline
16155   //   function or variable that is odr-used in that program outside of a
16156   //   discarded statement
16157   // C++20 [special]p1:
16158   //   The implementation will implicitly define [defaulted special members]
16159   //   if they are odr-used or needed for constant evaluation.
16160   //
16161   // Note that we skip the implicit instantiation of templates that are only
16162   // used in unused default arguments or by recursive calls to themselves.
16163   // This is formally non-conforming, but seems reasonable in practice.
16164   bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used ||
16165                                              NeededForConstantEvaluation);
16166 
16167   // C++14 [temp.expl.spec]p6:
16168   //   If a template [...] is explicitly specialized then that specialization
16169   //   shall be declared before the first use of that specialization that would
16170   //   cause an implicit instantiation to take place, in every translation unit
16171   //   in which such a use occurs
16172   if (NeedDefinition &&
16173       (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
16174        Func->getMemberSpecializationInfo()))
16175     checkSpecializationVisibility(Loc, Func);
16176 
16177   if (getLangOpts().CUDA)
16178     CheckCUDACall(Loc, Func);
16179 
16180   // If we need a definition, try to create one.
16181   if (NeedDefinition && !Func->getBody()) {
16182     runWithSufficientStackSpace(Loc, [&] {
16183       if (CXXConstructorDecl *Constructor =
16184               dyn_cast<CXXConstructorDecl>(Func)) {
16185         Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
16186         if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
16187           if (Constructor->isDefaultConstructor()) {
16188             if (Constructor->isTrivial() &&
16189                 !Constructor->hasAttr<DLLExportAttr>())
16190               return;
16191             DefineImplicitDefaultConstructor(Loc, Constructor);
16192           } else if (Constructor->isCopyConstructor()) {
16193             DefineImplicitCopyConstructor(Loc, Constructor);
16194           } else if (Constructor->isMoveConstructor()) {
16195             DefineImplicitMoveConstructor(Loc, Constructor);
16196           }
16197         } else if (Constructor->getInheritedConstructor()) {
16198           DefineInheritingConstructor(Loc, Constructor);
16199         }
16200       } else if (CXXDestructorDecl *Destructor =
16201                      dyn_cast<CXXDestructorDecl>(Func)) {
16202         Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
16203         if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
16204           if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
16205             return;
16206           DefineImplicitDestructor(Loc, Destructor);
16207         }
16208         if (Destructor->isVirtual() && getLangOpts().AppleKext)
16209           MarkVTableUsed(Loc, Destructor->getParent());
16210       } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
16211         if (MethodDecl->isOverloadedOperator() &&
16212             MethodDecl->getOverloadedOperator() == OO_Equal) {
16213           MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
16214           if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
16215             if (MethodDecl->isCopyAssignmentOperator())
16216               DefineImplicitCopyAssignment(Loc, MethodDecl);
16217             else if (MethodDecl->isMoveAssignmentOperator())
16218               DefineImplicitMoveAssignment(Loc, MethodDecl);
16219           }
16220         } else if (isa<CXXConversionDecl>(MethodDecl) &&
16221                    MethodDecl->getParent()->isLambda()) {
16222           CXXConversionDecl *Conversion =
16223               cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
16224           if (Conversion->isLambdaToBlockPointerConversion())
16225             DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
16226           else
16227             DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
16228         } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
16229           MarkVTableUsed(Loc, MethodDecl->getParent());
16230       }
16231 
16232       if (Func->isDefaulted() && !Func->isDeleted()) {
16233         DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func);
16234         if (DCK != DefaultedComparisonKind::None)
16235           DefineDefaultedComparison(Loc, Func, DCK);
16236       }
16237 
16238       // Implicit instantiation of function templates and member functions of
16239       // class templates.
16240       if (Func->isImplicitlyInstantiable()) {
16241         TemplateSpecializationKind TSK =
16242             Func->getTemplateSpecializationKindForInstantiation();
16243         SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
16244         bool FirstInstantiation = PointOfInstantiation.isInvalid();
16245         if (FirstInstantiation) {
16246           PointOfInstantiation = Loc;
16247           Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
16248         } else if (TSK != TSK_ImplicitInstantiation) {
16249           // Use the point of use as the point of instantiation, instead of the
16250           // point of explicit instantiation (which we track as the actual point
16251           // of instantiation). This gives better backtraces in diagnostics.
16252           PointOfInstantiation = Loc;
16253         }
16254 
16255         if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
16256             Func->isConstexpr()) {
16257           if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
16258               cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
16259               CodeSynthesisContexts.size())
16260             PendingLocalImplicitInstantiations.push_back(
16261                 std::make_pair(Func, PointOfInstantiation));
16262           else if (Func->isConstexpr())
16263             // Do not defer instantiations of constexpr functions, to avoid the
16264             // expression evaluator needing to call back into Sema if it sees a
16265             // call to such a function.
16266             InstantiateFunctionDefinition(PointOfInstantiation, Func);
16267           else {
16268             Func->setInstantiationIsPending(true);
16269             PendingInstantiations.push_back(
16270                 std::make_pair(Func, PointOfInstantiation));
16271             // Notify the consumer that a function was implicitly instantiated.
16272             Consumer.HandleCXXImplicitFunctionInstantiation(Func);
16273           }
16274         }
16275       } else {
16276         // Walk redefinitions, as some of them may be instantiable.
16277         for (auto i : Func->redecls()) {
16278           if (!i->isUsed(false) && i->isImplicitlyInstantiable())
16279             MarkFunctionReferenced(Loc, i, MightBeOdrUse);
16280         }
16281       }
16282     });
16283   }
16284 
16285   // C++14 [except.spec]p17:
16286   //   An exception-specification is considered to be needed when:
16287   //   - the function is odr-used or, if it appears in an unevaluated operand,
16288   //     would be odr-used if the expression were potentially-evaluated;
16289   //
16290   // Note, we do this even if MightBeOdrUse is false. That indicates that the
16291   // function is a pure virtual function we're calling, and in that case the
16292   // function was selected by overload resolution and we need to resolve its
16293   // exception specification for a different reason.
16294   const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
16295   if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
16296     ResolveExceptionSpec(Loc, FPT);
16297 
16298   // If this is the first "real" use, act on that.
16299   if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) {
16300     // Keep track of used but undefined functions.
16301     if (!Func->isDefined()) {
16302       if (mightHaveNonExternalLinkage(Func))
16303         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
16304       else if (Func->getMostRecentDecl()->isInlined() &&
16305                !LangOpts.GNUInline &&
16306                !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
16307         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
16308       else if (isExternalWithNoLinkageType(Func))
16309         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
16310     }
16311 
16312     // Some x86 Windows calling conventions mangle the size of the parameter
16313     // pack into the name. Computing the size of the parameters requires the
16314     // parameter types to be complete. Check that now.
16315     if (funcHasParameterSizeMangling(*this, Func))
16316       CheckCompleteParameterTypesForMangler(*this, Func, Loc);
16317 
16318     Func->markUsed(Context);
16319   }
16320 }
16321 
16322 /// Directly mark a variable odr-used. Given a choice, prefer to use
16323 /// MarkVariableReferenced since it does additional checks and then
16324 /// calls MarkVarDeclODRUsed.
16325 /// If the variable must be captured:
16326 ///  - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
16327 ///  - else capture it in the DeclContext that maps to the
16328 ///    *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
16329 static void
16330 MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef,
16331                    const unsigned *const FunctionScopeIndexToStopAt = nullptr) {
16332   // Keep track of used but undefined variables.
16333   // FIXME: We shouldn't suppress this warning for static data members.
16334   if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
16335       (!Var->isExternallyVisible() || Var->isInline() ||
16336        SemaRef.isExternalWithNoLinkageType(Var)) &&
16337       !(Var->isStaticDataMember() && Var->hasInit())) {
16338     SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()];
16339     if (old.isInvalid())
16340       old = Loc;
16341   }
16342   QualType CaptureType, DeclRefType;
16343   if (SemaRef.LangOpts.OpenMP)
16344     SemaRef.tryCaptureOpenMPLambdas(Var);
16345   SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit,
16346     /*EllipsisLoc*/ SourceLocation(),
16347     /*BuildAndDiagnose*/ true,
16348     CaptureType, DeclRefType,
16349     FunctionScopeIndexToStopAt);
16350 
16351   Var->markUsed(SemaRef.Context);
16352 }
16353 
16354 void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture,
16355                                              SourceLocation Loc,
16356                                              unsigned CapturingScopeIndex) {
16357   MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex);
16358 }
16359 
16360 static void
16361 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
16362                                    ValueDecl *var, DeclContext *DC) {
16363   DeclContext *VarDC = var->getDeclContext();
16364 
16365   //  If the parameter still belongs to the translation unit, then
16366   //  we're actually just using one parameter in the declaration of
16367   //  the next.
16368   if (isa<ParmVarDecl>(var) &&
16369       isa<TranslationUnitDecl>(VarDC))
16370     return;
16371 
16372   // For C code, don't diagnose about capture if we're not actually in code
16373   // right now; it's impossible to write a non-constant expression outside of
16374   // function context, so we'll get other (more useful) diagnostics later.
16375   //
16376   // For C++, things get a bit more nasty... it would be nice to suppress this
16377   // diagnostic for certain cases like using a local variable in an array bound
16378   // for a member of a local class, but the correct predicate is not obvious.
16379   if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
16380     return;
16381 
16382   unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
16383   unsigned ContextKind = 3; // unknown
16384   if (isa<CXXMethodDecl>(VarDC) &&
16385       cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
16386     ContextKind = 2;
16387   } else if (isa<FunctionDecl>(VarDC)) {
16388     ContextKind = 0;
16389   } else if (isa<BlockDecl>(VarDC)) {
16390     ContextKind = 1;
16391   }
16392 
16393   S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
16394     << var << ValueKind << ContextKind << VarDC;
16395   S.Diag(var->getLocation(), diag::note_entity_declared_at)
16396       << var;
16397 
16398   // FIXME: Add additional diagnostic info about class etc. which prevents
16399   // capture.
16400 }
16401 
16402 
16403 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
16404                                       bool &SubCapturesAreNested,
16405                                       QualType &CaptureType,
16406                                       QualType &DeclRefType) {
16407    // Check whether we've already captured it.
16408   if (CSI->CaptureMap.count(Var)) {
16409     // If we found a capture, any subcaptures are nested.
16410     SubCapturesAreNested = true;
16411 
16412     // Retrieve the capture type for this variable.
16413     CaptureType = CSI->getCapture(Var).getCaptureType();
16414 
16415     // Compute the type of an expression that refers to this variable.
16416     DeclRefType = CaptureType.getNonReferenceType();
16417 
16418     // Similarly to mutable captures in lambda, all the OpenMP captures by copy
16419     // are mutable in the sense that user can change their value - they are
16420     // private instances of the captured declarations.
16421     const Capture &Cap = CSI->getCapture(Var);
16422     if (Cap.isCopyCapture() &&
16423         !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
16424         !(isa<CapturedRegionScopeInfo>(CSI) &&
16425           cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
16426       DeclRefType.addConst();
16427     return true;
16428   }
16429   return false;
16430 }
16431 
16432 // Only block literals, captured statements, and lambda expressions can
16433 // capture; other scopes don't work.
16434 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
16435                                  SourceLocation Loc,
16436                                  const bool Diagnose, Sema &S) {
16437   if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
16438     return getLambdaAwareParentOfDeclContext(DC);
16439   else if (Var->hasLocalStorage()) {
16440     if (Diagnose)
16441        diagnoseUncapturableValueReference(S, Loc, Var, DC);
16442   }
16443   return nullptr;
16444 }
16445 
16446 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
16447 // certain types of variables (unnamed, variably modified types etc.)
16448 // so check for eligibility.
16449 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
16450                                  SourceLocation Loc,
16451                                  const bool Diagnose, Sema &S) {
16452 
16453   bool IsBlock = isa<BlockScopeInfo>(CSI);
16454   bool IsLambda = isa<LambdaScopeInfo>(CSI);
16455 
16456   // Lambdas are not allowed to capture unnamed variables
16457   // (e.g. anonymous unions).
16458   // FIXME: The C++11 rule don't actually state this explicitly, but I'm
16459   // assuming that's the intent.
16460   if (IsLambda && !Var->getDeclName()) {
16461     if (Diagnose) {
16462       S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
16463       S.Diag(Var->getLocation(), diag::note_declared_at);
16464     }
16465     return false;
16466   }
16467 
16468   // Prohibit variably-modified types in blocks; they're difficult to deal with.
16469   if (Var->getType()->isVariablyModifiedType() && IsBlock) {
16470     if (Diagnose) {
16471       S.Diag(Loc, diag::err_ref_vm_type);
16472       S.Diag(Var->getLocation(), diag::note_previous_decl)
16473         << Var->getDeclName();
16474     }
16475     return false;
16476   }
16477   // Prohibit structs with flexible array members too.
16478   // We cannot capture what is in the tail end of the struct.
16479   if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
16480     if (VTTy->getDecl()->hasFlexibleArrayMember()) {
16481       if (Diagnose) {
16482         if (IsBlock)
16483           S.Diag(Loc, diag::err_ref_flexarray_type);
16484         else
16485           S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
16486             << Var->getDeclName();
16487         S.Diag(Var->getLocation(), diag::note_previous_decl)
16488           << Var->getDeclName();
16489       }
16490       return false;
16491     }
16492   }
16493   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
16494   // Lambdas and captured statements are not allowed to capture __block
16495   // variables; they don't support the expected semantics.
16496   if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
16497     if (Diagnose) {
16498       S.Diag(Loc, diag::err_capture_block_variable)
16499         << Var->getDeclName() << !IsLambda;
16500       S.Diag(Var->getLocation(), diag::note_previous_decl)
16501         << Var->getDeclName();
16502     }
16503     return false;
16504   }
16505   // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
16506   if (S.getLangOpts().OpenCL && IsBlock &&
16507       Var->getType()->isBlockPointerType()) {
16508     if (Diagnose)
16509       S.Diag(Loc, diag::err_opencl_block_ref_block);
16510     return false;
16511   }
16512 
16513   return true;
16514 }
16515 
16516 // Returns true if the capture by block was successful.
16517 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
16518                                  SourceLocation Loc,
16519                                  const bool BuildAndDiagnose,
16520                                  QualType &CaptureType,
16521                                  QualType &DeclRefType,
16522                                  const bool Nested,
16523                                  Sema &S, bool Invalid) {
16524   bool ByRef = false;
16525 
16526   // Blocks are not allowed to capture arrays, excepting OpenCL.
16527   // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
16528   // (decayed to pointers).
16529   if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
16530     if (BuildAndDiagnose) {
16531       S.Diag(Loc, diag::err_ref_array_type);
16532       S.Diag(Var->getLocation(), diag::note_previous_decl)
16533       << Var->getDeclName();
16534       Invalid = true;
16535     } else {
16536       return false;
16537     }
16538   }
16539 
16540   // Forbid the block-capture of autoreleasing variables.
16541   if (!Invalid &&
16542       CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
16543     if (BuildAndDiagnose) {
16544       S.Diag(Loc, diag::err_arc_autoreleasing_capture)
16545         << /*block*/ 0;
16546       S.Diag(Var->getLocation(), diag::note_previous_decl)
16547         << Var->getDeclName();
16548       Invalid = true;
16549     } else {
16550       return false;
16551     }
16552   }
16553 
16554   // Warn about implicitly autoreleasing indirect parameters captured by blocks.
16555   if (const auto *PT = CaptureType->getAs<PointerType>()) {
16556     QualType PointeeTy = PT->getPointeeType();
16557 
16558     if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() &&
16559         PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
16560         !S.Context.hasDirectOwnershipQualifier(PointeeTy)) {
16561       if (BuildAndDiagnose) {
16562         SourceLocation VarLoc = Var->getLocation();
16563         S.Diag(Loc, diag::warn_block_capture_autoreleasing);
16564         S.Diag(VarLoc, diag::note_declare_parameter_strong);
16565       }
16566     }
16567   }
16568 
16569   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
16570   if (HasBlocksAttr || CaptureType->isReferenceType() ||
16571       (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) {
16572     // Block capture by reference does not change the capture or
16573     // declaration reference types.
16574     ByRef = true;
16575   } else {
16576     // Block capture by copy introduces 'const'.
16577     CaptureType = CaptureType.getNonReferenceType().withConst();
16578     DeclRefType = CaptureType;
16579   }
16580 
16581   // Actually capture the variable.
16582   if (BuildAndDiagnose)
16583     BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(),
16584                     CaptureType, Invalid);
16585 
16586   return !Invalid;
16587 }
16588 
16589 
16590 /// Capture the given variable in the captured region.
16591 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
16592                                     VarDecl *Var,
16593                                     SourceLocation Loc,
16594                                     const bool BuildAndDiagnose,
16595                                     QualType &CaptureType,
16596                                     QualType &DeclRefType,
16597                                     const bool RefersToCapturedVariable,
16598                                     Sema &S, bool Invalid) {
16599   // By default, capture variables by reference.
16600   bool ByRef = true;
16601   // Using an LValue reference type is consistent with Lambdas (see below).
16602   if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
16603     if (S.isOpenMPCapturedDecl(Var)) {
16604       bool HasConst = DeclRefType.isConstQualified();
16605       DeclRefType = DeclRefType.getUnqualifiedType();
16606       // Don't lose diagnostics about assignments to const.
16607       if (HasConst)
16608         DeclRefType.addConst();
16609     }
16610     // Do not capture firstprivates in tasks.
16611     if (S.isOpenMPPrivateDecl(Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel) !=
16612         OMPC_unknown)
16613       return true;
16614     ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel,
16615                                     RSI->OpenMPCaptureLevel);
16616   }
16617 
16618   if (ByRef)
16619     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
16620   else
16621     CaptureType = DeclRefType;
16622 
16623   // Actually capture the variable.
16624   if (BuildAndDiagnose)
16625     RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable,
16626                     Loc, SourceLocation(), CaptureType, Invalid);
16627 
16628   return !Invalid;
16629 }
16630 
16631 /// Capture the given variable in the lambda.
16632 static bool captureInLambda(LambdaScopeInfo *LSI,
16633                             VarDecl *Var,
16634                             SourceLocation Loc,
16635                             const bool BuildAndDiagnose,
16636                             QualType &CaptureType,
16637                             QualType &DeclRefType,
16638                             const bool RefersToCapturedVariable,
16639                             const Sema::TryCaptureKind Kind,
16640                             SourceLocation EllipsisLoc,
16641                             const bool IsTopScope,
16642                             Sema &S, bool Invalid) {
16643   // Determine whether we are capturing by reference or by value.
16644   bool ByRef = false;
16645   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
16646     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
16647   } else {
16648     ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
16649   }
16650 
16651   // Compute the type of the field that will capture this variable.
16652   if (ByRef) {
16653     // C++11 [expr.prim.lambda]p15:
16654     //   An entity is captured by reference if it is implicitly or
16655     //   explicitly captured but not captured by copy. It is
16656     //   unspecified whether additional unnamed non-static data
16657     //   members are declared in the closure type for entities
16658     //   captured by reference.
16659     //
16660     // FIXME: It is not clear whether we want to build an lvalue reference
16661     // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
16662     // to do the former, while EDG does the latter. Core issue 1249 will
16663     // clarify, but for now we follow GCC because it's a more permissive and
16664     // easily defensible position.
16665     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
16666   } else {
16667     // C++11 [expr.prim.lambda]p14:
16668     //   For each entity captured by copy, an unnamed non-static
16669     //   data member is declared in the closure type. The
16670     //   declaration order of these members is unspecified. The type
16671     //   of such a data member is the type of the corresponding
16672     //   captured entity if the entity is not a reference to an
16673     //   object, or the referenced type otherwise. [Note: If the
16674     //   captured entity is a reference to a function, the
16675     //   corresponding data member is also a reference to a
16676     //   function. - end note ]
16677     if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
16678       if (!RefType->getPointeeType()->isFunctionType())
16679         CaptureType = RefType->getPointeeType();
16680     }
16681 
16682     // Forbid the lambda copy-capture of autoreleasing variables.
16683     if (!Invalid &&
16684         CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
16685       if (BuildAndDiagnose) {
16686         S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
16687         S.Diag(Var->getLocation(), diag::note_previous_decl)
16688           << Var->getDeclName();
16689         Invalid = true;
16690       } else {
16691         return false;
16692       }
16693     }
16694 
16695     // Make sure that by-copy captures are of a complete and non-abstract type.
16696     if (!Invalid && BuildAndDiagnose) {
16697       if (!CaptureType->isDependentType() &&
16698           S.RequireCompleteSizedType(
16699               Loc, CaptureType,
16700               diag::err_capture_of_incomplete_or_sizeless_type,
16701               Var->getDeclName()))
16702         Invalid = true;
16703       else if (S.RequireNonAbstractType(Loc, CaptureType,
16704                                         diag::err_capture_of_abstract_type))
16705         Invalid = true;
16706     }
16707   }
16708 
16709   // Compute the type of a reference to this captured variable.
16710   if (ByRef)
16711     DeclRefType = CaptureType.getNonReferenceType();
16712   else {
16713     // C++ [expr.prim.lambda]p5:
16714     //   The closure type for a lambda-expression has a public inline
16715     //   function call operator [...]. This function call operator is
16716     //   declared const (9.3.1) if and only if the lambda-expression's
16717     //   parameter-declaration-clause is not followed by mutable.
16718     DeclRefType = CaptureType.getNonReferenceType();
16719     if (!LSI->Mutable && !CaptureType->isReferenceType())
16720       DeclRefType.addConst();
16721   }
16722 
16723   // Add the capture.
16724   if (BuildAndDiagnose)
16725     LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable,
16726                     Loc, EllipsisLoc, CaptureType, Invalid);
16727 
16728   return !Invalid;
16729 }
16730 
16731 bool Sema::tryCaptureVariable(
16732     VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
16733     SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
16734     QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
16735   // An init-capture is notionally from the context surrounding its
16736   // declaration, but its parent DC is the lambda class.
16737   DeclContext *VarDC = Var->getDeclContext();
16738   if (Var->isInitCapture())
16739     VarDC = VarDC->getParent();
16740 
16741   DeclContext *DC = CurContext;
16742   const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
16743       ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
16744   // We need to sync up the Declaration Context with the
16745   // FunctionScopeIndexToStopAt
16746   if (FunctionScopeIndexToStopAt) {
16747     unsigned FSIndex = FunctionScopes.size() - 1;
16748     while (FSIndex != MaxFunctionScopesIndex) {
16749       DC = getLambdaAwareParentOfDeclContext(DC);
16750       --FSIndex;
16751     }
16752   }
16753 
16754 
16755   // If the variable is declared in the current context, there is no need to
16756   // capture it.
16757   if (VarDC == DC) return true;
16758 
16759   // Capture global variables if it is required to use private copy of this
16760   // variable.
16761   bool IsGlobal = !Var->hasLocalStorage();
16762   if (IsGlobal &&
16763       !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true,
16764                                                 MaxFunctionScopesIndex)))
16765     return true;
16766   Var = Var->getCanonicalDecl();
16767 
16768   // Walk up the stack to determine whether we can capture the variable,
16769   // performing the "simple" checks that don't depend on type. We stop when
16770   // we've either hit the declared scope of the variable or find an existing
16771   // capture of that variable.  We start from the innermost capturing-entity
16772   // (the DC) and ensure that all intervening capturing-entities
16773   // (blocks/lambdas etc.) between the innermost capturer and the variable`s
16774   // declcontext can either capture the variable or have already captured
16775   // the variable.
16776   CaptureType = Var->getType();
16777   DeclRefType = CaptureType.getNonReferenceType();
16778   bool Nested = false;
16779   bool Explicit = (Kind != TryCapture_Implicit);
16780   unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
16781   do {
16782     // Only block literals, captured statements, and lambda expressions can
16783     // capture; other scopes don't work.
16784     DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
16785                                                               ExprLoc,
16786                                                               BuildAndDiagnose,
16787                                                               *this);
16788     // We need to check for the parent *first* because, if we *have*
16789     // private-captured a global variable, we need to recursively capture it in
16790     // intermediate blocks, lambdas, etc.
16791     if (!ParentDC) {
16792       if (IsGlobal) {
16793         FunctionScopesIndex = MaxFunctionScopesIndex - 1;
16794         break;
16795       }
16796       return true;
16797     }
16798 
16799     FunctionScopeInfo  *FSI = FunctionScopes[FunctionScopesIndex];
16800     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
16801 
16802 
16803     // Check whether we've already captured it.
16804     if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
16805                                              DeclRefType)) {
16806       CSI->getCapture(Var).markUsed(BuildAndDiagnose);
16807       break;
16808     }
16809     // If we are instantiating a generic lambda call operator body,
16810     // we do not want to capture new variables.  What was captured
16811     // during either a lambdas transformation or initial parsing
16812     // should be used.
16813     if (isGenericLambdaCallOperatorSpecialization(DC)) {
16814       if (BuildAndDiagnose) {
16815         LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
16816         if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
16817           Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
16818           Diag(Var->getLocation(), diag::note_previous_decl)
16819              << Var->getDeclName();
16820           Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
16821         } else
16822           diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
16823       }
16824       return true;
16825     }
16826 
16827     // Try to capture variable-length arrays types.
16828     if (Var->getType()->isVariablyModifiedType()) {
16829       // We're going to walk down into the type and look for VLA
16830       // expressions.
16831       QualType QTy = Var->getType();
16832       if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
16833         QTy = PVD->getOriginalType();
16834       captureVariablyModifiedType(Context, QTy, CSI);
16835     }
16836 
16837     if (getLangOpts().OpenMP) {
16838       if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
16839         // OpenMP private variables should not be captured in outer scope, so
16840         // just break here. Similarly, global variables that are captured in a
16841         // target region should not be captured outside the scope of the region.
16842         if (RSI->CapRegionKind == CR_OpenMP) {
16843           OpenMPClauseKind IsOpenMPPrivateDecl = isOpenMPPrivateDecl(
16844               Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel);
16845           // If the variable is private (i.e. not captured) and has variably
16846           // modified type, we still need to capture the type for correct
16847           // codegen in all regions, associated with the construct. Currently,
16848           // it is captured in the innermost captured region only.
16849           if (IsOpenMPPrivateDecl != OMPC_unknown &&
16850               Var->getType()->isVariablyModifiedType()) {
16851             QualType QTy = Var->getType();
16852             if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
16853               QTy = PVD->getOriginalType();
16854             for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel);
16855                  I < E; ++I) {
16856               auto *OuterRSI = cast<CapturedRegionScopeInfo>(
16857                   FunctionScopes[FunctionScopesIndex - I]);
16858               assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel &&
16859                      "Wrong number of captured regions associated with the "
16860                      "OpenMP construct.");
16861               captureVariablyModifiedType(Context, QTy, OuterRSI);
16862             }
16863           }
16864           bool IsTargetCap =
16865               IsOpenMPPrivateDecl != OMPC_private &&
16866               isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel,
16867                                          RSI->OpenMPCaptureLevel);
16868           // Do not capture global if it is not privatized in outer regions.
16869           bool IsGlobalCap =
16870               IsGlobal && isOpenMPGlobalCapturedDecl(Var, RSI->OpenMPLevel,
16871                                                      RSI->OpenMPCaptureLevel);
16872 
16873           // When we detect target captures we are looking from inside the
16874           // target region, therefore we need to propagate the capture from the
16875           // enclosing region. Therefore, the capture is not initially nested.
16876           if (IsTargetCap)
16877             adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel);
16878 
16879           if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private ||
16880               (IsGlobal && !IsGlobalCap)) {
16881             Nested = !IsTargetCap;
16882             DeclRefType = DeclRefType.getUnqualifiedType();
16883             CaptureType = Context.getLValueReferenceType(DeclRefType);
16884             break;
16885           }
16886         }
16887       }
16888     }
16889     if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
16890       // No capture-default, and this is not an explicit capture
16891       // so cannot capture this variable.
16892       if (BuildAndDiagnose) {
16893         Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
16894         Diag(Var->getLocation(), diag::note_previous_decl)
16895           << Var->getDeclName();
16896         if (cast<LambdaScopeInfo>(CSI)->Lambda)
16897           Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getBeginLoc(),
16898                diag::note_lambda_decl);
16899         // FIXME: If we error out because an outer lambda can not implicitly
16900         // capture a variable that an inner lambda explicitly captures, we
16901         // should have the inner lambda do the explicit capture - because
16902         // it makes for cleaner diagnostics later.  This would purely be done
16903         // so that the diagnostic does not misleadingly claim that a variable
16904         // can not be captured by a lambda implicitly even though it is captured
16905         // explicitly.  Suggestion:
16906         //  - create const bool VariableCaptureWasInitiallyExplicit = Explicit
16907         //    at the function head
16908         //  - cache the StartingDeclContext - this must be a lambda
16909         //  - captureInLambda in the innermost lambda the variable.
16910       }
16911       return true;
16912     }
16913 
16914     FunctionScopesIndex--;
16915     DC = ParentDC;
16916     Explicit = false;
16917   } while (!VarDC->Equals(DC));
16918 
16919   // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
16920   // computing the type of the capture at each step, checking type-specific
16921   // requirements, and adding captures if requested.
16922   // If the variable had already been captured previously, we start capturing
16923   // at the lambda nested within that one.
16924   bool Invalid = false;
16925   for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
16926        ++I) {
16927     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
16928 
16929     // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
16930     // certain types of variables (unnamed, variably modified types etc.)
16931     // so check for eligibility.
16932     if (!Invalid)
16933       Invalid =
16934           !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this);
16935 
16936     // After encountering an error, if we're actually supposed to capture, keep
16937     // capturing in nested contexts to suppress any follow-on diagnostics.
16938     if (Invalid && !BuildAndDiagnose)
16939       return true;
16940 
16941     if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
16942       Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
16943                                DeclRefType, Nested, *this, Invalid);
16944       Nested = true;
16945     } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
16946       Invalid = !captureInCapturedRegion(RSI, Var, ExprLoc, BuildAndDiagnose,
16947                                          CaptureType, DeclRefType, Nested,
16948                                          *this, Invalid);
16949       Nested = true;
16950     } else {
16951       LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
16952       Invalid =
16953           !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
16954                            DeclRefType, Nested, Kind, EllipsisLoc,
16955                            /*IsTopScope*/ I == N - 1, *this, Invalid);
16956       Nested = true;
16957     }
16958 
16959     if (Invalid && !BuildAndDiagnose)
16960       return true;
16961   }
16962   return Invalid;
16963 }
16964 
16965 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
16966                               TryCaptureKind Kind, SourceLocation EllipsisLoc) {
16967   QualType CaptureType;
16968   QualType DeclRefType;
16969   return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
16970                             /*BuildAndDiagnose=*/true, CaptureType,
16971                             DeclRefType, nullptr);
16972 }
16973 
16974 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
16975   QualType CaptureType;
16976   QualType DeclRefType;
16977   return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
16978                              /*BuildAndDiagnose=*/false, CaptureType,
16979                              DeclRefType, nullptr);
16980 }
16981 
16982 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
16983   QualType CaptureType;
16984   QualType DeclRefType;
16985 
16986   // Determine whether we can capture this variable.
16987   if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
16988                          /*BuildAndDiagnose=*/false, CaptureType,
16989                          DeclRefType, nullptr))
16990     return QualType();
16991 
16992   return DeclRefType;
16993 }
16994 
16995 namespace {
16996 // Helper to copy the template arguments from a DeclRefExpr or MemberExpr.
16997 // The produced TemplateArgumentListInfo* points to data stored within this
16998 // object, so should only be used in contexts where the pointer will not be
16999 // used after the CopiedTemplateArgs object is destroyed.
17000 class CopiedTemplateArgs {
17001   bool HasArgs;
17002   TemplateArgumentListInfo TemplateArgStorage;
17003 public:
17004   template<typename RefExpr>
17005   CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) {
17006     if (HasArgs)
17007       E->copyTemplateArgumentsInto(TemplateArgStorage);
17008   }
17009   operator TemplateArgumentListInfo*()
17010 #ifdef __has_cpp_attribute
17011 #if __has_cpp_attribute(clang::lifetimebound)
17012   [[clang::lifetimebound]]
17013 #endif
17014 #endif
17015   {
17016     return HasArgs ? &TemplateArgStorage : nullptr;
17017   }
17018 };
17019 }
17020 
17021 /// Walk the set of potential results of an expression and mark them all as
17022 /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason.
17023 ///
17024 /// \return A new expression if we found any potential results, ExprEmpty() if
17025 ///         not, and ExprError() if we diagnosed an error.
17026 static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E,
17027                                                       NonOdrUseReason NOUR) {
17028   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
17029   // an object that satisfies the requirements for appearing in a
17030   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
17031   // is immediately applied."  This function handles the lvalue-to-rvalue
17032   // conversion part.
17033   //
17034   // If we encounter a node that claims to be an odr-use but shouldn't be, we
17035   // transform it into the relevant kind of non-odr-use node and rebuild the
17036   // tree of nodes leading to it.
17037   //
17038   // This is a mini-TreeTransform that only transforms a restricted subset of
17039   // nodes (and only certain operands of them).
17040 
17041   // Rebuild a subexpression.
17042   auto Rebuild = [&](Expr *Sub) {
17043     return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR);
17044   };
17045 
17046   // Check whether a potential result satisfies the requirements of NOUR.
17047   auto IsPotentialResultOdrUsed = [&](NamedDecl *D) {
17048     // Any entity other than a VarDecl is always odr-used whenever it's named
17049     // in a potentially-evaluated expression.
17050     auto *VD = dyn_cast<VarDecl>(D);
17051     if (!VD)
17052       return true;
17053 
17054     // C++2a [basic.def.odr]p4:
17055     //   A variable x whose name appears as a potentially-evalauted expression
17056     //   e is odr-used by e unless
17057     //   -- x is a reference that is usable in constant expressions, or
17058     //   -- x is a variable of non-reference type that is usable in constant
17059     //      expressions and has no mutable subobjects, and e is an element of
17060     //      the set of potential results of an expression of
17061     //      non-volatile-qualified non-class type to which the lvalue-to-rvalue
17062     //      conversion is applied, or
17063     //   -- x is a variable of non-reference type, and e is an element of the
17064     //      set of potential results of a discarded-value expression to which
17065     //      the lvalue-to-rvalue conversion is not applied
17066     //
17067     // We check the first bullet and the "potentially-evaluated" condition in
17068     // BuildDeclRefExpr. We check the type requirements in the second bullet
17069     // in CheckLValueToRValueConversionOperand below.
17070     switch (NOUR) {
17071     case NOUR_None:
17072     case NOUR_Unevaluated:
17073       llvm_unreachable("unexpected non-odr-use-reason");
17074 
17075     case NOUR_Constant:
17076       // Constant references were handled when they were built.
17077       if (VD->getType()->isReferenceType())
17078         return true;
17079       if (auto *RD = VD->getType()->getAsCXXRecordDecl())
17080         if (RD->hasMutableFields())
17081           return true;
17082       if (!VD->isUsableInConstantExpressions(S.Context))
17083         return true;
17084       break;
17085 
17086     case NOUR_Discarded:
17087       if (VD->getType()->isReferenceType())
17088         return true;
17089       break;
17090     }
17091     return false;
17092   };
17093 
17094   // Mark that this expression does not constitute an odr-use.
17095   auto MarkNotOdrUsed = [&] {
17096     S.MaybeODRUseExprs.erase(E);
17097     if (LambdaScopeInfo *LSI = S.getCurLambda())
17098       LSI->markVariableExprAsNonODRUsed(E);
17099   };
17100 
17101   // C++2a [basic.def.odr]p2:
17102   //   The set of potential results of an expression e is defined as follows:
17103   switch (E->getStmtClass()) {
17104   //   -- If e is an id-expression, ...
17105   case Expr::DeclRefExprClass: {
17106     auto *DRE = cast<DeclRefExpr>(E);
17107     if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl()))
17108       break;
17109 
17110     // Rebuild as a non-odr-use DeclRefExpr.
17111     MarkNotOdrUsed();
17112     return DeclRefExpr::Create(
17113         S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(),
17114         DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(),
17115         DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(),
17116         DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR);
17117   }
17118 
17119   case Expr::FunctionParmPackExprClass: {
17120     auto *FPPE = cast<FunctionParmPackExpr>(E);
17121     // If any of the declarations in the pack is odr-used, then the expression
17122     // as a whole constitutes an odr-use.
17123     for (VarDecl *D : *FPPE)
17124       if (IsPotentialResultOdrUsed(D))
17125         return ExprEmpty();
17126 
17127     // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice,
17128     // nothing cares about whether we marked this as an odr-use, but it might
17129     // be useful for non-compiler tools.
17130     MarkNotOdrUsed();
17131     break;
17132   }
17133 
17134   //   -- If e is a subscripting operation with an array operand...
17135   case Expr::ArraySubscriptExprClass: {
17136     auto *ASE = cast<ArraySubscriptExpr>(E);
17137     Expr *OldBase = ASE->getBase()->IgnoreImplicit();
17138     if (!OldBase->getType()->isArrayType())
17139       break;
17140     ExprResult Base = Rebuild(OldBase);
17141     if (!Base.isUsable())
17142       return Base;
17143     Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS();
17144     Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS();
17145     SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored.
17146     return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS,
17147                                      ASE->getRBracketLoc());
17148   }
17149 
17150   case Expr::MemberExprClass: {
17151     auto *ME = cast<MemberExpr>(E);
17152     // -- If e is a class member access expression [...] naming a non-static
17153     //    data member...
17154     if (isa<FieldDecl>(ME->getMemberDecl())) {
17155       ExprResult Base = Rebuild(ME->getBase());
17156       if (!Base.isUsable())
17157         return Base;
17158       return MemberExpr::Create(
17159           S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(),
17160           ME->getQualifierLoc(), ME->getTemplateKeywordLoc(),
17161           ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(),
17162           CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(),
17163           ME->getObjectKind(), ME->isNonOdrUse());
17164     }
17165 
17166     if (ME->getMemberDecl()->isCXXInstanceMember())
17167       break;
17168 
17169     // -- If e is a class member access expression naming a static data member,
17170     //    ...
17171     if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl()))
17172       break;
17173 
17174     // Rebuild as a non-odr-use MemberExpr.
17175     MarkNotOdrUsed();
17176     return MemberExpr::Create(
17177         S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(),
17178         ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(),
17179         ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME),
17180         ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR);
17181     return ExprEmpty();
17182   }
17183 
17184   case Expr::BinaryOperatorClass: {
17185     auto *BO = cast<BinaryOperator>(E);
17186     Expr *LHS = BO->getLHS();
17187     Expr *RHS = BO->getRHS();
17188     // -- If e is a pointer-to-member expression of the form e1 .* e2 ...
17189     if (BO->getOpcode() == BO_PtrMemD) {
17190       ExprResult Sub = Rebuild(LHS);
17191       if (!Sub.isUsable())
17192         return Sub;
17193       LHS = Sub.get();
17194     //   -- If e is a comma expression, ...
17195     } else if (BO->getOpcode() == BO_Comma) {
17196       ExprResult Sub = Rebuild(RHS);
17197       if (!Sub.isUsable())
17198         return Sub;
17199       RHS = Sub.get();
17200     } else {
17201       break;
17202     }
17203     return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(),
17204                         LHS, RHS);
17205   }
17206 
17207   //   -- If e has the form (e1)...
17208   case Expr::ParenExprClass: {
17209     auto *PE = cast<ParenExpr>(E);
17210     ExprResult Sub = Rebuild(PE->getSubExpr());
17211     if (!Sub.isUsable())
17212       return Sub;
17213     return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get());
17214   }
17215 
17216   //   -- If e is a glvalue conditional expression, ...
17217   // We don't apply this to a binary conditional operator. FIXME: Should we?
17218   case Expr::ConditionalOperatorClass: {
17219     auto *CO = cast<ConditionalOperator>(E);
17220     ExprResult LHS = Rebuild(CO->getLHS());
17221     if (LHS.isInvalid())
17222       return ExprError();
17223     ExprResult RHS = Rebuild(CO->getRHS());
17224     if (RHS.isInvalid())
17225       return ExprError();
17226     if (!LHS.isUsable() && !RHS.isUsable())
17227       return ExprEmpty();
17228     if (!LHS.isUsable())
17229       LHS = CO->getLHS();
17230     if (!RHS.isUsable())
17231       RHS = CO->getRHS();
17232     return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(),
17233                                 CO->getCond(), LHS.get(), RHS.get());
17234   }
17235 
17236   // [Clang extension]
17237   //   -- If e has the form __extension__ e1...
17238   case Expr::UnaryOperatorClass: {
17239     auto *UO = cast<UnaryOperator>(E);
17240     if (UO->getOpcode() != UO_Extension)
17241       break;
17242     ExprResult Sub = Rebuild(UO->getSubExpr());
17243     if (!Sub.isUsable())
17244       return Sub;
17245     return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension,
17246                           Sub.get());
17247   }
17248 
17249   // [Clang extension]
17250   //   -- If e has the form _Generic(...), the set of potential results is the
17251   //      union of the sets of potential results of the associated expressions.
17252   case Expr::GenericSelectionExprClass: {
17253     auto *GSE = cast<GenericSelectionExpr>(E);
17254 
17255     SmallVector<Expr *, 4> AssocExprs;
17256     bool AnyChanged = false;
17257     for (Expr *OrigAssocExpr : GSE->getAssocExprs()) {
17258       ExprResult AssocExpr = Rebuild(OrigAssocExpr);
17259       if (AssocExpr.isInvalid())
17260         return ExprError();
17261       if (AssocExpr.isUsable()) {
17262         AssocExprs.push_back(AssocExpr.get());
17263         AnyChanged = true;
17264       } else {
17265         AssocExprs.push_back(OrigAssocExpr);
17266       }
17267     }
17268 
17269     return AnyChanged ? S.CreateGenericSelectionExpr(
17270                             GSE->getGenericLoc(), GSE->getDefaultLoc(),
17271                             GSE->getRParenLoc(), GSE->getControllingExpr(),
17272                             GSE->getAssocTypeSourceInfos(), AssocExprs)
17273                       : ExprEmpty();
17274   }
17275 
17276   // [Clang extension]
17277   //   -- If e has the form __builtin_choose_expr(...), the set of potential
17278   //      results is the union of the sets of potential results of the
17279   //      second and third subexpressions.
17280   case Expr::ChooseExprClass: {
17281     auto *CE = cast<ChooseExpr>(E);
17282 
17283     ExprResult LHS = Rebuild(CE->getLHS());
17284     if (LHS.isInvalid())
17285       return ExprError();
17286 
17287     ExprResult RHS = Rebuild(CE->getLHS());
17288     if (RHS.isInvalid())
17289       return ExprError();
17290 
17291     if (!LHS.get() && !RHS.get())
17292       return ExprEmpty();
17293     if (!LHS.isUsable())
17294       LHS = CE->getLHS();
17295     if (!RHS.isUsable())
17296       RHS = CE->getRHS();
17297 
17298     return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(),
17299                              RHS.get(), CE->getRParenLoc());
17300   }
17301 
17302   // Step through non-syntactic nodes.
17303   case Expr::ConstantExprClass: {
17304     auto *CE = cast<ConstantExpr>(E);
17305     ExprResult Sub = Rebuild(CE->getSubExpr());
17306     if (!Sub.isUsable())
17307       return Sub;
17308     return ConstantExpr::Create(S.Context, Sub.get());
17309   }
17310 
17311   // We could mostly rely on the recursive rebuilding to rebuild implicit
17312   // casts, but not at the top level, so rebuild them here.
17313   case Expr::ImplicitCastExprClass: {
17314     auto *ICE = cast<ImplicitCastExpr>(E);
17315     // Only step through the narrow set of cast kinds we expect to encounter.
17316     // Anything else suggests we've left the region in which potential results
17317     // can be found.
17318     switch (ICE->getCastKind()) {
17319     case CK_NoOp:
17320     case CK_DerivedToBase:
17321     case CK_UncheckedDerivedToBase: {
17322       ExprResult Sub = Rebuild(ICE->getSubExpr());
17323       if (!Sub.isUsable())
17324         return Sub;
17325       CXXCastPath Path(ICE->path());
17326       return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(),
17327                                  ICE->getValueKind(), &Path);
17328     }
17329 
17330     default:
17331       break;
17332     }
17333     break;
17334   }
17335 
17336   default:
17337     break;
17338   }
17339 
17340   // Can't traverse through this node. Nothing to do.
17341   return ExprEmpty();
17342 }
17343 
17344 ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) {
17345   // Check whether the operand is or contains an object of non-trivial C union
17346   // type.
17347   if (E->getType().isVolatileQualified() &&
17348       (E->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
17349        E->getType().hasNonTrivialToPrimitiveCopyCUnion()))
17350     checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
17351                           Sema::NTCUC_LValueToRValueVolatile,
17352                           NTCUK_Destruct|NTCUK_Copy);
17353 
17354   // C++2a [basic.def.odr]p4:
17355   //   [...] an expression of non-volatile-qualified non-class type to which
17356   //   the lvalue-to-rvalue conversion is applied [...]
17357   if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>())
17358     return E;
17359 
17360   ExprResult Result =
17361       rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant);
17362   if (Result.isInvalid())
17363     return ExprError();
17364   return Result.get() ? Result : E;
17365 }
17366 
17367 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
17368   Res = CorrectDelayedTyposInExpr(Res);
17369 
17370   if (!Res.isUsable())
17371     return Res;
17372 
17373   // If a constant-expression is a reference to a variable where we delay
17374   // deciding whether it is an odr-use, just assume we will apply the
17375   // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
17376   // (a non-type template argument), we have special handling anyway.
17377   return CheckLValueToRValueConversionOperand(Res.get());
17378 }
17379 
17380 void Sema::CleanupVarDeclMarking() {
17381   // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
17382   // call.
17383   MaybeODRUseExprSet LocalMaybeODRUseExprs;
17384   std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs);
17385 
17386   for (Expr *E : LocalMaybeODRUseExprs) {
17387     if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
17388       MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()),
17389                          DRE->getLocation(), *this);
17390     } else if (auto *ME = dyn_cast<MemberExpr>(E)) {
17391       MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(),
17392                          *this);
17393     } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) {
17394       for (VarDecl *VD : *FP)
17395         MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this);
17396     } else {
17397       llvm_unreachable("Unexpected expression");
17398     }
17399   }
17400 
17401   assert(MaybeODRUseExprs.empty() &&
17402          "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?");
17403 }
17404 
17405 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
17406                                     VarDecl *Var, Expr *E) {
17407   assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||
17408           isa<FunctionParmPackExpr>(E)) &&
17409          "Invalid Expr argument to DoMarkVarDeclReferenced");
17410   Var->setReferenced();
17411 
17412   if (Var->isInvalidDecl())
17413     return;
17414 
17415   auto *MSI = Var->getMemberSpecializationInfo();
17416   TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind()
17417                                        : Var->getTemplateSpecializationKind();
17418 
17419   OdrUseContext OdrUse = isOdrUseContext(SemaRef);
17420   bool UsableInConstantExpr =
17421       Var->mightBeUsableInConstantExpressions(SemaRef.Context);
17422 
17423   // C++20 [expr.const]p12:
17424   //   A variable [...] is needed for constant evaluation if it is [...] a
17425   //   variable whose name appears as a potentially constant evaluated
17426   //   expression that is either a contexpr variable or is of non-volatile
17427   //   const-qualified integral type or of reference type
17428   bool NeededForConstantEvaluation =
17429       isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr;
17430 
17431   bool NeedDefinition =
17432       OdrUse == OdrUseContext::Used || NeededForConstantEvaluation;
17433 
17434   VarTemplateSpecializationDecl *VarSpec =
17435       dyn_cast<VarTemplateSpecializationDecl>(Var);
17436   assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
17437          "Can't instantiate a partial template specialization.");
17438 
17439   // If this might be a member specialization of a static data member, check
17440   // the specialization is visible. We already did the checks for variable
17441   // template specializations when we created them.
17442   if (NeedDefinition && TSK != TSK_Undeclared &&
17443       !isa<VarTemplateSpecializationDecl>(Var))
17444     SemaRef.checkSpecializationVisibility(Loc, Var);
17445 
17446   // Perform implicit instantiation of static data members, static data member
17447   // templates of class templates, and variable template specializations. Delay
17448   // instantiations of variable templates, except for those that could be used
17449   // in a constant expression.
17450   if (NeedDefinition && isTemplateInstantiation(TSK)) {
17451     // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
17452     // instantiation declaration if a variable is usable in a constant
17453     // expression (among other cases).
17454     bool TryInstantiating =
17455         TSK == TSK_ImplicitInstantiation ||
17456         (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
17457 
17458     if (TryInstantiating) {
17459       SourceLocation PointOfInstantiation =
17460           MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation();
17461       bool FirstInstantiation = PointOfInstantiation.isInvalid();
17462       if (FirstInstantiation) {
17463         PointOfInstantiation = Loc;
17464         if (MSI)
17465           MSI->setPointOfInstantiation(PointOfInstantiation);
17466         else
17467           Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
17468       }
17469 
17470       bool InstantiationDependent = false;
17471       bool IsNonDependent =
17472           VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
17473                         VarSpec->getTemplateArgsInfo(), InstantiationDependent)
17474                   : true;
17475 
17476       // Do not instantiate specializations that are still type-dependent.
17477       if (IsNonDependent) {
17478         if (UsableInConstantExpr) {
17479           // Do not defer instantiations of variables that could be used in a
17480           // constant expression.
17481           SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] {
17482             SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
17483           });
17484         } else if (FirstInstantiation ||
17485                    isa<VarTemplateSpecializationDecl>(Var)) {
17486           // FIXME: For a specialization of a variable template, we don't
17487           // distinguish between "declaration and type implicitly instantiated"
17488           // and "implicit instantiation of definition requested", so we have
17489           // no direct way to avoid enqueueing the pending instantiation
17490           // multiple times.
17491           SemaRef.PendingInstantiations
17492               .push_back(std::make_pair(Var, PointOfInstantiation));
17493         }
17494       }
17495     }
17496   }
17497 
17498   // C++2a [basic.def.odr]p4:
17499   //   A variable x whose name appears as a potentially-evaluated expression e
17500   //   is odr-used by e unless
17501   //   -- x is a reference that is usable in constant expressions
17502   //   -- x is a variable of non-reference type that is usable in constant
17503   //      expressions and has no mutable subobjects [FIXME], and e is an
17504   //      element of the set of potential results of an expression of
17505   //      non-volatile-qualified non-class type to which the lvalue-to-rvalue
17506   //      conversion is applied
17507   //   -- x is a variable of non-reference type, and e is an element of the set
17508   //      of potential results of a discarded-value expression to which the
17509   //      lvalue-to-rvalue conversion is not applied [FIXME]
17510   //
17511   // We check the first part of the second bullet here, and
17512   // Sema::CheckLValueToRValueConversionOperand deals with the second part.
17513   // FIXME: To get the third bullet right, we need to delay this even for
17514   // variables that are not usable in constant expressions.
17515 
17516   // If we already know this isn't an odr-use, there's nothing more to do.
17517   if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E))
17518     if (DRE->isNonOdrUse())
17519       return;
17520   if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E))
17521     if (ME->isNonOdrUse())
17522       return;
17523 
17524   switch (OdrUse) {
17525   case OdrUseContext::None:
17526     assert((!E || isa<FunctionParmPackExpr>(E)) &&
17527            "missing non-odr-use marking for unevaluated decl ref");
17528     break;
17529 
17530   case OdrUseContext::FormallyOdrUsed:
17531     // FIXME: Ignoring formal odr-uses results in incorrect lambda capture
17532     // behavior.
17533     break;
17534 
17535   case OdrUseContext::Used:
17536     // If we might later find that this expression isn't actually an odr-use,
17537     // delay the marking.
17538     if (E && Var->isUsableInConstantExpressions(SemaRef.Context))
17539       SemaRef.MaybeODRUseExprs.insert(E);
17540     else
17541       MarkVarDeclODRUsed(Var, Loc, SemaRef);
17542     break;
17543 
17544   case OdrUseContext::Dependent:
17545     // If this is a dependent context, we don't need to mark variables as
17546     // odr-used, but we may still need to track them for lambda capture.
17547     // FIXME: Do we also need to do this inside dependent typeid expressions
17548     // (which are modeled as unevaluated at this point)?
17549     const bool RefersToEnclosingScope =
17550         (SemaRef.CurContext != Var->getDeclContext() &&
17551          Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
17552     if (RefersToEnclosingScope) {
17553       LambdaScopeInfo *const LSI =
17554           SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
17555       if (LSI && (!LSI->CallOperator ||
17556                   !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
17557         // If a variable could potentially be odr-used, defer marking it so
17558         // until we finish analyzing the full expression for any
17559         // lvalue-to-rvalue
17560         // or discarded value conversions that would obviate odr-use.
17561         // Add it to the list of potential captures that will be analyzed
17562         // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
17563         // unless the variable is a reference that was initialized by a constant
17564         // expression (this will never need to be captured or odr-used).
17565         //
17566         // FIXME: We can simplify this a lot after implementing P0588R1.
17567         assert(E && "Capture variable should be used in an expression.");
17568         if (!Var->getType()->isReferenceType() ||
17569             !Var->isUsableInConstantExpressions(SemaRef.Context))
17570           LSI->addPotentialCapture(E->IgnoreParens());
17571       }
17572     }
17573     break;
17574   }
17575 }
17576 
17577 /// Mark a variable referenced, and check whether it is odr-used
17578 /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
17579 /// used directly for normal expressions referring to VarDecl.
17580 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
17581   DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
17582 }
17583 
17584 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
17585                                Decl *D, Expr *E, bool MightBeOdrUse) {
17586   if (SemaRef.isInOpenMPDeclareTargetContext())
17587     SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
17588 
17589   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
17590     DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
17591     return;
17592   }
17593 
17594   SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
17595 
17596   // If this is a call to a method via a cast, also mark the method in the
17597   // derived class used in case codegen can devirtualize the call.
17598   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
17599   if (!ME)
17600     return;
17601   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
17602   if (!MD)
17603     return;
17604   // Only attempt to devirtualize if this is truly a virtual call.
17605   bool IsVirtualCall = MD->isVirtual() &&
17606                           ME->performsVirtualDispatch(SemaRef.getLangOpts());
17607   if (!IsVirtualCall)
17608     return;
17609 
17610   // If it's possible to devirtualize the call, mark the called function
17611   // referenced.
17612   CXXMethodDecl *DM = MD->getDevirtualizedMethod(
17613       ME->getBase(), SemaRef.getLangOpts().AppleKext);
17614   if (DM)
17615     SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
17616 }
17617 
17618 /// Perform reference-marking and odr-use handling for a DeclRefExpr.
17619 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) {
17620   // TODO: update this with DR# once a defect report is filed.
17621   // C++11 defect. The address of a pure member should not be an ODR use, even
17622   // if it's a qualified reference.
17623   bool OdrUse = true;
17624   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
17625     if (Method->isVirtual() &&
17626         !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
17627       OdrUse = false;
17628 
17629   if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl()))
17630     if (!isConstantEvaluated() && FD->isConsteval() &&
17631         !RebuildingImmediateInvocation)
17632       ExprEvalContexts.back().ReferenceToConsteval.insert(E);
17633   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
17634 }
17635 
17636 /// Perform reference-marking and odr-use handling for a MemberExpr.
17637 void Sema::MarkMemberReferenced(MemberExpr *E) {
17638   // C++11 [basic.def.odr]p2:
17639   //   A non-overloaded function whose name appears as a potentially-evaluated
17640   //   expression or a member of a set of candidate functions, if selected by
17641   //   overload resolution when referred to from a potentially-evaluated
17642   //   expression, is odr-used, unless it is a pure virtual function and its
17643   //   name is not explicitly qualified.
17644   bool MightBeOdrUse = true;
17645   if (E->performsVirtualDispatch(getLangOpts())) {
17646     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
17647       if (Method->isPure())
17648         MightBeOdrUse = false;
17649   }
17650   SourceLocation Loc =
17651       E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
17652   MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse);
17653 }
17654 
17655 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr.
17656 void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) {
17657   for (VarDecl *VD : *E)
17658     MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true);
17659 }
17660 
17661 /// Perform marking for a reference to an arbitrary declaration.  It
17662 /// marks the declaration referenced, and performs odr-use checking for
17663 /// functions and variables. This method should not be used when building a
17664 /// normal expression which refers to a variable.
17665 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
17666                                  bool MightBeOdrUse) {
17667   if (MightBeOdrUse) {
17668     if (auto *VD = dyn_cast<VarDecl>(D)) {
17669       MarkVariableReferenced(Loc, VD);
17670       return;
17671     }
17672   }
17673   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
17674     MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
17675     return;
17676   }
17677   D->setReferenced();
17678 }
17679 
17680 namespace {
17681   // Mark all of the declarations used by a type as referenced.
17682   // FIXME: Not fully implemented yet! We need to have a better understanding
17683   // of when we're entering a context we should not recurse into.
17684   // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
17685   // TreeTransforms rebuilding the type in a new context. Rather than
17686   // duplicating the TreeTransform logic, we should consider reusing it here.
17687   // Currently that causes problems when rebuilding LambdaExprs.
17688   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
17689     Sema &S;
17690     SourceLocation Loc;
17691 
17692   public:
17693     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
17694 
17695     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
17696 
17697     bool TraverseTemplateArgument(const TemplateArgument &Arg);
17698   };
17699 }
17700 
17701 bool MarkReferencedDecls::TraverseTemplateArgument(
17702     const TemplateArgument &Arg) {
17703   {
17704     // A non-type template argument is a constant-evaluated context.
17705     EnterExpressionEvaluationContext Evaluated(
17706         S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
17707     if (Arg.getKind() == TemplateArgument::Declaration) {
17708       if (Decl *D = Arg.getAsDecl())
17709         S.MarkAnyDeclReferenced(Loc, D, true);
17710     } else if (Arg.getKind() == TemplateArgument::Expression) {
17711       S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false);
17712     }
17713   }
17714 
17715   return Inherited::TraverseTemplateArgument(Arg);
17716 }
17717 
17718 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
17719   MarkReferencedDecls Marker(*this, Loc);
17720   Marker.TraverseType(T);
17721 }
17722 
17723 namespace {
17724 /// Helper class that marks all of the declarations referenced by
17725 /// potentially-evaluated subexpressions as "referenced".
17726 class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> {
17727 public:
17728   typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited;
17729   bool SkipLocalVariables;
17730 
17731   EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
17732       : Inherited(S), SkipLocalVariables(SkipLocalVariables) {}
17733 
17734   void visitUsedDecl(SourceLocation Loc, Decl *D) {
17735     S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D));
17736   }
17737 
17738   void VisitDeclRefExpr(DeclRefExpr *E) {
17739     // If we were asked not to visit local variables, don't.
17740     if (SkipLocalVariables) {
17741       if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
17742         if (VD->hasLocalStorage())
17743           return;
17744     }
17745     S.MarkDeclRefReferenced(E);
17746   }
17747 
17748   void VisitMemberExpr(MemberExpr *E) {
17749     S.MarkMemberReferenced(E);
17750     Visit(E->getBase());
17751   }
17752 };
17753 } // namespace
17754 
17755 /// Mark any declarations that appear within this expression or any
17756 /// potentially-evaluated subexpressions as "referenced".
17757 ///
17758 /// \param SkipLocalVariables If true, don't mark local variables as
17759 /// 'referenced'.
17760 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
17761                                             bool SkipLocalVariables) {
17762   EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
17763 }
17764 
17765 /// Emit a diagnostic that describes an effect on the run-time behavior
17766 /// of the program being compiled.
17767 ///
17768 /// This routine emits the given diagnostic when the code currently being
17769 /// type-checked is "potentially evaluated", meaning that there is a
17770 /// possibility that the code will actually be executable. Code in sizeof()
17771 /// expressions, code used only during overload resolution, etc., are not
17772 /// potentially evaluated. This routine will suppress such diagnostics or,
17773 /// in the absolutely nutty case of potentially potentially evaluated
17774 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
17775 /// later.
17776 ///
17777 /// This routine should be used for all diagnostics that describe the run-time
17778 /// behavior of a program, such as passing a non-POD value through an ellipsis.
17779 /// Failure to do so will likely result in spurious diagnostics or failures
17780 /// during overload resolution or within sizeof/alignof/typeof/typeid.
17781 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts,
17782                                const PartialDiagnostic &PD) {
17783   switch (ExprEvalContexts.back().Context) {
17784   case ExpressionEvaluationContext::Unevaluated:
17785   case ExpressionEvaluationContext::UnevaluatedList:
17786   case ExpressionEvaluationContext::UnevaluatedAbstract:
17787   case ExpressionEvaluationContext::DiscardedStatement:
17788     // The argument will never be evaluated, so don't complain.
17789     break;
17790 
17791   case ExpressionEvaluationContext::ConstantEvaluated:
17792     // Relevant diagnostics should be produced by constant evaluation.
17793     break;
17794 
17795   case ExpressionEvaluationContext::PotentiallyEvaluated:
17796   case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
17797     if (!Stmts.empty() && getCurFunctionOrMethodDecl()) {
17798       FunctionScopes.back()->PossiblyUnreachableDiags.
17799         push_back(sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
17800       return true;
17801     }
17802 
17803     // The initializer of a constexpr variable or of the first declaration of a
17804     // static data member is not syntactically a constant evaluated constant,
17805     // but nonetheless is always required to be a constant expression, so we
17806     // can skip diagnosing.
17807     // FIXME: Using the mangling context here is a hack.
17808     if (auto *VD = dyn_cast_or_null<VarDecl>(
17809             ExprEvalContexts.back().ManglingContextDecl)) {
17810       if (VD->isConstexpr() ||
17811           (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline()))
17812         break;
17813       // FIXME: For any other kind of variable, we should build a CFG for its
17814       // initializer and check whether the context in question is reachable.
17815     }
17816 
17817     Diag(Loc, PD);
17818     return true;
17819   }
17820 
17821   return false;
17822 }
17823 
17824 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
17825                                const PartialDiagnostic &PD) {
17826   return DiagRuntimeBehavior(
17827       Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD);
17828 }
17829 
17830 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
17831                                CallExpr *CE, FunctionDecl *FD) {
17832   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
17833     return false;
17834 
17835   // If we're inside a decltype's expression, don't check for a valid return
17836   // type or construct temporaries until we know whether this is the last call.
17837   if (ExprEvalContexts.back().ExprContext ==
17838       ExpressionEvaluationContextRecord::EK_Decltype) {
17839     ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
17840     return false;
17841   }
17842 
17843   class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
17844     FunctionDecl *FD;
17845     CallExpr *CE;
17846 
17847   public:
17848     CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
17849       : FD(FD), CE(CE) { }
17850 
17851     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
17852       if (!FD) {
17853         S.Diag(Loc, diag::err_call_incomplete_return)
17854           << T << CE->getSourceRange();
17855         return;
17856       }
17857 
17858       S.Diag(Loc, diag::err_call_function_incomplete_return)
17859         << CE->getSourceRange() << FD->getDeclName() << T;
17860       S.Diag(FD->getLocation(), diag::note_entity_declared_at)
17861           << FD->getDeclName();
17862     }
17863   } Diagnoser(FD, CE);
17864 
17865   if (RequireCompleteType(Loc, ReturnType, Diagnoser))
17866     return true;
17867 
17868   return false;
17869 }
17870 
17871 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
17872 // will prevent this condition from triggering, which is what we want.
17873 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
17874   SourceLocation Loc;
17875 
17876   unsigned diagnostic = diag::warn_condition_is_assignment;
17877   bool IsOrAssign = false;
17878 
17879   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
17880     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
17881       return;
17882 
17883     IsOrAssign = Op->getOpcode() == BO_OrAssign;
17884 
17885     // Greylist some idioms by putting them into a warning subcategory.
17886     if (ObjCMessageExpr *ME
17887           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
17888       Selector Sel = ME->getSelector();
17889 
17890       // self = [<foo> init...]
17891       if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
17892         diagnostic = diag::warn_condition_is_idiomatic_assignment;
17893 
17894       // <foo> = [<bar> nextObject]
17895       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
17896         diagnostic = diag::warn_condition_is_idiomatic_assignment;
17897     }
17898 
17899     Loc = Op->getOperatorLoc();
17900   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
17901     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
17902       return;
17903 
17904     IsOrAssign = Op->getOperator() == OO_PipeEqual;
17905     Loc = Op->getOperatorLoc();
17906   } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
17907     return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
17908   else {
17909     // Not an assignment.
17910     return;
17911   }
17912 
17913   Diag(Loc, diagnostic) << E->getSourceRange();
17914 
17915   SourceLocation Open = E->getBeginLoc();
17916   SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
17917   Diag(Loc, diag::note_condition_assign_silence)
17918         << FixItHint::CreateInsertion(Open, "(")
17919         << FixItHint::CreateInsertion(Close, ")");
17920 
17921   if (IsOrAssign)
17922     Diag(Loc, diag::note_condition_or_assign_to_comparison)
17923       << FixItHint::CreateReplacement(Loc, "!=");
17924   else
17925     Diag(Loc, diag::note_condition_assign_to_comparison)
17926       << FixItHint::CreateReplacement(Loc, "==");
17927 }
17928 
17929 /// Redundant parentheses over an equality comparison can indicate
17930 /// that the user intended an assignment used as condition.
17931 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
17932   // Don't warn if the parens came from a macro.
17933   SourceLocation parenLoc = ParenE->getBeginLoc();
17934   if (parenLoc.isInvalid() || parenLoc.isMacroID())
17935     return;
17936   // Don't warn for dependent expressions.
17937   if (ParenE->isTypeDependent())
17938     return;
17939 
17940   Expr *E = ParenE->IgnoreParens();
17941 
17942   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
17943     if (opE->getOpcode() == BO_EQ &&
17944         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
17945                                                            == Expr::MLV_Valid) {
17946       SourceLocation Loc = opE->getOperatorLoc();
17947 
17948       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
17949       SourceRange ParenERange = ParenE->getSourceRange();
17950       Diag(Loc, diag::note_equality_comparison_silence)
17951         << FixItHint::CreateRemoval(ParenERange.getBegin())
17952         << FixItHint::CreateRemoval(ParenERange.getEnd());
17953       Diag(Loc, diag::note_equality_comparison_to_assign)
17954         << FixItHint::CreateReplacement(Loc, "=");
17955     }
17956 }
17957 
17958 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
17959                                        bool IsConstexpr) {
17960   DiagnoseAssignmentAsCondition(E);
17961   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
17962     DiagnoseEqualityWithExtraParens(parenE);
17963 
17964   ExprResult result = CheckPlaceholderExpr(E);
17965   if (result.isInvalid()) return ExprError();
17966   E = result.get();
17967 
17968   if (!E->isTypeDependent()) {
17969     if (getLangOpts().CPlusPlus)
17970       return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
17971 
17972     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
17973     if (ERes.isInvalid())
17974       return ExprError();
17975     E = ERes.get();
17976 
17977     QualType T = E->getType();
17978     if (!T->isScalarType()) { // C99 6.8.4.1p1
17979       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
17980         << T << E->getSourceRange();
17981       return ExprError();
17982     }
17983     CheckBoolLikeConversion(E, Loc);
17984   }
17985 
17986   return E;
17987 }
17988 
17989 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
17990                                            Expr *SubExpr, ConditionKind CK) {
17991   // Empty conditions are valid in for-statements.
17992   if (!SubExpr)
17993     return ConditionResult();
17994 
17995   ExprResult Cond;
17996   switch (CK) {
17997   case ConditionKind::Boolean:
17998     Cond = CheckBooleanCondition(Loc, SubExpr);
17999     break;
18000 
18001   case ConditionKind::ConstexprIf:
18002     Cond = CheckBooleanCondition(Loc, SubExpr, true);
18003     break;
18004 
18005   case ConditionKind::Switch:
18006     Cond = CheckSwitchCondition(Loc, SubExpr);
18007     break;
18008   }
18009   if (Cond.isInvalid())
18010     return ConditionError();
18011 
18012   // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
18013   FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
18014   if (!FullExpr.get())
18015     return ConditionError();
18016 
18017   return ConditionResult(*this, nullptr, FullExpr,
18018                          CK == ConditionKind::ConstexprIf);
18019 }
18020 
18021 namespace {
18022   /// A visitor for rebuilding a call to an __unknown_any expression
18023   /// to have an appropriate type.
18024   struct RebuildUnknownAnyFunction
18025     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
18026 
18027     Sema &S;
18028 
18029     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
18030 
18031     ExprResult VisitStmt(Stmt *S) {
18032       llvm_unreachable("unexpected statement!");
18033     }
18034 
18035     ExprResult VisitExpr(Expr *E) {
18036       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
18037         << E->getSourceRange();
18038       return ExprError();
18039     }
18040 
18041     /// Rebuild an expression which simply semantically wraps another
18042     /// expression which it shares the type and value kind of.
18043     template <class T> ExprResult rebuildSugarExpr(T *E) {
18044       ExprResult SubResult = Visit(E->getSubExpr());
18045       if (SubResult.isInvalid()) return ExprError();
18046 
18047       Expr *SubExpr = SubResult.get();
18048       E->setSubExpr(SubExpr);
18049       E->setType(SubExpr->getType());
18050       E->setValueKind(SubExpr->getValueKind());
18051       assert(E->getObjectKind() == OK_Ordinary);
18052       return E;
18053     }
18054 
18055     ExprResult VisitParenExpr(ParenExpr *E) {
18056       return rebuildSugarExpr(E);
18057     }
18058 
18059     ExprResult VisitUnaryExtension(UnaryOperator *E) {
18060       return rebuildSugarExpr(E);
18061     }
18062 
18063     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
18064       ExprResult SubResult = Visit(E->getSubExpr());
18065       if (SubResult.isInvalid()) return ExprError();
18066 
18067       Expr *SubExpr = SubResult.get();
18068       E->setSubExpr(SubExpr);
18069       E->setType(S.Context.getPointerType(SubExpr->getType()));
18070       assert(E->getValueKind() == VK_RValue);
18071       assert(E->getObjectKind() == OK_Ordinary);
18072       return E;
18073     }
18074 
18075     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
18076       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
18077 
18078       E->setType(VD->getType());
18079 
18080       assert(E->getValueKind() == VK_RValue);
18081       if (S.getLangOpts().CPlusPlus &&
18082           !(isa<CXXMethodDecl>(VD) &&
18083             cast<CXXMethodDecl>(VD)->isInstance()))
18084         E->setValueKind(VK_LValue);
18085 
18086       return E;
18087     }
18088 
18089     ExprResult VisitMemberExpr(MemberExpr *E) {
18090       return resolveDecl(E, E->getMemberDecl());
18091     }
18092 
18093     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
18094       return resolveDecl(E, E->getDecl());
18095     }
18096   };
18097 }
18098 
18099 /// Given a function expression of unknown-any type, try to rebuild it
18100 /// to have a function type.
18101 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
18102   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
18103   if (Result.isInvalid()) return ExprError();
18104   return S.DefaultFunctionArrayConversion(Result.get());
18105 }
18106 
18107 namespace {
18108   /// A visitor for rebuilding an expression of type __unknown_anytype
18109   /// into one which resolves the type directly on the referring
18110   /// expression.  Strict preservation of the original source
18111   /// structure is not a goal.
18112   struct RebuildUnknownAnyExpr
18113     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
18114 
18115     Sema &S;
18116 
18117     /// The current destination type.
18118     QualType DestType;
18119 
18120     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
18121       : S(S), DestType(CastType) {}
18122 
18123     ExprResult VisitStmt(Stmt *S) {
18124       llvm_unreachable("unexpected statement!");
18125     }
18126 
18127     ExprResult VisitExpr(Expr *E) {
18128       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
18129         << E->getSourceRange();
18130       return ExprError();
18131     }
18132 
18133     ExprResult VisitCallExpr(CallExpr *E);
18134     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
18135 
18136     /// Rebuild an expression which simply semantically wraps another
18137     /// expression which it shares the type and value kind of.
18138     template <class T> ExprResult rebuildSugarExpr(T *E) {
18139       ExprResult SubResult = Visit(E->getSubExpr());
18140       if (SubResult.isInvalid()) return ExprError();
18141       Expr *SubExpr = SubResult.get();
18142       E->setSubExpr(SubExpr);
18143       E->setType(SubExpr->getType());
18144       E->setValueKind(SubExpr->getValueKind());
18145       assert(E->getObjectKind() == OK_Ordinary);
18146       return E;
18147     }
18148 
18149     ExprResult VisitParenExpr(ParenExpr *E) {
18150       return rebuildSugarExpr(E);
18151     }
18152 
18153     ExprResult VisitUnaryExtension(UnaryOperator *E) {
18154       return rebuildSugarExpr(E);
18155     }
18156 
18157     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
18158       const PointerType *Ptr = DestType->getAs<PointerType>();
18159       if (!Ptr) {
18160         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
18161           << E->getSourceRange();
18162         return ExprError();
18163       }
18164 
18165       if (isa<CallExpr>(E->getSubExpr())) {
18166         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
18167           << E->getSourceRange();
18168         return ExprError();
18169       }
18170 
18171       assert(E->getValueKind() == VK_RValue);
18172       assert(E->getObjectKind() == OK_Ordinary);
18173       E->setType(DestType);
18174 
18175       // Build the sub-expression as if it were an object of the pointee type.
18176       DestType = Ptr->getPointeeType();
18177       ExprResult SubResult = Visit(E->getSubExpr());
18178       if (SubResult.isInvalid()) return ExprError();
18179       E->setSubExpr(SubResult.get());
18180       return E;
18181     }
18182 
18183     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
18184 
18185     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
18186 
18187     ExprResult VisitMemberExpr(MemberExpr *E) {
18188       return resolveDecl(E, E->getMemberDecl());
18189     }
18190 
18191     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
18192       return resolveDecl(E, E->getDecl());
18193     }
18194   };
18195 }
18196 
18197 /// Rebuilds a call expression which yielded __unknown_anytype.
18198 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
18199   Expr *CalleeExpr = E->getCallee();
18200 
18201   enum FnKind {
18202     FK_MemberFunction,
18203     FK_FunctionPointer,
18204     FK_BlockPointer
18205   };
18206 
18207   FnKind Kind;
18208   QualType CalleeType = CalleeExpr->getType();
18209   if (CalleeType == S.Context.BoundMemberTy) {
18210     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
18211     Kind = FK_MemberFunction;
18212     CalleeType = Expr::findBoundMemberType(CalleeExpr);
18213   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
18214     CalleeType = Ptr->getPointeeType();
18215     Kind = FK_FunctionPointer;
18216   } else {
18217     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
18218     Kind = FK_BlockPointer;
18219   }
18220   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
18221 
18222   // Verify that this is a legal result type of a function.
18223   if (DestType->isArrayType() || DestType->isFunctionType()) {
18224     unsigned diagID = diag::err_func_returning_array_function;
18225     if (Kind == FK_BlockPointer)
18226       diagID = diag::err_block_returning_array_function;
18227 
18228     S.Diag(E->getExprLoc(), diagID)
18229       << DestType->isFunctionType() << DestType;
18230     return ExprError();
18231   }
18232 
18233   // Otherwise, go ahead and set DestType as the call's result.
18234   E->setType(DestType.getNonLValueExprType(S.Context));
18235   E->setValueKind(Expr::getValueKindForType(DestType));
18236   assert(E->getObjectKind() == OK_Ordinary);
18237 
18238   // Rebuild the function type, replacing the result type with DestType.
18239   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
18240   if (Proto) {
18241     // __unknown_anytype(...) is a special case used by the debugger when
18242     // it has no idea what a function's signature is.
18243     //
18244     // We want to build this call essentially under the K&R
18245     // unprototyped rules, but making a FunctionNoProtoType in C++
18246     // would foul up all sorts of assumptions.  However, we cannot
18247     // simply pass all arguments as variadic arguments, nor can we
18248     // portably just call the function under a non-variadic type; see
18249     // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
18250     // However, it turns out that in practice it is generally safe to
18251     // call a function declared as "A foo(B,C,D);" under the prototype
18252     // "A foo(B,C,D,...);".  The only known exception is with the
18253     // Windows ABI, where any variadic function is implicitly cdecl
18254     // regardless of its normal CC.  Therefore we change the parameter
18255     // types to match the types of the arguments.
18256     //
18257     // This is a hack, but it is far superior to moving the
18258     // corresponding target-specific code from IR-gen to Sema/AST.
18259 
18260     ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
18261     SmallVector<QualType, 8> ArgTypes;
18262     if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
18263       ArgTypes.reserve(E->getNumArgs());
18264       for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
18265         Expr *Arg = E->getArg(i);
18266         QualType ArgType = Arg->getType();
18267         if (E->isLValue()) {
18268           ArgType = S.Context.getLValueReferenceType(ArgType);
18269         } else if (E->isXValue()) {
18270           ArgType = S.Context.getRValueReferenceType(ArgType);
18271         }
18272         ArgTypes.push_back(ArgType);
18273       }
18274       ParamTypes = ArgTypes;
18275     }
18276     DestType = S.Context.getFunctionType(DestType, ParamTypes,
18277                                          Proto->getExtProtoInfo());
18278   } else {
18279     DestType = S.Context.getFunctionNoProtoType(DestType,
18280                                                 FnType->getExtInfo());
18281   }
18282 
18283   // Rebuild the appropriate pointer-to-function type.
18284   switch (Kind) {
18285   case FK_MemberFunction:
18286     // Nothing to do.
18287     break;
18288 
18289   case FK_FunctionPointer:
18290     DestType = S.Context.getPointerType(DestType);
18291     break;
18292 
18293   case FK_BlockPointer:
18294     DestType = S.Context.getBlockPointerType(DestType);
18295     break;
18296   }
18297 
18298   // Finally, we can recurse.
18299   ExprResult CalleeResult = Visit(CalleeExpr);
18300   if (!CalleeResult.isUsable()) return ExprError();
18301   E->setCallee(CalleeResult.get());
18302 
18303   // Bind a temporary if necessary.
18304   return S.MaybeBindToTemporary(E);
18305 }
18306 
18307 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
18308   // Verify that this is a legal result type of a call.
18309   if (DestType->isArrayType() || DestType->isFunctionType()) {
18310     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
18311       << DestType->isFunctionType() << DestType;
18312     return ExprError();
18313   }
18314 
18315   // Rewrite the method result type if available.
18316   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
18317     assert(Method->getReturnType() == S.Context.UnknownAnyTy);
18318     Method->setReturnType(DestType);
18319   }
18320 
18321   // Change the type of the message.
18322   E->setType(DestType.getNonReferenceType());
18323   E->setValueKind(Expr::getValueKindForType(DestType));
18324 
18325   return S.MaybeBindToTemporary(E);
18326 }
18327 
18328 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
18329   // The only case we should ever see here is a function-to-pointer decay.
18330   if (E->getCastKind() == CK_FunctionToPointerDecay) {
18331     assert(E->getValueKind() == VK_RValue);
18332     assert(E->getObjectKind() == OK_Ordinary);
18333 
18334     E->setType(DestType);
18335 
18336     // Rebuild the sub-expression as the pointee (function) type.
18337     DestType = DestType->castAs<PointerType>()->getPointeeType();
18338 
18339     ExprResult Result = Visit(E->getSubExpr());
18340     if (!Result.isUsable()) return ExprError();
18341 
18342     E->setSubExpr(Result.get());
18343     return E;
18344   } else if (E->getCastKind() == CK_LValueToRValue) {
18345     assert(E->getValueKind() == VK_RValue);
18346     assert(E->getObjectKind() == OK_Ordinary);
18347 
18348     assert(isa<BlockPointerType>(E->getType()));
18349 
18350     E->setType(DestType);
18351 
18352     // The sub-expression has to be a lvalue reference, so rebuild it as such.
18353     DestType = S.Context.getLValueReferenceType(DestType);
18354 
18355     ExprResult Result = Visit(E->getSubExpr());
18356     if (!Result.isUsable()) return ExprError();
18357 
18358     E->setSubExpr(Result.get());
18359     return E;
18360   } else {
18361     llvm_unreachable("Unhandled cast type!");
18362   }
18363 }
18364 
18365 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
18366   ExprValueKind ValueKind = VK_LValue;
18367   QualType Type = DestType;
18368 
18369   // We know how to make this work for certain kinds of decls:
18370 
18371   //  - functions
18372   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
18373     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
18374       DestType = Ptr->getPointeeType();
18375       ExprResult Result = resolveDecl(E, VD);
18376       if (Result.isInvalid()) return ExprError();
18377       return S.ImpCastExprToType(Result.get(), Type,
18378                                  CK_FunctionToPointerDecay, VK_RValue);
18379     }
18380 
18381     if (!Type->isFunctionType()) {
18382       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
18383         << VD << E->getSourceRange();
18384       return ExprError();
18385     }
18386     if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
18387       // We must match the FunctionDecl's type to the hack introduced in
18388       // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
18389       // type. See the lengthy commentary in that routine.
18390       QualType FDT = FD->getType();
18391       const FunctionType *FnType = FDT->castAs<FunctionType>();
18392       const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
18393       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
18394       if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
18395         SourceLocation Loc = FD->getLocation();
18396         FunctionDecl *NewFD = FunctionDecl::Create(
18397             S.Context, FD->getDeclContext(), Loc, Loc,
18398             FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(),
18399             SC_None, false /*isInlineSpecified*/, FD->hasPrototype(),
18400             /*ConstexprKind*/ CSK_unspecified);
18401 
18402         if (FD->getQualifier())
18403           NewFD->setQualifierInfo(FD->getQualifierLoc());
18404 
18405         SmallVector<ParmVarDecl*, 16> Params;
18406         for (const auto &AI : FT->param_types()) {
18407           ParmVarDecl *Param =
18408             S.BuildParmVarDeclForTypedef(FD, Loc, AI);
18409           Param->setScopeInfo(0, Params.size());
18410           Params.push_back(Param);
18411         }
18412         NewFD->setParams(Params);
18413         DRE->setDecl(NewFD);
18414         VD = DRE->getDecl();
18415       }
18416     }
18417 
18418     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
18419       if (MD->isInstance()) {
18420         ValueKind = VK_RValue;
18421         Type = S.Context.BoundMemberTy;
18422       }
18423 
18424     // Function references aren't l-values in C.
18425     if (!S.getLangOpts().CPlusPlus)
18426       ValueKind = VK_RValue;
18427 
18428   //  - variables
18429   } else if (isa<VarDecl>(VD)) {
18430     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
18431       Type = RefTy->getPointeeType();
18432     } else if (Type->isFunctionType()) {
18433       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
18434         << VD << E->getSourceRange();
18435       return ExprError();
18436     }
18437 
18438   //  - nothing else
18439   } else {
18440     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
18441       << VD << E->getSourceRange();
18442     return ExprError();
18443   }
18444 
18445   // Modifying the declaration like this is friendly to IR-gen but
18446   // also really dangerous.
18447   VD->setType(DestType);
18448   E->setType(Type);
18449   E->setValueKind(ValueKind);
18450   return E;
18451 }
18452 
18453 /// Check a cast of an unknown-any type.  We intentionally only
18454 /// trigger this for C-style casts.
18455 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
18456                                      Expr *CastExpr, CastKind &CastKind,
18457                                      ExprValueKind &VK, CXXCastPath &Path) {
18458   // The type we're casting to must be either void or complete.
18459   if (!CastType->isVoidType() &&
18460       RequireCompleteType(TypeRange.getBegin(), CastType,
18461                           diag::err_typecheck_cast_to_incomplete))
18462     return ExprError();
18463 
18464   // Rewrite the casted expression from scratch.
18465   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
18466   if (!result.isUsable()) return ExprError();
18467 
18468   CastExpr = result.get();
18469   VK = CastExpr->getValueKind();
18470   CastKind = CK_NoOp;
18471 
18472   return CastExpr;
18473 }
18474 
18475 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
18476   return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
18477 }
18478 
18479 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
18480                                     Expr *arg, QualType &paramType) {
18481   // If the syntactic form of the argument is not an explicit cast of
18482   // any sort, just do default argument promotion.
18483   ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
18484   if (!castArg) {
18485     ExprResult result = DefaultArgumentPromotion(arg);
18486     if (result.isInvalid()) return ExprError();
18487     paramType = result.get()->getType();
18488     return result;
18489   }
18490 
18491   // Otherwise, use the type that was written in the explicit cast.
18492   assert(!arg->hasPlaceholderType());
18493   paramType = castArg->getTypeAsWritten();
18494 
18495   // Copy-initialize a parameter of that type.
18496   InitializedEntity entity =
18497     InitializedEntity::InitializeParameter(Context, paramType,
18498                                            /*consumed*/ false);
18499   return PerformCopyInitialization(entity, callLoc, arg);
18500 }
18501 
18502 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
18503   Expr *orig = E;
18504   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
18505   while (true) {
18506     E = E->IgnoreParenImpCasts();
18507     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
18508       E = call->getCallee();
18509       diagID = diag::err_uncasted_call_of_unknown_any;
18510     } else {
18511       break;
18512     }
18513   }
18514 
18515   SourceLocation loc;
18516   NamedDecl *d;
18517   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
18518     loc = ref->getLocation();
18519     d = ref->getDecl();
18520   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
18521     loc = mem->getMemberLoc();
18522     d = mem->getMemberDecl();
18523   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
18524     diagID = diag::err_uncasted_call_of_unknown_any;
18525     loc = msg->getSelectorStartLoc();
18526     d = msg->getMethodDecl();
18527     if (!d) {
18528       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
18529         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
18530         << orig->getSourceRange();
18531       return ExprError();
18532     }
18533   } else {
18534     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
18535       << E->getSourceRange();
18536     return ExprError();
18537   }
18538 
18539   S.Diag(loc, diagID) << d << orig->getSourceRange();
18540 
18541   // Never recoverable.
18542   return ExprError();
18543 }
18544 
18545 /// Check for operands with placeholder types and complain if found.
18546 /// Returns ExprError() if there was an error and no recovery was possible.
18547 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
18548   if (!getLangOpts().CPlusPlus) {
18549     // C cannot handle TypoExpr nodes on either side of a binop because it
18550     // doesn't handle dependent types properly, so make sure any TypoExprs have
18551     // been dealt with before checking the operands.
18552     ExprResult Result = CorrectDelayedTyposInExpr(E);
18553     if (!Result.isUsable()) return ExprError();
18554     E = Result.get();
18555   }
18556 
18557   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
18558   if (!placeholderType) return E;
18559 
18560   switch (placeholderType->getKind()) {
18561 
18562   // Overloaded expressions.
18563   case BuiltinType::Overload: {
18564     // Try to resolve a single function template specialization.
18565     // This is obligatory.
18566     ExprResult Result = E;
18567     if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
18568       return Result;
18569 
18570     // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
18571     // leaves Result unchanged on failure.
18572     Result = E;
18573     if (resolveAndFixAddressOfSingleOverloadCandidate(Result))
18574       return Result;
18575 
18576     // If that failed, try to recover with a call.
18577     tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
18578                          /*complain*/ true);
18579     return Result;
18580   }
18581 
18582   // Bound member functions.
18583   case BuiltinType::BoundMember: {
18584     ExprResult result = E;
18585     const Expr *BME = E->IgnoreParens();
18586     PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
18587     // Try to give a nicer diagnostic if it is a bound member that we recognize.
18588     if (isa<CXXPseudoDestructorExpr>(BME)) {
18589       PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
18590     } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
18591       if (ME->getMemberNameInfo().getName().getNameKind() ==
18592           DeclarationName::CXXDestructorName)
18593         PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
18594     }
18595     tryToRecoverWithCall(result, PD,
18596                          /*complain*/ true);
18597     return result;
18598   }
18599 
18600   // ARC unbridged casts.
18601   case BuiltinType::ARCUnbridgedCast: {
18602     Expr *realCast = stripARCUnbridgedCast(E);
18603     diagnoseARCUnbridgedCast(realCast);
18604     return realCast;
18605   }
18606 
18607   // Expressions of unknown type.
18608   case BuiltinType::UnknownAny:
18609     return diagnoseUnknownAnyExpr(*this, E);
18610 
18611   // Pseudo-objects.
18612   case BuiltinType::PseudoObject:
18613     return checkPseudoObjectRValue(E);
18614 
18615   case BuiltinType::BuiltinFn: {
18616     // Accept __noop without parens by implicitly converting it to a call expr.
18617     auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
18618     if (DRE) {
18619       auto *FD = cast<FunctionDecl>(DRE->getDecl());
18620       if (FD->getBuiltinID() == Builtin::BI__noop) {
18621         E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
18622                               CK_BuiltinFnToFnPtr)
18623                 .get();
18624         return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy,
18625                                 VK_RValue, SourceLocation());
18626       }
18627     }
18628 
18629     Diag(E->getBeginLoc(), diag::err_builtin_fn_use);
18630     return ExprError();
18631   }
18632 
18633   // Expressions of unknown type.
18634   case BuiltinType::OMPArraySection:
18635     Diag(E->getBeginLoc(), diag::err_omp_array_section_use);
18636     return ExprError();
18637 
18638   // Expressions of unknown type.
18639   case BuiltinType::OMPArrayShaping:
18640     return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use));
18641 
18642   case BuiltinType::OMPIterator:
18643     return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use));
18644 
18645   // Everything else should be impossible.
18646 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
18647   case BuiltinType::Id:
18648 #include "clang/Basic/OpenCLImageTypes.def"
18649 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
18650   case BuiltinType::Id:
18651 #include "clang/Basic/OpenCLExtensionTypes.def"
18652 #define SVE_TYPE(Name, Id, SingletonId) \
18653   case BuiltinType::Id:
18654 #include "clang/Basic/AArch64SVEACLETypes.def"
18655 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
18656 #define PLACEHOLDER_TYPE(Id, SingletonId)
18657 #include "clang/AST/BuiltinTypes.def"
18658     break;
18659   }
18660 
18661   llvm_unreachable("invalid placeholder type!");
18662 }
18663 
18664 bool Sema::CheckCaseExpression(Expr *E) {
18665   if (E->isTypeDependent())
18666     return true;
18667   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
18668     return E->getType()->isIntegralOrEnumerationType();
18669   return false;
18670 }
18671 
18672 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
18673 ExprResult
18674 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
18675   assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
18676          "Unknown Objective-C Boolean value!");
18677   QualType BoolT = Context.ObjCBuiltinBoolTy;
18678   if (!Context.getBOOLDecl()) {
18679     LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
18680                         Sema::LookupOrdinaryName);
18681     if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
18682       NamedDecl *ND = Result.getFoundDecl();
18683       if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
18684         Context.setBOOLDecl(TD);
18685     }
18686   }
18687   if (Context.getBOOLDecl())
18688     BoolT = Context.getBOOLType();
18689   return new (Context)
18690       ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
18691 }
18692 
18693 ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
18694     llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
18695     SourceLocation RParen) {
18696 
18697   StringRef Platform = getASTContext().getTargetInfo().getPlatformName();
18698 
18699   auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) {
18700     return Spec.getPlatform() == Platform;
18701   });
18702 
18703   VersionTuple Version;
18704   if (Spec != AvailSpecs.end())
18705     Version = Spec->getVersion();
18706 
18707   // The use of `@available` in the enclosing function should be analyzed to
18708   // warn when it's used inappropriately (i.e. not if(@available)).
18709   if (getCurFunctionOrMethodDecl())
18710     getEnclosingFunction()->HasPotentialAvailabilityViolations = true;
18711   else if (getCurBlock() || getCurLambda())
18712     getCurFunction()->HasPotentialAvailabilityViolations = true;
18713 
18714   return new (Context)
18715       ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
18716 }
18717 
18718 bool Sema::IsDependentFunctionNameExpr(Expr *E) {
18719   assert(E->isTypeDependent());
18720   return isa<UnresolvedLookupExpr>(E);
18721 }
18722 
18723 ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End,
18724                                     ArrayRef<Expr *> SubExprs) {
18725   // FIXME: enable it for C++, RecoveryExpr is type-dependent to suppress
18726   // bogus diagnostics and this trick does not work in C.
18727   // FIXME: use containsErrors() to suppress unwanted diags in C.
18728   if (!Context.getLangOpts().RecoveryAST)
18729     return ExprError();
18730 
18731   if (isSFINAEContext())
18732     return ExprError();
18733 
18734   return RecoveryExpr::Create(Context, Begin, End, SubExprs);
18735 }
18736