1 //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file implements semantic analysis for expressions.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "TreeTransform.h"
14 #include "UsedDeclVisitor.h"
15 #include "clang/AST/ASTConsumer.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/ASTLambda.h"
18 #include "clang/AST/ASTMutationListener.h"
19 #include "clang/AST/CXXInheritance.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "clang/AST/DeclTemplate.h"
22 #include "clang/AST/EvaluatedExprVisitor.h"
23 #include "clang/AST/Expr.h"
24 #include "clang/AST/ExprCXX.h"
25 #include "clang/AST/ExprObjC.h"
26 #include "clang/AST/ExprOpenMP.h"
27 #include "clang/AST/RecursiveASTVisitor.h"
28 #include "clang/AST/TypeLoc.h"
29 #include "clang/Basic/Builtins.h"
30 #include "clang/Basic/FixedPoint.h"
31 #include "clang/Basic/PartialDiagnostic.h"
32 #include "clang/Basic/SourceManager.h"
33 #include "clang/Basic/TargetInfo.h"
34 #include "clang/Lex/LiteralSupport.h"
35 #include "clang/Lex/Preprocessor.h"
36 #include "clang/Sema/AnalysisBasedWarnings.h"
37 #include "clang/Sema/DeclSpec.h"
38 #include "clang/Sema/DelayedDiagnostic.h"
39 #include "clang/Sema/Designator.h"
40 #include "clang/Sema/Initialization.h"
41 #include "clang/Sema/Lookup.h"
42 #include "clang/Sema/Overload.h"
43 #include "clang/Sema/ParsedTemplate.h"
44 #include "clang/Sema/Scope.h"
45 #include "clang/Sema/ScopeInfo.h"
46 #include "clang/Sema/SemaFixItUtils.h"
47 #include "clang/Sema/SemaInternal.h"
48 #include "clang/Sema/Template.h"
49 #include "llvm/Support/ConvertUTF.h"
50 #include "llvm/Support/SaveAndRestore.h"
51 using namespace clang;
52 using namespace sema;
53 using llvm::RoundingMode;
54 
55 /// Determine whether the use of this declaration is valid, without
56 /// emitting diagnostics.
57 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
58   // See if this is an auto-typed variable whose initializer we are parsing.
59   if (ParsingInitForAutoVars.count(D))
60     return false;
61 
62   // See if this is a deleted function.
63   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
64     if (FD->isDeleted())
65       return false;
66 
67     // If the function has a deduced return type, and we can't deduce it,
68     // then we can't use it either.
69     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
70         DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
71       return false;
72 
73     // See if this is an aligned allocation/deallocation function that is
74     // unavailable.
75     if (TreatUnavailableAsInvalid &&
76         isUnavailableAlignedAllocationFunction(*FD))
77       return false;
78   }
79 
80   // See if this function is unavailable.
81   if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
82       cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
83     return false;
84 
85   return true;
86 }
87 
88 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
89   // Warn if this is used but marked unused.
90   if (const auto *A = D->getAttr<UnusedAttr>()) {
91     // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
92     // should diagnose them.
93     if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused &&
94         A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) {
95       const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext());
96       if (DC && !DC->hasAttr<UnusedAttr>())
97         S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
98     }
99   }
100 }
101 
102 /// Emit a note explaining that this function is deleted.
103 void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
104   assert(Decl && Decl->isDeleted());
105 
106   if (Decl->isDefaulted()) {
107     // If the method was explicitly defaulted, point at that declaration.
108     if (!Decl->isImplicit())
109       Diag(Decl->getLocation(), diag::note_implicitly_deleted);
110 
111     // Try to diagnose why this special member function was implicitly
112     // deleted. This might fail, if that reason no longer applies.
113     DiagnoseDeletedDefaultedFunction(Decl);
114     return;
115   }
116 
117   auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
118   if (Ctor && Ctor->isInheritingConstructor())
119     return NoteDeletedInheritingConstructor(Ctor);
120 
121   Diag(Decl->getLocation(), diag::note_availability_specified_here)
122     << Decl << 1;
123 }
124 
125 /// Determine whether a FunctionDecl was ever declared with an
126 /// explicit storage class.
127 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
128   for (auto I : D->redecls()) {
129     if (I->getStorageClass() != SC_None)
130       return true;
131   }
132   return false;
133 }
134 
135 /// Check whether we're in an extern inline function and referring to a
136 /// variable or function with internal linkage (C11 6.7.4p3).
137 ///
138 /// This is only a warning because we used to silently accept this code, but
139 /// in many cases it will not behave correctly. This is not enabled in C++ mode
140 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
141 /// and so while there may still be user mistakes, most of the time we can't
142 /// prove that there are errors.
143 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
144                                                       const NamedDecl *D,
145                                                       SourceLocation Loc) {
146   // This is disabled under C++; there are too many ways for this to fire in
147   // contexts where the warning is a false positive, or where it is technically
148   // correct but benign.
149   if (S.getLangOpts().CPlusPlus)
150     return;
151 
152   // Check if this is an inlined function or method.
153   FunctionDecl *Current = S.getCurFunctionDecl();
154   if (!Current)
155     return;
156   if (!Current->isInlined())
157     return;
158   if (!Current->isExternallyVisible())
159     return;
160 
161   // Check if the decl has internal linkage.
162   if (D->getFormalLinkage() != InternalLinkage)
163     return;
164 
165   // Downgrade from ExtWarn to Extension if
166   //  (1) the supposedly external inline function is in the main file,
167   //      and probably won't be included anywhere else.
168   //  (2) the thing we're referencing is a pure function.
169   //  (3) the thing we're referencing is another inline function.
170   // This last can give us false negatives, but it's better than warning on
171   // wrappers for simple C library functions.
172   const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
173   bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
174   if (!DowngradeWarning && UsedFn)
175     DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
176 
177   S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
178                                : diag::ext_internal_in_extern_inline)
179     << /*IsVar=*/!UsedFn << D;
180 
181   S.MaybeSuggestAddingStaticToDecl(Current);
182 
183   S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
184       << D;
185 }
186 
187 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
188   const FunctionDecl *First = Cur->getFirstDecl();
189 
190   // Suggest "static" on the function, if possible.
191   if (!hasAnyExplicitStorageClass(First)) {
192     SourceLocation DeclBegin = First->getSourceRange().getBegin();
193     Diag(DeclBegin, diag::note_convert_inline_to_static)
194       << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
195   }
196 }
197 
198 /// Determine whether the use of this declaration is valid, and
199 /// emit any corresponding diagnostics.
200 ///
201 /// This routine diagnoses various problems with referencing
202 /// declarations that can occur when using a declaration. For example,
203 /// it might warn if a deprecated or unavailable declaration is being
204 /// used, or produce an error (and return true) if a C++0x deleted
205 /// function is being used.
206 ///
207 /// \returns true if there was an error (this declaration cannot be
208 /// referenced), false otherwise.
209 ///
210 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
211                              const ObjCInterfaceDecl *UnknownObjCClass,
212                              bool ObjCPropertyAccess,
213                              bool AvoidPartialAvailabilityChecks,
214                              ObjCInterfaceDecl *ClassReceiver) {
215   SourceLocation Loc = Locs.front();
216   if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
217     // If there were any diagnostics suppressed by template argument deduction,
218     // emit them now.
219     auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
220     if (Pos != SuppressedDiagnostics.end()) {
221       for (const PartialDiagnosticAt &Suppressed : Pos->second)
222         Diag(Suppressed.first, Suppressed.second);
223 
224       // Clear out the list of suppressed diagnostics, so that we don't emit
225       // them again for this specialization. However, we don't obsolete this
226       // entry from the table, because we want to avoid ever emitting these
227       // diagnostics again.
228       Pos->second.clear();
229     }
230 
231     // C++ [basic.start.main]p3:
232     //   The function 'main' shall not be used within a program.
233     if (cast<FunctionDecl>(D)->isMain())
234       Diag(Loc, diag::ext_main_used);
235 
236     diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc);
237   }
238 
239   // See if this is an auto-typed variable whose initializer we are parsing.
240   if (ParsingInitForAutoVars.count(D)) {
241     if (isa<BindingDecl>(D)) {
242       Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
243         << D->getDeclName();
244     } else {
245       Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
246         << D->getDeclName() << cast<VarDecl>(D)->getType();
247     }
248     return true;
249   }
250 
251   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
252     // See if this is a deleted function.
253     if (FD->isDeleted()) {
254       auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
255       if (Ctor && Ctor->isInheritingConstructor())
256         Diag(Loc, diag::err_deleted_inherited_ctor_use)
257             << Ctor->getParent()
258             << Ctor->getInheritedConstructor().getConstructor()->getParent();
259       else
260         Diag(Loc, diag::err_deleted_function_use);
261       NoteDeletedFunction(FD);
262       return true;
263     }
264 
265     // [expr.prim.id]p4
266     //   A program that refers explicitly or implicitly to a function with a
267     //   trailing requires-clause whose constraint-expression is not satisfied,
268     //   other than to declare it, is ill-formed. [...]
269     //
270     // See if this is a function with constraints that need to be satisfied.
271     // Check this before deducing the return type, as it might instantiate the
272     // definition.
273     if (FD->getTrailingRequiresClause()) {
274       ConstraintSatisfaction Satisfaction;
275       if (CheckFunctionConstraints(FD, Satisfaction, Loc))
276         // A diagnostic will have already been generated (non-constant
277         // constraint expression, for example)
278         return true;
279       if (!Satisfaction.IsSatisfied) {
280         Diag(Loc,
281              diag::err_reference_to_function_with_unsatisfied_constraints)
282             << D;
283         DiagnoseUnsatisfiedConstraint(Satisfaction);
284         return true;
285       }
286     }
287 
288     // If the function has a deduced return type, and we can't deduce it,
289     // then we can't use it either.
290     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
291         DeduceReturnType(FD, Loc))
292       return true;
293 
294     if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD))
295       return true;
296 
297     if (getLangOpts().SYCLIsDevice && !checkSYCLDeviceFunction(Loc, FD))
298       return true;
299   }
300 
301   if (auto *MD = dyn_cast<CXXMethodDecl>(D)) {
302     // Lambdas are only default-constructible or assignable in C++2a onwards.
303     if (MD->getParent()->isLambda() &&
304         ((isa<CXXConstructorDecl>(MD) &&
305           cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) ||
306          MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) {
307       Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign)
308         << !isa<CXXConstructorDecl>(MD);
309     }
310   }
311 
312   auto getReferencedObjCProp = [](const NamedDecl *D) ->
313                                       const ObjCPropertyDecl * {
314     if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
315       return MD->findPropertyDecl();
316     return nullptr;
317   };
318   if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
319     if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc))
320       return true;
321   } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) {
322       return true;
323   }
324 
325   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
326   // Only the variables omp_in and omp_out are allowed in the combiner.
327   // Only the variables omp_priv and omp_orig are allowed in the
328   // initializer-clause.
329   auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
330   if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
331       isa<VarDecl>(D)) {
332     Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
333         << getCurFunction()->HasOMPDeclareReductionCombiner;
334     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
335     return true;
336   }
337 
338   // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions
339   //  List-items in map clauses on this construct may only refer to the declared
340   //  variable var and entities that could be referenced by a procedure defined
341   //  at the same location
342   auto *DMD = dyn_cast<OMPDeclareMapperDecl>(CurContext);
343   if (LangOpts.OpenMP && DMD && !CurContext->containsDecl(D) &&
344       isa<VarDecl>(D)) {
345     Diag(Loc, diag::err_omp_declare_mapper_wrong_var)
346         << DMD->getVarName().getAsString();
347     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
348     return true;
349   }
350 
351   DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,
352                              AvoidPartialAvailabilityChecks, ClassReceiver);
353 
354   DiagnoseUnusedOfDecl(*this, D, Loc);
355 
356   diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
357 
358   if (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice))
359     if (const auto *VD = dyn_cast<ValueDecl>(D))
360       checkDeviceDecl(VD, Loc);
361 
362   if (isa<ParmVarDecl>(D) && isa<RequiresExprBodyDecl>(D->getDeclContext()) &&
363       !isUnevaluatedContext()) {
364     // C++ [expr.prim.req.nested] p3
365     //   A local parameter shall only appear as an unevaluated operand
366     //   (Clause 8) within the constraint-expression.
367     Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context)
368         << D;
369     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
370     return true;
371   }
372 
373   return false;
374 }
375 
376 /// DiagnoseSentinelCalls - This routine checks whether a call or
377 /// message-send is to a declaration with the sentinel attribute, and
378 /// if so, it checks that the requirements of the sentinel are
379 /// satisfied.
380 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
381                                  ArrayRef<Expr *> Args) {
382   const SentinelAttr *attr = D->getAttr<SentinelAttr>();
383   if (!attr)
384     return;
385 
386   // The number of formal parameters of the declaration.
387   unsigned numFormalParams;
388 
389   // The kind of declaration.  This is also an index into a %select in
390   // the diagnostic.
391   enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
392 
393   if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
394     numFormalParams = MD->param_size();
395     calleeType = CT_Method;
396   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
397     numFormalParams = FD->param_size();
398     calleeType = CT_Function;
399   } else if (isa<VarDecl>(D)) {
400     QualType type = cast<ValueDecl>(D)->getType();
401     const FunctionType *fn = nullptr;
402     if (const PointerType *ptr = type->getAs<PointerType>()) {
403       fn = ptr->getPointeeType()->getAs<FunctionType>();
404       if (!fn) return;
405       calleeType = CT_Function;
406     } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
407       fn = ptr->getPointeeType()->castAs<FunctionType>();
408       calleeType = CT_Block;
409     } else {
410       return;
411     }
412 
413     if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
414       numFormalParams = proto->getNumParams();
415     } else {
416       numFormalParams = 0;
417     }
418   } else {
419     return;
420   }
421 
422   // "nullPos" is the number of formal parameters at the end which
423   // effectively count as part of the variadic arguments.  This is
424   // useful if you would prefer to not have *any* formal parameters,
425   // but the language forces you to have at least one.
426   unsigned nullPos = attr->getNullPos();
427   assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
428   numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
429 
430   // The number of arguments which should follow the sentinel.
431   unsigned numArgsAfterSentinel = attr->getSentinel();
432 
433   // If there aren't enough arguments for all the formal parameters,
434   // the sentinel, and the args after the sentinel, complain.
435   if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
436     Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
437     Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
438     return;
439   }
440 
441   // Otherwise, find the sentinel expression.
442   Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
443   if (!sentinelExpr) return;
444   if (sentinelExpr->isValueDependent()) return;
445   if (Context.isSentinelNullExpr(sentinelExpr)) return;
446 
447   // Pick a reasonable string to insert.  Optimistically use 'nil', 'nullptr',
448   // or 'NULL' if those are actually defined in the context.  Only use
449   // 'nil' for ObjC methods, where it's much more likely that the
450   // variadic arguments form a list of object pointers.
451   SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc());
452   std::string NullValue;
453   if (calleeType == CT_Method && PP.isMacroDefined("nil"))
454     NullValue = "nil";
455   else if (getLangOpts().CPlusPlus11)
456     NullValue = "nullptr";
457   else if (PP.isMacroDefined("NULL"))
458     NullValue = "NULL";
459   else
460     NullValue = "(void*) 0";
461 
462   if (MissingNilLoc.isInvalid())
463     Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
464   else
465     Diag(MissingNilLoc, diag::warn_missing_sentinel)
466       << int(calleeType)
467       << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
468   Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
469 }
470 
471 SourceRange Sema::getExprRange(Expr *E) const {
472   return E ? E->getSourceRange() : SourceRange();
473 }
474 
475 //===----------------------------------------------------------------------===//
476 //  Standard Promotions and Conversions
477 //===----------------------------------------------------------------------===//
478 
479 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
480 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
481   // Handle any placeholder expressions which made it here.
482   if (E->getType()->isPlaceholderType()) {
483     ExprResult result = CheckPlaceholderExpr(E);
484     if (result.isInvalid()) return ExprError();
485     E = result.get();
486   }
487 
488   QualType Ty = E->getType();
489   assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
490 
491   if (Ty->isFunctionType()) {
492     if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
493       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
494         if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
495           return ExprError();
496 
497     E = ImpCastExprToType(E, Context.getPointerType(Ty),
498                           CK_FunctionToPointerDecay).get();
499   } else if (Ty->isArrayType()) {
500     // In C90 mode, arrays only promote to pointers if the array expression is
501     // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
502     // type 'array of type' is converted to an expression that has type 'pointer
503     // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
504     // that has type 'array of type' ...".  The relevant change is "an lvalue"
505     // (C90) to "an expression" (C99).
506     //
507     // C++ 4.2p1:
508     // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
509     // T" can be converted to an rvalue of type "pointer to T".
510     //
511     if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
512       E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
513                             CK_ArrayToPointerDecay).get();
514   }
515   return E;
516 }
517 
518 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
519   // Check to see if we are dereferencing a null pointer.  If so,
520   // and if not volatile-qualified, this is undefined behavior that the
521   // optimizer will delete, so warn about it.  People sometimes try to use this
522   // to get a deterministic trap and are surprised by clang's behavior.  This
523   // only handles the pattern "*null", which is a very syntactic check.
524   const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts());
525   if (UO && UO->getOpcode() == UO_Deref &&
526       UO->getSubExpr()->getType()->isPointerType()) {
527     const LangAS AS =
528         UO->getSubExpr()->getType()->getPointeeType().getAddressSpace();
529     if ((!isTargetAddressSpace(AS) ||
530          (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) &&
531         UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant(
532             S.Context, Expr::NPC_ValueDependentIsNotNull) &&
533         !UO->getType().isVolatileQualified()) {
534       S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
535                             S.PDiag(diag::warn_indirection_through_null)
536                                 << UO->getSubExpr()->getSourceRange());
537       S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
538                             S.PDiag(diag::note_indirection_through_null));
539     }
540   }
541 }
542 
543 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
544                                     SourceLocation AssignLoc,
545                                     const Expr* RHS) {
546   const ObjCIvarDecl *IV = OIRE->getDecl();
547   if (!IV)
548     return;
549 
550   DeclarationName MemberName = IV->getDeclName();
551   IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
552   if (!Member || !Member->isStr("isa"))
553     return;
554 
555   const Expr *Base = OIRE->getBase();
556   QualType BaseType = Base->getType();
557   if (OIRE->isArrow())
558     BaseType = BaseType->getPointeeType();
559   if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
560     if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
561       ObjCInterfaceDecl *ClassDeclared = nullptr;
562       ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
563       if (!ClassDeclared->getSuperClass()
564           && (*ClassDeclared->ivar_begin()) == IV) {
565         if (RHS) {
566           NamedDecl *ObjectSetClass =
567             S.LookupSingleName(S.TUScope,
568                                &S.Context.Idents.get("object_setClass"),
569                                SourceLocation(), S.LookupOrdinaryName);
570           if (ObjectSetClass) {
571             SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc());
572             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign)
573                 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
574                                               "object_setClass(")
575                 << FixItHint::CreateReplacement(
576                        SourceRange(OIRE->getOpLoc(), AssignLoc), ",")
577                 << FixItHint::CreateInsertion(RHSLocEnd, ")");
578           }
579           else
580             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
581         } else {
582           NamedDecl *ObjectGetClass =
583             S.LookupSingleName(S.TUScope,
584                                &S.Context.Idents.get("object_getClass"),
585                                SourceLocation(), S.LookupOrdinaryName);
586           if (ObjectGetClass)
587             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use)
588                 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
589                                               "object_getClass(")
590                 << FixItHint::CreateReplacement(
591                        SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")");
592           else
593             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
594         }
595         S.Diag(IV->getLocation(), diag::note_ivar_decl);
596       }
597     }
598 }
599 
600 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
601   // Handle any placeholder expressions which made it here.
602   if (E->getType()->isPlaceholderType()) {
603     ExprResult result = CheckPlaceholderExpr(E);
604     if (result.isInvalid()) return ExprError();
605     E = result.get();
606   }
607 
608   // C++ [conv.lval]p1:
609   //   A glvalue of a non-function, non-array type T can be
610   //   converted to a prvalue.
611   if (!E->isGLValue()) return E;
612 
613   QualType T = E->getType();
614   assert(!T.isNull() && "r-value conversion on typeless expression?");
615 
616   // lvalue-to-rvalue conversion cannot be applied to function or array types.
617   if (T->isFunctionType() || T->isArrayType())
618     return E;
619 
620   // We don't want to throw lvalue-to-rvalue casts on top of
621   // expressions of certain types in C++.
622   if (getLangOpts().CPlusPlus &&
623       (E->getType() == Context.OverloadTy ||
624        T->isDependentType() ||
625        T->isRecordType()))
626     return E;
627 
628   // The C standard is actually really unclear on this point, and
629   // DR106 tells us what the result should be but not why.  It's
630   // generally best to say that void types just doesn't undergo
631   // lvalue-to-rvalue at all.  Note that expressions of unqualified
632   // 'void' type are never l-values, but qualified void can be.
633   if (T->isVoidType())
634     return E;
635 
636   // OpenCL usually rejects direct accesses to values of 'half' type.
637   if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
638       T->isHalfType()) {
639     Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
640       << 0 << T;
641     return ExprError();
642   }
643 
644   CheckForNullPointerDereference(*this, E);
645   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
646     NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
647                                      &Context.Idents.get("object_getClass"),
648                                      SourceLocation(), LookupOrdinaryName);
649     if (ObjectGetClass)
650       Diag(E->getExprLoc(), diag::warn_objc_isa_use)
651           << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(")
652           << FixItHint::CreateReplacement(
653                  SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
654     else
655       Diag(E->getExprLoc(), diag::warn_objc_isa_use);
656   }
657   else if (const ObjCIvarRefExpr *OIRE =
658             dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
659     DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
660 
661   // C++ [conv.lval]p1:
662   //   [...] If T is a non-class type, the type of the prvalue is the
663   //   cv-unqualified version of T. Otherwise, the type of the
664   //   rvalue is T.
665   //
666   // C99 6.3.2.1p2:
667   //   If the lvalue has qualified type, the value has the unqualified
668   //   version of the type of the lvalue; otherwise, the value has the
669   //   type of the lvalue.
670   if (T.hasQualifiers())
671     T = T.getUnqualifiedType();
672 
673   // Under the MS ABI, lock down the inheritance model now.
674   if (T->isMemberPointerType() &&
675       Context.getTargetInfo().getCXXABI().isMicrosoft())
676     (void)isCompleteType(E->getExprLoc(), T);
677 
678   ExprResult Res = CheckLValueToRValueConversionOperand(E);
679   if (Res.isInvalid())
680     return Res;
681   E = Res.get();
682 
683   // Loading a __weak object implicitly retains the value, so we need a cleanup to
684   // balance that.
685   if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
686     Cleanup.setExprNeedsCleanups(true);
687 
688   if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
689     Cleanup.setExprNeedsCleanups(true);
690 
691   // C++ [conv.lval]p3:
692   //   If T is cv std::nullptr_t, the result is a null pointer constant.
693   CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue;
694   Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_RValue);
695 
696   // C11 6.3.2.1p2:
697   //   ... if the lvalue has atomic type, the value has the non-atomic version
698   //   of the type of the lvalue ...
699   if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
700     T = Atomic->getValueType().getUnqualifiedType();
701     Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
702                                    nullptr, VK_RValue);
703   }
704 
705   return Res;
706 }
707 
708 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
709   ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
710   if (Res.isInvalid())
711     return ExprError();
712   Res = DefaultLvalueConversion(Res.get());
713   if (Res.isInvalid())
714     return ExprError();
715   return Res;
716 }
717 
718 /// CallExprUnaryConversions - a special case of an unary conversion
719 /// performed on a function designator of a call expression.
720 ExprResult Sema::CallExprUnaryConversions(Expr *E) {
721   QualType Ty = E->getType();
722   ExprResult Res = E;
723   // Only do implicit cast for a function type, but not for a pointer
724   // to function type.
725   if (Ty->isFunctionType()) {
726     Res = ImpCastExprToType(E, Context.getPointerType(Ty),
727                             CK_FunctionToPointerDecay).get();
728     if (Res.isInvalid())
729       return ExprError();
730   }
731   Res = DefaultLvalueConversion(Res.get());
732   if (Res.isInvalid())
733     return ExprError();
734   return Res.get();
735 }
736 
737 /// UsualUnaryConversions - Performs various conversions that are common to most
738 /// operators (C99 6.3). The conversions of array and function types are
739 /// sometimes suppressed. For example, the array->pointer conversion doesn't
740 /// apply if the array is an argument to the sizeof or address (&) operators.
741 /// In these instances, this routine should *not* be called.
742 ExprResult Sema::UsualUnaryConversions(Expr *E) {
743   // First, convert to an r-value.
744   ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
745   if (Res.isInvalid())
746     return ExprError();
747   E = Res.get();
748 
749   QualType Ty = E->getType();
750   assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
751 
752   // Half FP have to be promoted to float unless it is natively supported
753   if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
754     return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
755 
756   // Try to perform integral promotions if the object has a theoretically
757   // promotable type.
758   if (Ty->isIntegralOrUnscopedEnumerationType()) {
759     // C99 6.3.1.1p2:
760     //
761     //   The following may be used in an expression wherever an int or
762     //   unsigned int may be used:
763     //     - an object or expression with an integer type whose integer
764     //       conversion rank is less than or equal to the rank of int
765     //       and unsigned int.
766     //     - A bit-field of type _Bool, int, signed int, or unsigned int.
767     //
768     //   If an int can represent all values of the original type, the
769     //   value is converted to an int; otherwise, it is converted to an
770     //   unsigned int. These are called the integer promotions. All
771     //   other types are unchanged by the integer promotions.
772 
773     QualType PTy = Context.isPromotableBitField(E);
774     if (!PTy.isNull()) {
775       E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
776       return E;
777     }
778     if (Ty->isPromotableIntegerType()) {
779       QualType PT = Context.getPromotedIntegerType(Ty);
780       E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
781       return E;
782     }
783   }
784   return E;
785 }
786 
787 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
788 /// do not have a prototype. Arguments that have type float or __fp16
789 /// are promoted to double. All other argument types are converted by
790 /// UsualUnaryConversions().
791 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
792   QualType Ty = E->getType();
793   assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
794 
795   ExprResult Res = UsualUnaryConversions(E);
796   if (Res.isInvalid())
797     return ExprError();
798   E = Res.get();
799 
800   // If this is a 'float'  or '__fp16' (CVR qualified or typedef)
801   // promote to double.
802   // Note that default argument promotion applies only to float (and
803   // half/fp16); it does not apply to _Float16.
804   const BuiltinType *BTy = Ty->getAs<BuiltinType>();
805   if (BTy && (BTy->getKind() == BuiltinType::Half ||
806               BTy->getKind() == BuiltinType::Float)) {
807     if (getLangOpts().OpenCL &&
808         !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
809         if (BTy->getKind() == BuiltinType::Half) {
810             E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
811         }
812     } else {
813       E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
814     }
815   }
816 
817   // C++ performs lvalue-to-rvalue conversion as a default argument
818   // promotion, even on class types, but note:
819   //   C++11 [conv.lval]p2:
820   //     When an lvalue-to-rvalue conversion occurs in an unevaluated
821   //     operand or a subexpression thereof the value contained in the
822   //     referenced object is not accessed. Otherwise, if the glvalue
823   //     has a class type, the conversion copy-initializes a temporary
824   //     of type T from the glvalue and the result of the conversion
825   //     is a prvalue for the temporary.
826   // FIXME: add some way to gate this entire thing for correctness in
827   // potentially potentially evaluated contexts.
828   if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
829     ExprResult Temp = PerformCopyInitialization(
830                        InitializedEntity::InitializeTemporary(E->getType()),
831                                                 E->getExprLoc(), E);
832     if (Temp.isInvalid())
833       return ExprError();
834     E = Temp.get();
835   }
836 
837   return E;
838 }
839 
840 /// Determine the degree of POD-ness for an expression.
841 /// Incomplete types are considered POD, since this check can be performed
842 /// when we're in an unevaluated context.
843 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
844   if (Ty->isIncompleteType()) {
845     // C++11 [expr.call]p7:
846     //   After these conversions, if the argument does not have arithmetic,
847     //   enumeration, pointer, pointer to member, or class type, the program
848     //   is ill-formed.
849     //
850     // Since we've already performed array-to-pointer and function-to-pointer
851     // decay, the only such type in C++ is cv void. This also handles
852     // initializer lists as variadic arguments.
853     if (Ty->isVoidType())
854       return VAK_Invalid;
855 
856     if (Ty->isObjCObjectType())
857       return VAK_Invalid;
858     return VAK_Valid;
859   }
860 
861   if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
862     return VAK_Invalid;
863 
864   if (Ty.isCXX98PODType(Context))
865     return VAK_Valid;
866 
867   // C++11 [expr.call]p7:
868   //   Passing a potentially-evaluated argument of class type (Clause 9)
869   //   having a non-trivial copy constructor, a non-trivial move constructor,
870   //   or a non-trivial destructor, with no corresponding parameter,
871   //   is conditionally-supported with implementation-defined semantics.
872   if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
873     if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
874       if (!Record->hasNonTrivialCopyConstructor() &&
875           !Record->hasNonTrivialMoveConstructor() &&
876           !Record->hasNonTrivialDestructor())
877         return VAK_ValidInCXX11;
878 
879   if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
880     return VAK_Valid;
881 
882   if (Ty->isObjCObjectType())
883     return VAK_Invalid;
884 
885   if (getLangOpts().MSVCCompat)
886     return VAK_MSVCUndefined;
887 
888   // FIXME: In C++11, these cases are conditionally-supported, meaning we're
889   // permitted to reject them. We should consider doing so.
890   return VAK_Undefined;
891 }
892 
893 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
894   // Don't allow one to pass an Objective-C interface to a vararg.
895   const QualType &Ty = E->getType();
896   VarArgKind VAK = isValidVarArgType(Ty);
897 
898   // Complain about passing non-POD types through varargs.
899   switch (VAK) {
900   case VAK_ValidInCXX11:
901     DiagRuntimeBehavior(
902         E->getBeginLoc(), nullptr,
903         PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT);
904     LLVM_FALLTHROUGH;
905   case VAK_Valid:
906     if (Ty->isRecordType()) {
907       // This is unlikely to be what the user intended. If the class has a
908       // 'c_str' member function, the user probably meant to call that.
909       DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
910                           PDiag(diag::warn_pass_class_arg_to_vararg)
911                               << Ty << CT << hasCStrMethod(E) << ".c_str()");
912     }
913     break;
914 
915   case VAK_Undefined:
916   case VAK_MSVCUndefined:
917     DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
918                         PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
919                             << getLangOpts().CPlusPlus11 << Ty << CT);
920     break;
921 
922   case VAK_Invalid:
923     if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
924       Diag(E->getBeginLoc(),
925            diag::err_cannot_pass_non_trivial_c_struct_to_vararg)
926           << Ty << CT;
927     else if (Ty->isObjCObjectType())
928       DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
929                           PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
930                               << Ty << CT);
931     else
932       Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg)
933           << isa<InitListExpr>(E) << Ty << CT;
934     break;
935   }
936 }
937 
938 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
939 /// will create a trap if the resulting type is not a POD type.
940 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
941                                                   FunctionDecl *FDecl) {
942   if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
943     // Strip the unbridged-cast placeholder expression off, if applicable.
944     if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
945         (CT == VariadicMethod ||
946          (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
947       E = stripARCUnbridgedCast(E);
948 
949     // Otherwise, do normal placeholder checking.
950     } else {
951       ExprResult ExprRes = CheckPlaceholderExpr(E);
952       if (ExprRes.isInvalid())
953         return ExprError();
954       E = ExprRes.get();
955     }
956   }
957 
958   ExprResult ExprRes = DefaultArgumentPromotion(E);
959   if (ExprRes.isInvalid())
960     return ExprError();
961   E = ExprRes.get();
962 
963   // Diagnostics regarding non-POD argument types are
964   // emitted along with format string checking in Sema::CheckFunctionCall().
965   if (isValidVarArgType(E->getType()) == VAK_Undefined) {
966     // Turn this into a trap.
967     CXXScopeSpec SS;
968     SourceLocation TemplateKWLoc;
969     UnqualifiedId Name;
970     Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
971                        E->getBeginLoc());
972     ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name,
973                                           /*HasTrailingLParen=*/true,
974                                           /*IsAddressOfOperand=*/false);
975     if (TrapFn.isInvalid())
976       return ExprError();
977 
978     ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(),
979                                     None, E->getEndLoc());
980     if (Call.isInvalid())
981       return ExprError();
982 
983     ExprResult Comma =
984         ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E);
985     if (Comma.isInvalid())
986       return ExprError();
987     return Comma.get();
988   }
989 
990   if (!getLangOpts().CPlusPlus &&
991       RequireCompleteType(E->getExprLoc(), E->getType(),
992                           diag::err_call_incomplete_argument))
993     return ExprError();
994 
995   return E;
996 }
997 
998 /// Converts an integer to complex float type.  Helper function of
999 /// UsualArithmeticConversions()
1000 ///
1001 /// \return false if the integer expression is an integer type and is
1002 /// successfully converted to the complex type.
1003 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
1004                                                   ExprResult &ComplexExpr,
1005                                                   QualType IntTy,
1006                                                   QualType ComplexTy,
1007                                                   bool SkipCast) {
1008   if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
1009   if (SkipCast) return false;
1010   if (IntTy->isIntegerType()) {
1011     QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
1012     IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
1013     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1014                                   CK_FloatingRealToComplex);
1015   } else {
1016     assert(IntTy->isComplexIntegerType());
1017     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1018                                   CK_IntegralComplexToFloatingComplex);
1019   }
1020   return false;
1021 }
1022 
1023 /// Handle arithmetic conversion with complex types.  Helper function of
1024 /// UsualArithmeticConversions()
1025 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
1026                                              ExprResult &RHS, QualType LHSType,
1027                                              QualType RHSType,
1028                                              bool IsCompAssign) {
1029   // if we have an integer operand, the result is the complex type.
1030   if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
1031                                              /*skipCast*/false))
1032     return LHSType;
1033   if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
1034                                              /*skipCast*/IsCompAssign))
1035     return RHSType;
1036 
1037   // This handles complex/complex, complex/float, or float/complex.
1038   // When both operands are complex, the shorter operand is converted to the
1039   // type of the longer, and that is the type of the result. This corresponds
1040   // to what is done when combining two real floating-point operands.
1041   // The fun begins when size promotion occur across type domains.
1042   // From H&S 6.3.4: When one operand is complex and the other is a real
1043   // floating-point type, the less precise type is converted, within it's
1044   // real or complex domain, to the precision of the other type. For example,
1045   // when combining a "long double" with a "double _Complex", the
1046   // "double _Complex" is promoted to "long double _Complex".
1047 
1048   // Compute the rank of the two types, regardless of whether they are complex.
1049   int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1050 
1051   auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
1052   auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
1053   QualType LHSElementType =
1054       LHSComplexType ? LHSComplexType->getElementType() : LHSType;
1055   QualType RHSElementType =
1056       RHSComplexType ? RHSComplexType->getElementType() : RHSType;
1057 
1058   QualType ResultType = S.Context.getComplexType(LHSElementType);
1059   if (Order < 0) {
1060     // Promote the precision of the LHS if not an assignment.
1061     ResultType = S.Context.getComplexType(RHSElementType);
1062     if (!IsCompAssign) {
1063       if (LHSComplexType)
1064         LHS =
1065             S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
1066       else
1067         LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
1068     }
1069   } else if (Order > 0) {
1070     // Promote the precision of the RHS.
1071     if (RHSComplexType)
1072       RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
1073     else
1074       RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
1075   }
1076   return ResultType;
1077 }
1078 
1079 /// Handle arithmetic conversion from integer to float.  Helper function
1080 /// of UsualArithmeticConversions()
1081 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1082                                            ExprResult &IntExpr,
1083                                            QualType FloatTy, QualType IntTy,
1084                                            bool ConvertFloat, bool ConvertInt) {
1085   if (IntTy->isIntegerType()) {
1086     if (ConvertInt)
1087       // Convert intExpr to the lhs floating point type.
1088       IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1089                                     CK_IntegralToFloating);
1090     return FloatTy;
1091   }
1092 
1093   // Convert both sides to the appropriate complex float.
1094   assert(IntTy->isComplexIntegerType());
1095   QualType result = S.Context.getComplexType(FloatTy);
1096 
1097   // _Complex int -> _Complex float
1098   if (ConvertInt)
1099     IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1100                                   CK_IntegralComplexToFloatingComplex);
1101 
1102   // float -> _Complex float
1103   if (ConvertFloat)
1104     FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1105                                     CK_FloatingRealToComplex);
1106 
1107   return result;
1108 }
1109 
1110 /// Handle arithmethic conversion with floating point types.  Helper
1111 /// function of UsualArithmeticConversions()
1112 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1113                                       ExprResult &RHS, QualType LHSType,
1114                                       QualType RHSType, bool IsCompAssign) {
1115   bool LHSFloat = LHSType->isRealFloatingType();
1116   bool RHSFloat = RHSType->isRealFloatingType();
1117 
1118   // If we have two real floating types, convert the smaller operand
1119   // to the bigger result.
1120   if (LHSFloat && RHSFloat) {
1121     int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1122     if (order > 0) {
1123       RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1124       return LHSType;
1125     }
1126 
1127     assert(order < 0 && "illegal float comparison");
1128     if (!IsCompAssign)
1129       LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1130     return RHSType;
1131   }
1132 
1133   if (LHSFloat) {
1134     // Half FP has to be promoted to float unless it is natively supported
1135     if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1136       LHSType = S.Context.FloatTy;
1137 
1138     return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1139                                       /*ConvertFloat=*/!IsCompAssign,
1140                                       /*ConvertInt=*/ true);
1141   }
1142   assert(RHSFloat);
1143   return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1144                                     /*convertInt=*/ true,
1145                                     /*convertFloat=*/!IsCompAssign);
1146 }
1147 
1148 /// Diagnose attempts to convert between __float128 and long double if
1149 /// there is no support for such conversion. Helper function of
1150 /// UsualArithmeticConversions().
1151 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1152                                       QualType RHSType) {
1153   /*  No issue converting if at least one of the types is not a floating point
1154       type or the two types have the same rank.
1155   */
1156   if (!LHSType->isFloatingType() || !RHSType->isFloatingType() ||
1157       S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0)
1158     return false;
1159 
1160   assert(LHSType->isFloatingType() && RHSType->isFloatingType() &&
1161          "The remaining types must be floating point types.");
1162 
1163   auto *LHSComplex = LHSType->getAs<ComplexType>();
1164   auto *RHSComplex = RHSType->getAs<ComplexType>();
1165 
1166   QualType LHSElemType = LHSComplex ?
1167     LHSComplex->getElementType() : LHSType;
1168   QualType RHSElemType = RHSComplex ?
1169     RHSComplex->getElementType() : RHSType;
1170 
1171   // No issue if the two types have the same representation
1172   if (&S.Context.getFloatTypeSemantics(LHSElemType) ==
1173       &S.Context.getFloatTypeSemantics(RHSElemType))
1174     return false;
1175 
1176   bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty &&
1177                                 RHSElemType == S.Context.LongDoubleTy);
1178   Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy &&
1179                             RHSElemType == S.Context.Float128Ty);
1180 
1181   // We've handled the situation where __float128 and long double have the same
1182   // representation. We allow all conversions for all possible long double types
1183   // except PPC's double double.
1184   return Float128AndLongDouble &&
1185     (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) ==
1186      &llvm::APFloat::PPCDoubleDouble());
1187 }
1188 
1189 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1190 
1191 namespace {
1192 /// These helper callbacks are placed in an anonymous namespace to
1193 /// permit their use as function template parameters.
1194 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1195   return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1196 }
1197 
1198 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1199   return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1200                              CK_IntegralComplexCast);
1201 }
1202 }
1203 
1204 /// Handle integer arithmetic conversions.  Helper function of
1205 /// UsualArithmeticConversions()
1206 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1207 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1208                                         ExprResult &RHS, QualType LHSType,
1209                                         QualType RHSType, bool IsCompAssign) {
1210   // The rules for this case are in C99 6.3.1.8
1211   int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1212   bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1213   bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1214   if (LHSSigned == RHSSigned) {
1215     // Same signedness; use the higher-ranked type
1216     if (order >= 0) {
1217       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1218       return LHSType;
1219     } else if (!IsCompAssign)
1220       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1221     return RHSType;
1222   } else if (order != (LHSSigned ? 1 : -1)) {
1223     // The unsigned type has greater than or equal rank to the
1224     // signed type, so use the unsigned type
1225     if (RHSSigned) {
1226       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1227       return LHSType;
1228     } else if (!IsCompAssign)
1229       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1230     return RHSType;
1231   } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1232     // The two types are different widths; if we are here, that
1233     // means the signed type is larger than the unsigned type, so
1234     // use the signed type.
1235     if (LHSSigned) {
1236       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1237       return LHSType;
1238     } else if (!IsCompAssign)
1239       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1240     return RHSType;
1241   } else {
1242     // The signed type is higher-ranked than the unsigned type,
1243     // but isn't actually any bigger (like unsigned int and long
1244     // on most 32-bit systems).  Use the unsigned type corresponding
1245     // to the signed type.
1246     QualType result =
1247       S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1248     RHS = (*doRHSCast)(S, RHS.get(), result);
1249     if (!IsCompAssign)
1250       LHS = (*doLHSCast)(S, LHS.get(), result);
1251     return result;
1252   }
1253 }
1254 
1255 /// Handle conversions with GCC complex int extension.  Helper function
1256 /// of UsualArithmeticConversions()
1257 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1258                                            ExprResult &RHS, QualType LHSType,
1259                                            QualType RHSType,
1260                                            bool IsCompAssign) {
1261   const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1262   const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1263 
1264   if (LHSComplexInt && RHSComplexInt) {
1265     QualType LHSEltType = LHSComplexInt->getElementType();
1266     QualType RHSEltType = RHSComplexInt->getElementType();
1267     QualType ScalarType =
1268       handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1269         (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1270 
1271     return S.Context.getComplexType(ScalarType);
1272   }
1273 
1274   if (LHSComplexInt) {
1275     QualType LHSEltType = LHSComplexInt->getElementType();
1276     QualType ScalarType =
1277       handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1278         (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1279     QualType ComplexType = S.Context.getComplexType(ScalarType);
1280     RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1281                               CK_IntegralRealToComplex);
1282 
1283     return ComplexType;
1284   }
1285 
1286   assert(RHSComplexInt);
1287 
1288   QualType RHSEltType = RHSComplexInt->getElementType();
1289   QualType ScalarType =
1290     handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1291       (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1292   QualType ComplexType = S.Context.getComplexType(ScalarType);
1293 
1294   if (!IsCompAssign)
1295     LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1296                               CK_IntegralRealToComplex);
1297   return ComplexType;
1298 }
1299 
1300 /// Return the rank of a given fixed point or integer type. The value itself
1301 /// doesn't matter, but the values must be increasing with proper increasing
1302 /// rank as described in N1169 4.1.1.
1303 static unsigned GetFixedPointRank(QualType Ty) {
1304   const auto *BTy = Ty->getAs<BuiltinType>();
1305   assert(BTy && "Expected a builtin type.");
1306 
1307   switch (BTy->getKind()) {
1308   case BuiltinType::ShortFract:
1309   case BuiltinType::UShortFract:
1310   case BuiltinType::SatShortFract:
1311   case BuiltinType::SatUShortFract:
1312     return 1;
1313   case BuiltinType::Fract:
1314   case BuiltinType::UFract:
1315   case BuiltinType::SatFract:
1316   case BuiltinType::SatUFract:
1317     return 2;
1318   case BuiltinType::LongFract:
1319   case BuiltinType::ULongFract:
1320   case BuiltinType::SatLongFract:
1321   case BuiltinType::SatULongFract:
1322     return 3;
1323   case BuiltinType::ShortAccum:
1324   case BuiltinType::UShortAccum:
1325   case BuiltinType::SatShortAccum:
1326   case BuiltinType::SatUShortAccum:
1327     return 4;
1328   case BuiltinType::Accum:
1329   case BuiltinType::UAccum:
1330   case BuiltinType::SatAccum:
1331   case BuiltinType::SatUAccum:
1332     return 5;
1333   case BuiltinType::LongAccum:
1334   case BuiltinType::ULongAccum:
1335   case BuiltinType::SatLongAccum:
1336   case BuiltinType::SatULongAccum:
1337     return 6;
1338   default:
1339     if (BTy->isInteger())
1340       return 0;
1341     llvm_unreachable("Unexpected fixed point or integer type");
1342   }
1343 }
1344 
1345 /// handleFixedPointConversion - Fixed point operations between fixed
1346 /// point types and integers or other fixed point types do not fall under
1347 /// usual arithmetic conversion since these conversions could result in loss
1348 /// of precsision (N1169 4.1.4). These operations should be calculated with
1349 /// the full precision of their result type (N1169 4.1.6.2.1).
1350 static QualType handleFixedPointConversion(Sema &S, QualType LHSTy,
1351                                            QualType RHSTy) {
1352   assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) &&
1353          "Expected at least one of the operands to be a fixed point type");
1354   assert((LHSTy->isFixedPointOrIntegerType() ||
1355           RHSTy->isFixedPointOrIntegerType()) &&
1356          "Special fixed point arithmetic operation conversions are only "
1357          "applied to ints or other fixed point types");
1358 
1359   // If one operand has signed fixed-point type and the other operand has
1360   // unsigned fixed-point type, then the unsigned fixed-point operand is
1361   // converted to its corresponding signed fixed-point type and the resulting
1362   // type is the type of the converted operand.
1363   if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType())
1364     LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy);
1365   else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType())
1366     RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy);
1367 
1368   // The result type is the type with the highest rank, whereby a fixed-point
1369   // conversion rank is always greater than an integer conversion rank; if the
1370   // type of either of the operands is a saturating fixedpoint type, the result
1371   // type shall be the saturating fixed-point type corresponding to the type
1372   // with the highest rank; the resulting value is converted (taking into
1373   // account rounding and overflow) to the precision of the resulting type.
1374   // Same ranks between signed and unsigned types are resolved earlier, so both
1375   // types are either signed or both unsigned at this point.
1376   unsigned LHSTyRank = GetFixedPointRank(LHSTy);
1377   unsigned RHSTyRank = GetFixedPointRank(RHSTy);
1378 
1379   QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy;
1380 
1381   if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType())
1382     ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy);
1383 
1384   return ResultTy;
1385 }
1386 
1387 /// Check that the usual arithmetic conversions can be performed on this pair of
1388 /// expressions that might be of enumeration type.
1389 static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS,
1390                                            SourceLocation Loc,
1391                                            Sema::ArithConvKind ACK) {
1392   // C++2a [expr.arith.conv]p1:
1393   //   If one operand is of enumeration type and the other operand is of a
1394   //   different enumeration type or a floating-point type, this behavior is
1395   //   deprecated ([depr.arith.conv.enum]).
1396   //
1397   // Warn on this in all language modes. Produce a deprecation warning in C++20.
1398   // Eventually we will presumably reject these cases (in C++23 onwards?).
1399   QualType L = LHS->getType(), R = RHS->getType();
1400   bool LEnum = L->isUnscopedEnumerationType(),
1401        REnum = R->isUnscopedEnumerationType();
1402   bool IsCompAssign = ACK == Sema::ACK_CompAssign;
1403   if ((!IsCompAssign && LEnum && R->isFloatingType()) ||
1404       (REnum && L->isFloatingType())) {
1405     S.Diag(Loc, S.getLangOpts().CPlusPlus20
1406                     ? diag::warn_arith_conv_enum_float_cxx20
1407                     : diag::warn_arith_conv_enum_float)
1408         << LHS->getSourceRange() << RHS->getSourceRange()
1409         << (int)ACK << LEnum << L << R;
1410   } else if (!IsCompAssign && LEnum && REnum &&
1411              !S.Context.hasSameUnqualifiedType(L, R)) {
1412     unsigned DiagID;
1413     if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() ||
1414         !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) {
1415       // If either enumeration type is unnamed, it's less likely that the
1416       // user cares about this, but this situation is still deprecated in
1417       // C++2a. Use a different warning group.
1418       DiagID = S.getLangOpts().CPlusPlus20
1419                     ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20
1420                     : diag::warn_arith_conv_mixed_anon_enum_types;
1421     } else if (ACK == Sema::ACK_Conditional) {
1422       // Conditional expressions are separated out because they have
1423       // historically had a different warning flag.
1424       DiagID = S.getLangOpts().CPlusPlus20
1425                    ? diag::warn_conditional_mixed_enum_types_cxx20
1426                    : diag::warn_conditional_mixed_enum_types;
1427     } else if (ACK == Sema::ACK_Comparison) {
1428       // Comparison expressions are separated out because they have
1429       // historically had a different warning flag.
1430       DiagID = S.getLangOpts().CPlusPlus20
1431                    ? diag::warn_comparison_mixed_enum_types_cxx20
1432                    : diag::warn_comparison_mixed_enum_types;
1433     } else {
1434       DiagID = S.getLangOpts().CPlusPlus20
1435                    ? diag::warn_arith_conv_mixed_enum_types_cxx20
1436                    : diag::warn_arith_conv_mixed_enum_types;
1437     }
1438     S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
1439                         << (int)ACK << L << R;
1440   }
1441 }
1442 
1443 /// UsualArithmeticConversions - Performs various conversions that are common to
1444 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1445 /// routine returns the first non-arithmetic type found. The client is
1446 /// responsible for emitting appropriate error diagnostics.
1447 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1448                                           SourceLocation Loc,
1449                                           ArithConvKind ACK) {
1450   checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK);
1451 
1452   if (ACK != ACK_CompAssign) {
1453     LHS = UsualUnaryConversions(LHS.get());
1454     if (LHS.isInvalid())
1455       return QualType();
1456   }
1457 
1458   RHS = UsualUnaryConversions(RHS.get());
1459   if (RHS.isInvalid())
1460     return QualType();
1461 
1462   // For conversion purposes, we ignore any qualifiers.
1463   // For example, "const float" and "float" are equivalent.
1464   QualType LHSType =
1465     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1466   QualType RHSType =
1467     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1468 
1469   // For conversion purposes, we ignore any atomic qualifier on the LHS.
1470   if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1471     LHSType = AtomicLHS->getValueType();
1472 
1473   // If both types are identical, no conversion is needed.
1474   if (LHSType == RHSType)
1475     return LHSType;
1476 
1477   // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1478   // The caller can deal with this (e.g. pointer + int).
1479   if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1480     return QualType();
1481 
1482   // Apply unary and bitfield promotions to the LHS's type.
1483   QualType LHSUnpromotedType = LHSType;
1484   if (LHSType->isPromotableIntegerType())
1485     LHSType = Context.getPromotedIntegerType(LHSType);
1486   QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1487   if (!LHSBitfieldPromoteTy.isNull())
1488     LHSType = LHSBitfieldPromoteTy;
1489   if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign)
1490     LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1491 
1492   // If both types are identical, no conversion is needed.
1493   if (LHSType == RHSType)
1494     return LHSType;
1495 
1496   // ExtInt types aren't subject to conversions between them or normal integers,
1497   // so this fails.
1498   if(LHSType->isExtIntType() || RHSType->isExtIntType())
1499     return QualType();
1500 
1501   // At this point, we have two different arithmetic types.
1502 
1503   // Diagnose attempts to convert between __float128 and long double where
1504   // such conversions currently can't be handled.
1505   if (unsupportedTypeConversion(*this, LHSType, RHSType))
1506     return QualType();
1507 
1508   // Handle complex types first (C99 6.3.1.8p1).
1509   if (LHSType->isComplexType() || RHSType->isComplexType())
1510     return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1511                                         ACK == ACK_CompAssign);
1512 
1513   // Now handle "real" floating types (i.e. float, double, long double).
1514   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1515     return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1516                                  ACK == ACK_CompAssign);
1517 
1518   // Handle GCC complex int extension.
1519   if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1520     return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1521                                       ACK == ACK_CompAssign);
1522 
1523   if (LHSType->isFixedPointType() || RHSType->isFixedPointType())
1524     return handleFixedPointConversion(*this, LHSType, RHSType);
1525 
1526   // Finally, we have two differing integer types.
1527   return handleIntegerConversion<doIntegralCast, doIntegralCast>
1528            (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign);
1529 }
1530 
1531 //===----------------------------------------------------------------------===//
1532 //  Semantic Analysis for various Expression Types
1533 //===----------------------------------------------------------------------===//
1534 
1535 
1536 ExprResult
1537 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1538                                 SourceLocation DefaultLoc,
1539                                 SourceLocation RParenLoc,
1540                                 Expr *ControllingExpr,
1541                                 ArrayRef<ParsedType> ArgTypes,
1542                                 ArrayRef<Expr *> ArgExprs) {
1543   unsigned NumAssocs = ArgTypes.size();
1544   assert(NumAssocs == ArgExprs.size());
1545 
1546   TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1547   for (unsigned i = 0; i < NumAssocs; ++i) {
1548     if (ArgTypes[i])
1549       (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1550     else
1551       Types[i] = nullptr;
1552   }
1553 
1554   ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1555                                              ControllingExpr,
1556                                              llvm::makeArrayRef(Types, NumAssocs),
1557                                              ArgExprs);
1558   delete [] Types;
1559   return ER;
1560 }
1561 
1562 ExprResult
1563 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1564                                  SourceLocation DefaultLoc,
1565                                  SourceLocation RParenLoc,
1566                                  Expr *ControllingExpr,
1567                                  ArrayRef<TypeSourceInfo *> Types,
1568                                  ArrayRef<Expr *> Exprs) {
1569   unsigned NumAssocs = Types.size();
1570   assert(NumAssocs == Exprs.size());
1571 
1572   // Decay and strip qualifiers for the controlling expression type, and handle
1573   // placeholder type replacement. See committee discussion from WG14 DR423.
1574   {
1575     EnterExpressionEvaluationContext Unevaluated(
1576         *this, Sema::ExpressionEvaluationContext::Unevaluated);
1577     ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
1578     if (R.isInvalid())
1579       return ExprError();
1580     ControllingExpr = R.get();
1581   }
1582 
1583   // The controlling expression is an unevaluated operand, so side effects are
1584   // likely unintended.
1585   if (!inTemplateInstantiation() &&
1586       ControllingExpr->HasSideEffects(Context, false))
1587     Diag(ControllingExpr->getExprLoc(),
1588          diag::warn_side_effects_unevaluated_context);
1589 
1590   bool TypeErrorFound = false,
1591        IsResultDependent = ControllingExpr->isTypeDependent(),
1592        ContainsUnexpandedParameterPack
1593          = ControllingExpr->containsUnexpandedParameterPack();
1594 
1595   for (unsigned i = 0; i < NumAssocs; ++i) {
1596     if (Exprs[i]->containsUnexpandedParameterPack())
1597       ContainsUnexpandedParameterPack = true;
1598 
1599     if (Types[i]) {
1600       if (Types[i]->getType()->containsUnexpandedParameterPack())
1601         ContainsUnexpandedParameterPack = true;
1602 
1603       if (Types[i]->getType()->isDependentType()) {
1604         IsResultDependent = true;
1605       } else {
1606         // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1607         // complete object type other than a variably modified type."
1608         unsigned D = 0;
1609         if (Types[i]->getType()->isIncompleteType())
1610           D = diag::err_assoc_type_incomplete;
1611         else if (!Types[i]->getType()->isObjectType())
1612           D = diag::err_assoc_type_nonobject;
1613         else if (Types[i]->getType()->isVariablyModifiedType())
1614           D = diag::err_assoc_type_variably_modified;
1615 
1616         if (D != 0) {
1617           Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1618             << Types[i]->getTypeLoc().getSourceRange()
1619             << Types[i]->getType();
1620           TypeErrorFound = true;
1621         }
1622 
1623         // C11 6.5.1.1p2 "No two generic associations in the same generic
1624         // selection shall specify compatible types."
1625         for (unsigned j = i+1; j < NumAssocs; ++j)
1626           if (Types[j] && !Types[j]->getType()->isDependentType() &&
1627               Context.typesAreCompatible(Types[i]->getType(),
1628                                          Types[j]->getType())) {
1629             Diag(Types[j]->getTypeLoc().getBeginLoc(),
1630                  diag::err_assoc_compatible_types)
1631               << Types[j]->getTypeLoc().getSourceRange()
1632               << Types[j]->getType()
1633               << Types[i]->getType();
1634             Diag(Types[i]->getTypeLoc().getBeginLoc(),
1635                  diag::note_compat_assoc)
1636               << Types[i]->getTypeLoc().getSourceRange()
1637               << Types[i]->getType();
1638             TypeErrorFound = true;
1639           }
1640       }
1641     }
1642   }
1643   if (TypeErrorFound)
1644     return ExprError();
1645 
1646   // If we determined that the generic selection is result-dependent, don't
1647   // try to compute the result expression.
1648   if (IsResultDependent)
1649     return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types,
1650                                         Exprs, DefaultLoc, RParenLoc,
1651                                         ContainsUnexpandedParameterPack);
1652 
1653   SmallVector<unsigned, 1> CompatIndices;
1654   unsigned DefaultIndex = -1U;
1655   for (unsigned i = 0; i < NumAssocs; ++i) {
1656     if (!Types[i])
1657       DefaultIndex = i;
1658     else if (Context.typesAreCompatible(ControllingExpr->getType(),
1659                                         Types[i]->getType()))
1660       CompatIndices.push_back(i);
1661   }
1662 
1663   // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1664   // type compatible with at most one of the types named in its generic
1665   // association list."
1666   if (CompatIndices.size() > 1) {
1667     // We strip parens here because the controlling expression is typically
1668     // parenthesized in macro definitions.
1669     ControllingExpr = ControllingExpr->IgnoreParens();
1670     Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match)
1671         << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1672         << (unsigned)CompatIndices.size();
1673     for (unsigned I : CompatIndices) {
1674       Diag(Types[I]->getTypeLoc().getBeginLoc(),
1675            diag::note_compat_assoc)
1676         << Types[I]->getTypeLoc().getSourceRange()
1677         << Types[I]->getType();
1678     }
1679     return ExprError();
1680   }
1681 
1682   // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1683   // its controlling expression shall have type compatible with exactly one of
1684   // the types named in its generic association list."
1685   if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1686     // We strip parens here because the controlling expression is typically
1687     // parenthesized in macro definitions.
1688     ControllingExpr = ControllingExpr->IgnoreParens();
1689     Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match)
1690         << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1691     return ExprError();
1692   }
1693 
1694   // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1695   // type name that is compatible with the type of the controlling expression,
1696   // then the result expression of the generic selection is the expression
1697   // in that generic association. Otherwise, the result expression of the
1698   // generic selection is the expression in the default generic association."
1699   unsigned ResultIndex =
1700     CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1701 
1702   return GenericSelectionExpr::Create(
1703       Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1704       ContainsUnexpandedParameterPack, ResultIndex);
1705 }
1706 
1707 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1708 /// location of the token and the offset of the ud-suffix within it.
1709 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1710                                      unsigned Offset) {
1711   return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1712                                         S.getLangOpts());
1713 }
1714 
1715 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1716 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
1717 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1718                                                  IdentifierInfo *UDSuffix,
1719                                                  SourceLocation UDSuffixLoc,
1720                                                  ArrayRef<Expr*> Args,
1721                                                  SourceLocation LitEndLoc) {
1722   assert(Args.size() <= 2 && "too many arguments for literal operator");
1723 
1724   QualType ArgTy[2];
1725   for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1726     ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1727     if (ArgTy[ArgIdx]->isArrayType())
1728       ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1729   }
1730 
1731   DeclarationName OpName =
1732     S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1733   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1734   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1735 
1736   LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1737   if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1738                               /*AllowRaw*/ false, /*AllowTemplate*/ false,
1739                               /*AllowStringTemplate*/ false,
1740                               /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
1741     return ExprError();
1742 
1743   return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1744 }
1745 
1746 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1747 /// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
1748 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1749 /// multiple tokens.  However, the common case is that StringToks points to one
1750 /// string.
1751 ///
1752 ExprResult
1753 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
1754   assert(!StringToks.empty() && "Must have at least one string!");
1755 
1756   StringLiteralParser Literal(StringToks, PP);
1757   if (Literal.hadError)
1758     return ExprError();
1759 
1760   SmallVector<SourceLocation, 4> StringTokLocs;
1761   for (const Token &Tok : StringToks)
1762     StringTokLocs.push_back(Tok.getLocation());
1763 
1764   QualType CharTy = Context.CharTy;
1765   StringLiteral::StringKind Kind = StringLiteral::Ascii;
1766   if (Literal.isWide()) {
1767     CharTy = Context.getWideCharType();
1768     Kind = StringLiteral::Wide;
1769   } else if (Literal.isUTF8()) {
1770     if (getLangOpts().Char8)
1771       CharTy = Context.Char8Ty;
1772     Kind = StringLiteral::UTF8;
1773   } else if (Literal.isUTF16()) {
1774     CharTy = Context.Char16Ty;
1775     Kind = StringLiteral::UTF16;
1776   } else if (Literal.isUTF32()) {
1777     CharTy = Context.Char32Ty;
1778     Kind = StringLiteral::UTF32;
1779   } else if (Literal.isPascal()) {
1780     CharTy = Context.UnsignedCharTy;
1781   }
1782 
1783   // Warn on initializing an array of char from a u8 string literal; this
1784   // becomes ill-formed in C++2a.
1785   if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus20 &&
1786       !getLangOpts().Char8 && Kind == StringLiteral::UTF8) {
1787     Diag(StringTokLocs.front(), diag::warn_cxx20_compat_utf8_string);
1788 
1789     // Create removals for all 'u8' prefixes in the string literal(s). This
1790     // ensures C++2a compatibility (but may change the program behavior when
1791     // built by non-Clang compilers for which the execution character set is
1792     // not always UTF-8).
1793     auto RemovalDiag = PDiag(diag::note_cxx20_compat_utf8_string_remove_u8);
1794     SourceLocation RemovalDiagLoc;
1795     for (const Token &Tok : StringToks) {
1796       if (Tok.getKind() == tok::utf8_string_literal) {
1797         if (RemovalDiagLoc.isInvalid())
1798           RemovalDiagLoc = Tok.getLocation();
1799         RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange(
1800             Tok.getLocation(),
1801             Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2,
1802                                            getSourceManager(), getLangOpts())));
1803       }
1804     }
1805     Diag(RemovalDiagLoc, RemovalDiag);
1806   }
1807 
1808   QualType StrTy =
1809       Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars());
1810 
1811   // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1812   StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1813                                              Kind, Literal.Pascal, StrTy,
1814                                              &StringTokLocs[0],
1815                                              StringTokLocs.size());
1816   if (Literal.getUDSuffix().empty())
1817     return Lit;
1818 
1819   // We're building a user-defined literal.
1820   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1821   SourceLocation UDSuffixLoc =
1822     getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1823                    Literal.getUDSuffixOffset());
1824 
1825   // Make sure we're allowed user-defined literals here.
1826   if (!UDLScope)
1827     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1828 
1829   // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1830   //   operator "" X (str, len)
1831   QualType SizeType = Context.getSizeType();
1832 
1833   DeclarationName OpName =
1834     Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1835   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1836   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1837 
1838   QualType ArgTy[] = {
1839     Context.getArrayDecayedType(StrTy), SizeType
1840   };
1841 
1842   LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1843   switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1844                                 /*AllowRaw*/ false, /*AllowTemplate*/ false,
1845                                 /*AllowStringTemplate*/ true,
1846                                 /*DiagnoseMissing*/ true)) {
1847 
1848   case LOLR_Cooked: {
1849     llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1850     IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1851                                                     StringTokLocs[0]);
1852     Expr *Args[] = { Lit, LenArg };
1853 
1854     return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1855   }
1856 
1857   case LOLR_StringTemplate: {
1858     TemplateArgumentListInfo ExplicitArgs;
1859 
1860     unsigned CharBits = Context.getIntWidth(CharTy);
1861     bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1862     llvm::APSInt Value(CharBits, CharIsUnsigned);
1863 
1864     TemplateArgument TypeArg(CharTy);
1865     TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1866     ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1867 
1868     for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1869       Value = Lit->getCodeUnit(I);
1870       TemplateArgument Arg(Context, Value, CharTy);
1871       TemplateArgumentLocInfo ArgInfo;
1872       ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1873     }
1874     return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1875                                     &ExplicitArgs);
1876   }
1877   case LOLR_Raw:
1878   case LOLR_Template:
1879   case LOLR_ErrorNoDiagnostic:
1880     llvm_unreachable("unexpected literal operator lookup result");
1881   case LOLR_Error:
1882     return ExprError();
1883   }
1884   llvm_unreachable("unexpected literal operator lookup result");
1885 }
1886 
1887 DeclRefExpr *
1888 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1889                        SourceLocation Loc,
1890                        const CXXScopeSpec *SS) {
1891   DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1892   return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1893 }
1894 
1895 DeclRefExpr *
1896 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1897                        const DeclarationNameInfo &NameInfo,
1898                        const CXXScopeSpec *SS, NamedDecl *FoundD,
1899                        SourceLocation TemplateKWLoc,
1900                        const TemplateArgumentListInfo *TemplateArgs) {
1901   NestedNameSpecifierLoc NNS =
1902       SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc();
1903   return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc,
1904                           TemplateArgs);
1905 }
1906 
1907 NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) {
1908   // A declaration named in an unevaluated operand never constitutes an odr-use.
1909   if (isUnevaluatedContext())
1910     return NOUR_Unevaluated;
1911 
1912   // C++2a [basic.def.odr]p4:
1913   //   A variable x whose name appears as a potentially-evaluated expression e
1914   //   is odr-used by e unless [...] x is a reference that is usable in
1915   //   constant expressions.
1916   if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
1917     if (VD->getType()->isReferenceType() &&
1918         !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) &&
1919         VD->isUsableInConstantExpressions(Context))
1920       return NOUR_Constant;
1921   }
1922 
1923   // All remaining non-variable cases constitute an odr-use. For variables, we
1924   // need to wait and see how the expression is used.
1925   return NOUR_None;
1926 }
1927 
1928 /// BuildDeclRefExpr - Build an expression that references a
1929 /// declaration that does not require a closure capture.
1930 DeclRefExpr *
1931 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1932                        const DeclarationNameInfo &NameInfo,
1933                        NestedNameSpecifierLoc NNS, NamedDecl *FoundD,
1934                        SourceLocation TemplateKWLoc,
1935                        const TemplateArgumentListInfo *TemplateArgs) {
1936   bool RefersToCapturedVariable =
1937       isa<VarDecl>(D) &&
1938       NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
1939 
1940   DeclRefExpr *E = DeclRefExpr::Create(
1941       Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty,
1942       VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D));
1943   MarkDeclRefReferenced(E);
1944 
1945   // C++ [except.spec]p17:
1946   //   An exception-specification is considered to be needed when:
1947   //   - in an expression, the function is the unique lookup result or
1948   //     the selected member of a set of overloaded functions.
1949   //
1950   // We delay doing this until after we've built the function reference and
1951   // marked it as used so that:
1952   //  a) if the function is defaulted, we get errors from defining it before /
1953   //     instead of errors from computing its exception specification, and
1954   //  b) if the function is a defaulted comparison, we can use the body we
1955   //     build when defining it as input to the exception specification
1956   //     computation rather than computing a new body.
1957   if (auto *FPT = Ty->getAs<FunctionProtoType>()) {
1958     if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
1959       if (auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT))
1960         E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers()));
1961     }
1962   }
1963 
1964   if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
1965       Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() &&
1966       !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc()))
1967     getCurFunction()->recordUseOfWeak(E);
1968 
1969   FieldDecl *FD = dyn_cast<FieldDecl>(D);
1970   if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
1971     FD = IFD->getAnonField();
1972   if (FD) {
1973     UnusedPrivateFields.remove(FD);
1974     // Just in case we're building an illegal pointer-to-member.
1975     if (FD->isBitField())
1976       E->setObjectKind(OK_BitField);
1977   }
1978 
1979   // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
1980   // designates a bit-field.
1981   if (auto *BD = dyn_cast<BindingDecl>(D))
1982     if (auto *BE = BD->getBinding())
1983       E->setObjectKind(BE->getObjectKind());
1984 
1985   return E;
1986 }
1987 
1988 /// Decomposes the given name into a DeclarationNameInfo, its location, and
1989 /// possibly a list of template arguments.
1990 ///
1991 /// If this produces template arguments, it is permitted to call
1992 /// DecomposeTemplateName.
1993 ///
1994 /// This actually loses a lot of source location information for
1995 /// non-standard name kinds; we should consider preserving that in
1996 /// some way.
1997 void
1998 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1999                              TemplateArgumentListInfo &Buffer,
2000                              DeclarationNameInfo &NameInfo,
2001                              const TemplateArgumentListInfo *&TemplateArgs) {
2002   if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) {
2003     Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
2004     Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
2005 
2006     ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
2007                                        Id.TemplateId->NumArgs);
2008     translateTemplateArguments(TemplateArgsPtr, Buffer);
2009 
2010     TemplateName TName = Id.TemplateId->Template.get();
2011     SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
2012     NameInfo = Context.getNameForTemplate(TName, TNameLoc);
2013     TemplateArgs = &Buffer;
2014   } else {
2015     NameInfo = GetNameFromUnqualifiedId(Id);
2016     TemplateArgs = nullptr;
2017   }
2018 }
2019 
2020 static void emitEmptyLookupTypoDiagnostic(
2021     const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
2022     DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
2023     unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
2024   DeclContext *Ctx =
2025       SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
2026   if (!TC) {
2027     // Emit a special diagnostic for failed member lookups.
2028     // FIXME: computing the declaration context might fail here (?)
2029     if (Ctx)
2030       SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
2031                                                  << SS.getRange();
2032     else
2033       SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
2034     return;
2035   }
2036 
2037   std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
2038   bool DroppedSpecifier =
2039       TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
2040   unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
2041                         ? diag::note_implicit_param_decl
2042                         : diag::note_previous_decl;
2043   if (!Ctx)
2044     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
2045                          SemaRef.PDiag(NoteID));
2046   else
2047     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
2048                                  << Typo << Ctx << DroppedSpecifier
2049                                  << SS.getRange(),
2050                          SemaRef.PDiag(NoteID));
2051 }
2052 
2053 /// Diagnose an empty lookup.
2054 ///
2055 /// \return false if new lookup candidates were found
2056 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
2057                                CorrectionCandidateCallback &CCC,
2058                                TemplateArgumentListInfo *ExplicitTemplateArgs,
2059                                ArrayRef<Expr *> Args, TypoExpr **Out) {
2060   DeclarationName Name = R.getLookupName();
2061 
2062   unsigned diagnostic = diag::err_undeclared_var_use;
2063   unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
2064   if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
2065       Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
2066       Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
2067     diagnostic = diag::err_undeclared_use;
2068     diagnostic_suggest = diag::err_undeclared_use_suggest;
2069   }
2070 
2071   // If the original lookup was an unqualified lookup, fake an
2072   // unqualified lookup.  This is useful when (for example) the
2073   // original lookup would not have found something because it was a
2074   // dependent name.
2075   DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
2076   while (DC) {
2077     if (isa<CXXRecordDecl>(DC)) {
2078       LookupQualifiedName(R, DC);
2079 
2080       if (!R.empty()) {
2081         // Don't give errors about ambiguities in this lookup.
2082         R.suppressDiagnostics();
2083 
2084         // During a default argument instantiation the CurContext points
2085         // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
2086         // function parameter list, hence add an explicit check.
2087         bool isDefaultArgument =
2088             !CodeSynthesisContexts.empty() &&
2089             CodeSynthesisContexts.back().Kind ==
2090                 CodeSynthesisContext::DefaultFunctionArgumentInstantiation;
2091         CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
2092         bool isInstance = CurMethod &&
2093                           CurMethod->isInstance() &&
2094                           DC == CurMethod->getParent() && !isDefaultArgument;
2095 
2096         // Give a code modification hint to insert 'this->'.
2097         // TODO: fixit for inserting 'Base<T>::' in the other cases.
2098         // Actually quite difficult!
2099         if (getLangOpts().MSVCCompat)
2100           diagnostic = diag::ext_found_via_dependent_bases_lookup;
2101         if (isInstance) {
2102           Diag(R.getNameLoc(), diagnostic) << Name
2103             << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
2104           CheckCXXThisCapture(R.getNameLoc());
2105         } else {
2106           Diag(R.getNameLoc(), diagnostic) << Name;
2107         }
2108 
2109         // Do we really want to note all of these?
2110         for (NamedDecl *D : R)
2111           Diag(D->getLocation(), diag::note_dependent_var_use);
2112 
2113         // Return true if we are inside a default argument instantiation
2114         // and the found name refers to an instance member function, otherwise
2115         // the function calling DiagnoseEmptyLookup will try to create an
2116         // implicit member call and this is wrong for default argument.
2117         if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
2118           Diag(R.getNameLoc(), diag::err_member_call_without_object);
2119           return true;
2120         }
2121 
2122         // Tell the callee to try to recover.
2123         return false;
2124       }
2125 
2126       R.clear();
2127     }
2128 
2129     DC = DC->getLookupParent();
2130   }
2131 
2132   // We didn't find anything, so try to correct for a typo.
2133   TypoCorrection Corrected;
2134   if (S && Out) {
2135     SourceLocation TypoLoc = R.getNameLoc();
2136     assert(!ExplicitTemplateArgs &&
2137            "Diagnosing an empty lookup with explicit template args!");
2138     *Out = CorrectTypoDelayed(
2139         R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
2140         [=](const TypoCorrection &TC) {
2141           emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
2142                                         diagnostic, diagnostic_suggest);
2143         },
2144         nullptr, CTK_ErrorRecovery);
2145     if (*Out)
2146       return true;
2147   } else if (S &&
2148              (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
2149                                       S, &SS, CCC, CTK_ErrorRecovery))) {
2150     std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
2151     bool DroppedSpecifier =
2152         Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
2153     R.setLookupName(Corrected.getCorrection());
2154 
2155     bool AcceptableWithRecovery = false;
2156     bool AcceptableWithoutRecovery = false;
2157     NamedDecl *ND = Corrected.getFoundDecl();
2158     if (ND) {
2159       if (Corrected.isOverloaded()) {
2160         OverloadCandidateSet OCS(R.getNameLoc(),
2161                                  OverloadCandidateSet::CSK_Normal);
2162         OverloadCandidateSet::iterator Best;
2163         for (NamedDecl *CD : Corrected) {
2164           if (FunctionTemplateDecl *FTD =
2165                    dyn_cast<FunctionTemplateDecl>(CD))
2166             AddTemplateOverloadCandidate(
2167                 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
2168                 Args, OCS);
2169           else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
2170             if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
2171               AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
2172                                    Args, OCS);
2173         }
2174         switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
2175         case OR_Success:
2176           ND = Best->FoundDecl;
2177           Corrected.setCorrectionDecl(ND);
2178           break;
2179         default:
2180           // FIXME: Arbitrarily pick the first declaration for the note.
2181           Corrected.setCorrectionDecl(ND);
2182           break;
2183         }
2184       }
2185       R.addDecl(ND);
2186       if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2187         CXXRecordDecl *Record = nullptr;
2188         if (Corrected.getCorrectionSpecifier()) {
2189           const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
2190           Record = Ty->getAsCXXRecordDecl();
2191         }
2192         if (!Record)
2193           Record = cast<CXXRecordDecl>(
2194               ND->getDeclContext()->getRedeclContext());
2195         R.setNamingClass(Record);
2196       }
2197 
2198       auto *UnderlyingND = ND->getUnderlyingDecl();
2199       AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2200                                isa<FunctionTemplateDecl>(UnderlyingND);
2201       // FIXME: If we ended up with a typo for a type name or
2202       // Objective-C class name, we're in trouble because the parser
2203       // is in the wrong place to recover. Suggest the typo
2204       // correction, but don't make it a fix-it since we're not going
2205       // to recover well anyway.
2206       AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) ||
2207                                   getAsTypeTemplateDecl(UnderlyingND) ||
2208                                   isa<ObjCInterfaceDecl>(UnderlyingND);
2209     } else {
2210       // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2211       // because we aren't able to recover.
2212       AcceptableWithoutRecovery = true;
2213     }
2214 
2215     if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2216       unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2217                             ? diag::note_implicit_param_decl
2218                             : diag::note_previous_decl;
2219       if (SS.isEmpty())
2220         diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
2221                      PDiag(NoteID), AcceptableWithRecovery);
2222       else
2223         diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
2224                                   << Name << computeDeclContext(SS, false)
2225                                   << DroppedSpecifier << SS.getRange(),
2226                      PDiag(NoteID), AcceptableWithRecovery);
2227 
2228       // Tell the callee whether to try to recover.
2229       return !AcceptableWithRecovery;
2230     }
2231   }
2232   R.clear();
2233 
2234   // Emit a special diagnostic for failed member lookups.
2235   // FIXME: computing the declaration context might fail here (?)
2236   if (!SS.isEmpty()) {
2237     Diag(R.getNameLoc(), diag::err_no_member)
2238       << Name << computeDeclContext(SS, false)
2239       << SS.getRange();
2240     return true;
2241   }
2242 
2243   // Give up, we can't recover.
2244   Diag(R.getNameLoc(), diagnostic) << Name;
2245   return true;
2246 }
2247 
2248 /// In Microsoft mode, if we are inside a template class whose parent class has
2249 /// dependent base classes, and we can't resolve an unqualified identifier, then
2250 /// assume the identifier is a member of a dependent base class.  We can only
2251 /// recover successfully in static methods, instance methods, and other contexts
2252 /// where 'this' is available.  This doesn't precisely match MSVC's
2253 /// instantiation model, but it's close enough.
2254 static Expr *
2255 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
2256                                DeclarationNameInfo &NameInfo,
2257                                SourceLocation TemplateKWLoc,
2258                                const TemplateArgumentListInfo *TemplateArgs) {
2259   // Only try to recover from lookup into dependent bases in static methods or
2260   // contexts where 'this' is available.
2261   QualType ThisType = S.getCurrentThisType();
2262   const CXXRecordDecl *RD = nullptr;
2263   if (!ThisType.isNull())
2264     RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2265   else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2266     RD = MD->getParent();
2267   if (!RD || !RD->hasAnyDependentBases())
2268     return nullptr;
2269 
2270   // Diagnose this as unqualified lookup into a dependent base class.  If 'this'
2271   // is available, suggest inserting 'this->' as a fixit.
2272   SourceLocation Loc = NameInfo.getLoc();
2273   auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2274   DB << NameInfo.getName() << RD;
2275 
2276   if (!ThisType.isNull()) {
2277     DB << FixItHint::CreateInsertion(Loc, "this->");
2278     return CXXDependentScopeMemberExpr::Create(
2279         Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2280         /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2281         /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
2282   }
2283 
2284   // Synthesize a fake NNS that points to the derived class.  This will
2285   // perform name lookup during template instantiation.
2286   CXXScopeSpec SS;
2287   auto *NNS =
2288       NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2289   SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2290   return DependentScopeDeclRefExpr::Create(
2291       Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2292       TemplateArgs);
2293 }
2294 
2295 ExprResult
2296 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2297                         SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2298                         bool HasTrailingLParen, bool IsAddressOfOperand,
2299                         CorrectionCandidateCallback *CCC,
2300                         bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2301   assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2302          "cannot be direct & operand and have a trailing lparen");
2303   if (SS.isInvalid())
2304     return ExprError();
2305 
2306   TemplateArgumentListInfo TemplateArgsBuffer;
2307 
2308   // Decompose the UnqualifiedId into the following data.
2309   DeclarationNameInfo NameInfo;
2310   const TemplateArgumentListInfo *TemplateArgs;
2311   DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2312 
2313   DeclarationName Name = NameInfo.getName();
2314   IdentifierInfo *II = Name.getAsIdentifierInfo();
2315   SourceLocation NameLoc = NameInfo.getLoc();
2316 
2317   if (II && II->isEditorPlaceholder()) {
2318     // FIXME: When typed placeholders are supported we can create a typed
2319     // placeholder expression node.
2320     return ExprError();
2321   }
2322 
2323   // C++ [temp.dep.expr]p3:
2324   //   An id-expression is type-dependent if it contains:
2325   //     -- an identifier that was declared with a dependent type,
2326   //        (note: handled after lookup)
2327   //     -- a template-id that is dependent,
2328   //        (note: handled in BuildTemplateIdExpr)
2329   //     -- a conversion-function-id that specifies a dependent type,
2330   //     -- a nested-name-specifier that contains a class-name that
2331   //        names a dependent type.
2332   // Determine whether this is a member of an unknown specialization;
2333   // we need to handle these differently.
2334   bool DependentID = false;
2335   if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2336       Name.getCXXNameType()->isDependentType()) {
2337     DependentID = true;
2338   } else if (SS.isSet()) {
2339     if (DeclContext *DC = computeDeclContext(SS, false)) {
2340       if (RequireCompleteDeclContext(SS, DC))
2341         return ExprError();
2342     } else {
2343       DependentID = true;
2344     }
2345   }
2346 
2347   if (DependentID)
2348     return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2349                                       IsAddressOfOperand, TemplateArgs);
2350 
2351   // Perform the required lookup.
2352   LookupResult R(*this, NameInfo,
2353                  (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam)
2354                      ? LookupObjCImplicitSelfParam
2355                      : LookupOrdinaryName);
2356   if (TemplateKWLoc.isValid() || TemplateArgs) {
2357     // Lookup the template name again to correctly establish the context in
2358     // which it was found. This is really unfortunate as we already did the
2359     // lookup to determine that it was a template name in the first place. If
2360     // this becomes a performance hit, we can work harder to preserve those
2361     // results until we get here but it's likely not worth it.
2362     bool MemberOfUnknownSpecialization;
2363     AssumedTemplateKind AssumedTemplate;
2364     if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2365                            MemberOfUnknownSpecialization, TemplateKWLoc,
2366                            &AssumedTemplate))
2367       return ExprError();
2368 
2369     if (MemberOfUnknownSpecialization ||
2370         (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2371       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2372                                         IsAddressOfOperand, TemplateArgs);
2373   } else {
2374     bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2375     LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2376 
2377     // If the result might be in a dependent base class, this is a dependent
2378     // id-expression.
2379     if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2380       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2381                                         IsAddressOfOperand, TemplateArgs);
2382 
2383     // If this reference is in an Objective-C method, then we need to do
2384     // some special Objective-C lookup, too.
2385     if (IvarLookupFollowUp) {
2386       ExprResult E(LookupInObjCMethod(R, S, II, true));
2387       if (E.isInvalid())
2388         return ExprError();
2389 
2390       if (Expr *Ex = E.getAs<Expr>())
2391         return Ex;
2392     }
2393   }
2394 
2395   if (R.isAmbiguous())
2396     return ExprError();
2397 
2398   // This could be an implicitly declared function reference (legal in C90,
2399   // extension in C99, forbidden in C++).
2400   if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2401     NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2402     if (D) R.addDecl(D);
2403   }
2404 
2405   // Determine whether this name might be a candidate for
2406   // argument-dependent lookup.
2407   bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2408 
2409   if (R.empty() && !ADL) {
2410     if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2411       if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2412                                                    TemplateKWLoc, TemplateArgs))
2413         return E;
2414     }
2415 
2416     // Don't diagnose an empty lookup for inline assembly.
2417     if (IsInlineAsmIdentifier)
2418       return ExprError();
2419 
2420     // If this name wasn't predeclared and if this is not a function
2421     // call, diagnose the problem.
2422     TypoExpr *TE = nullptr;
2423     DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep()
2424                                                        : nullptr);
2425     DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;
2426     assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2427            "Typo correction callback misconfigured");
2428     if (CCC) {
2429       // Make sure the callback knows what the typo being diagnosed is.
2430       CCC->setTypoName(II);
2431       if (SS.isValid())
2432         CCC->setTypoNNS(SS.getScopeRep());
2433     }
2434     // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2435     // a template name, but we happen to have always already looked up the name
2436     // before we get here if it must be a template name.
2437     if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr,
2438                             None, &TE)) {
2439       if (TE && KeywordReplacement) {
2440         auto &State = getTypoExprState(TE);
2441         auto BestTC = State.Consumer->getNextCorrection();
2442         if (BestTC.isKeyword()) {
2443           auto *II = BestTC.getCorrectionAsIdentifierInfo();
2444           if (State.DiagHandler)
2445             State.DiagHandler(BestTC);
2446           KeywordReplacement->startToken();
2447           KeywordReplacement->setKind(II->getTokenID());
2448           KeywordReplacement->setIdentifierInfo(II);
2449           KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2450           // Clean up the state associated with the TypoExpr, since it has
2451           // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2452           clearDelayedTypo(TE);
2453           // Signal that a correction to a keyword was performed by returning a
2454           // valid-but-null ExprResult.
2455           return (Expr*)nullptr;
2456         }
2457         State.Consumer->resetCorrectionStream();
2458       }
2459       return TE ? TE : ExprError();
2460     }
2461 
2462     assert(!R.empty() &&
2463            "DiagnoseEmptyLookup returned false but added no results");
2464 
2465     // If we found an Objective-C instance variable, let
2466     // LookupInObjCMethod build the appropriate expression to
2467     // reference the ivar.
2468     if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2469       R.clear();
2470       ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2471       // In a hopelessly buggy code, Objective-C instance variable
2472       // lookup fails and no expression will be built to reference it.
2473       if (!E.isInvalid() && !E.get())
2474         return ExprError();
2475       return E;
2476     }
2477   }
2478 
2479   // This is guaranteed from this point on.
2480   assert(!R.empty() || ADL);
2481 
2482   // Check whether this might be a C++ implicit instance member access.
2483   // C++ [class.mfct.non-static]p3:
2484   //   When an id-expression that is not part of a class member access
2485   //   syntax and not used to form a pointer to member is used in the
2486   //   body of a non-static member function of class X, if name lookup
2487   //   resolves the name in the id-expression to a non-static non-type
2488   //   member of some class C, the id-expression is transformed into a
2489   //   class member access expression using (*this) as the
2490   //   postfix-expression to the left of the . operator.
2491   //
2492   // But we don't actually need to do this for '&' operands if R
2493   // resolved to a function or overloaded function set, because the
2494   // expression is ill-formed if it actually works out to be a
2495   // non-static member function:
2496   //
2497   // C++ [expr.ref]p4:
2498   //   Otherwise, if E1.E2 refers to a non-static member function. . .
2499   //   [t]he expression can be used only as the left-hand operand of a
2500   //   member function call.
2501   //
2502   // There are other safeguards against such uses, but it's important
2503   // to get this right here so that we don't end up making a
2504   // spuriously dependent expression if we're inside a dependent
2505   // instance method.
2506   if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2507     bool MightBeImplicitMember;
2508     if (!IsAddressOfOperand)
2509       MightBeImplicitMember = true;
2510     else if (!SS.isEmpty())
2511       MightBeImplicitMember = false;
2512     else if (R.isOverloadedResult())
2513       MightBeImplicitMember = false;
2514     else if (R.isUnresolvableResult())
2515       MightBeImplicitMember = true;
2516     else
2517       MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2518                               isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2519                               isa<MSPropertyDecl>(R.getFoundDecl());
2520 
2521     if (MightBeImplicitMember)
2522       return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2523                                              R, TemplateArgs, S);
2524   }
2525 
2526   if (TemplateArgs || TemplateKWLoc.isValid()) {
2527 
2528     // In C++1y, if this is a variable template id, then check it
2529     // in BuildTemplateIdExpr().
2530     // The single lookup result must be a variable template declaration.
2531     if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId &&
2532         Id.TemplateId->Kind == TNK_Var_template) {
2533       assert(R.getAsSingle<VarTemplateDecl>() &&
2534              "There should only be one declaration found.");
2535     }
2536 
2537     return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2538   }
2539 
2540   return BuildDeclarationNameExpr(SS, R, ADL);
2541 }
2542 
2543 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2544 /// declaration name, generally during template instantiation.
2545 /// There's a large number of things which don't need to be done along
2546 /// this path.
2547 ExprResult Sema::BuildQualifiedDeclarationNameExpr(
2548     CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2549     bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2550   DeclContext *DC = computeDeclContext(SS, false);
2551   if (!DC)
2552     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2553                                      NameInfo, /*TemplateArgs=*/nullptr);
2554 
2555   if (RequireCompleteDeclContext(SS, DC))
2556     return ExprError();
2557 
2558   LookupResult R(*this, NameInfo, LookupOrdinaryName);
2559   LookupQualifiedName(R, DC);
2560 
2561   if (R.isAmbiguous())
2562     return ExprError();
2563 
2564   if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2565     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2566                                      NameInfo, /*TemplateArgs=*/nullptr);
2567 
2568   if (R.empty()) {
2569     Diag(NameInfo.getLoc(), diag::err_no_member)
2570       << NameInfo.getName() << DC << SS.getRange();
2571     return ExprError();
2572   }
2573 
2574   if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2575     // Diagnose a missing typename if this resolved unambiguously to a type in
2576     // a dependent context.  If we can recover with a type, downgrade this to
2577     // a warning in Microsoft compatibility mode.
2578     unsigned DiagID = diag::err_typename_missing;
2579     if (RecoveryTSI && getLangOpts().MSVCCompat)
2580       DiagID = diag::ext_typename_missing;
2581     SourceLocation Loc = SS.getBeginLoc();
2582     auto D = Diag(Loc, DiagID);
2583     D << SS.getScopeRep() << NameInfo.getName().getAsString()
2584       << SourceRange(Loc, NameInfo.getEndLoc());
2585 
2586     // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2587     // context.
2588     if (!RecoveryTSI)
2589       return ExprError();
2590 
2591     // Only issue the fixit if we're prepared to recover.
2592     D << FixItHint::CreateInsertion(Loc, "typename ");
2593 
2594     // Recover by pretending this was an elaborated type.
2595     QualType Ty = Context.getTypeDeclType(TD);
2596     TypeLocBuilder TLB;
2597     TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2598 
2599     QualType ET = getElaboratedType(ETK_None, SS, Ty);
2600     ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2601     QTL.setElaboratedKeywordLoc(SourceLocation());
2602     QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2603 
2604     *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2605 
2606     return ExprEmpty();
2607   }
2608 
2609   // Defend against this resolving to an implicit member access. We usually
2610   // won't get here if this might be a legitimate a class member (we end up in
2611   // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2612   // a pointer-to-member or in an unevaluated context in C++11.
2613   if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2614     return BuildPossibleImplicitMemberExpr(SS,
2615                                            /*TemplateKWLoc=*/SourceLocation(),
2616                                            R, /*TemplateArgs=*/nullptr, S);
2617 
2618   return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2619 }
2620 
2621 /// The parser has read a name in, and Sema has detected that we're currently
2622 /// inside an ObjC method. Perform some additional checks and determine if we
2623 /// should form a reference to an ivar.
2624 ///
2625 /// Ideally, most of this would be done by lookup, but there's
2626 /// actually quite a lot of extra work involved.
2627 DeclResult Sema::LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S,
2628                                         IdentifierInfo *II) {
2629   SourceLocation Loc = Lookup.getNameLoc();
2630   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2631 
2632   // Check for error condition which is already reported.
2633   if (!CurMethod)
2634     return DeclResult(true);
2635 
2636   // There are two cases to handle here.  1) scoped lookup could have failed,
2637   // in which case we should look for an ivar.  2) scoped lookup could have
2638   // found a decl, but that decl is outside the current instance method (i.e.
2639   // a global variable).  In these two cases, we do a lookup for an ivar with
2640   // this name, if the lookup sucedes, we replace it our current decl.
2641 
2642   // If we're in a class method, we don't normally want to look for
2643   // ivars.  But if we don't find anything else, and there's an
2644   // ivar, that's an error.
2645   bool IsClassMethod = CurMethod->isClassMethod();
2646 
2647   bool LookForIvars;
2648   if (Lookup.empty())
2649     LookForIvars = true;
2650   else if (IsClassMethod)
2651     LookForIvars = false;
2652   else
2653     LookForIvars = (Lookup.isSingleResult() &&
2654                     Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2655   ObjCInterfaceDecl *IFace = nullptr;
2656   if (LookForIvars) {
2657     IFace = CurMethod->getClassInterface();
2658     ObjCInterfaceDecl *ClassDeclared;
2659     ObjCIvarDecl *IV = nullptr;
2660     if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2661       // Diagnose using an ivar in a class method.
2662       if (IsClassMethod) {
2663         Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
2664         return DeclResult(true);
2665       }
2666 
2667       // Diagnose the use of an ivar outside of the declaring class.
2668       if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2669           !declaresSameEntity(ClassDeclared, IFace) &&
2670           !getLangOpts().DebuggerSupport)
2671         Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
2672 
2673       // Success.
2674       return IV;
2675     }
2676   } else if (CurMethod->isInstanceMethod()) {
2677     // We should warn if a local variable hides an ivar.
2678     if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2679       ObjCInterfaceDecl *ClassDeclared;
2680       if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2681         if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2682             declaresSameEntity(IFace, ClassDeclared))
2683           Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2684       }
2685     }
2686   } else if (Lookup.isSingleResult() &&
2687              Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2688     // If accessing a stand-alone ivar in a class method, this is an error.
2689     if (const ObjCIvarDecl *IV =
2690             dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) {
2691       Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
2692       return DeclResult(true);
2693     }
2694   }
2695 
2696   // Didn't encounter an error, didn't find an ivar.
2697   return DeclResult(false);
2698 }
2699 
2700 ExprResult Sema::BuildIvarRefExpr(Scope *S, SourceLocation Loc,
2701                                   ObjCIvarDecl *IV) {
2702   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2703   assert(CurMethod && CurMethod->isInstanceMethod() &&
2704          "should not reference ivar from this context");
2705 
2706   ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
2707   assert(IFace && "should not reference ivar from this context");
2708 
2709   // If we're referencing an invalid decl, just return this as a silent
2710   // error node.  The error diagnostic was already emitted on the decl.
2711   if (IV->isInvalidDecl())
2712     return ExprError();
2713 
2714   // Check if referencing a field with __attribute__((deprecated)).
2715   if (DiagnoseUseOfDecl(IV, Loc))
2716     return ExprError();
2717 
2718   // FIXME: This should use a new expr for a direct reference, don't
2719   // turn this into Self->ivar, just return a BareIVarExpr or something.
2720   IdentifierInfo &II = Context.Idents.get("self");
2721   UnqualifiedId SelfName;
2722   SelfName.setIdentifier(&II, SourceLocation());
2723   SelfName.setKind(UnqualifiedIdKind::IK_ImplicitSelfParam);
2724   CXXScopeSpec SelfScopeSpec;
2725   SourceLocation TemplateKWLoc;
2726   ExprResult SelfExpr =
2727       ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName,
2728                         /*HasTrailingLParen=*/false,
2729                         /*IsAddressOfOperand=*/false);
2730   if (SelfExpr.isInvalid())
2731     return ExprError();
2732 
2733   SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2734   if (SelfExpr.isInvalid())
2735     return ExprError();
2736 
2737   MarkAnyDeclReferenced(Loc, IV, true);
2738 
2739   ObjCMethodFamily MF = CurMethod->getMethodFamily();
2740   if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2741       !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2742     Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2743 
2744   ObjCIvarRefExpr *Result = new (Context)
2745       ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2746                       IV->getLocation(), SelfExpr.get(), true, true);
2747 
2748   if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2749     if (!isUnevaluatedContext() &&
2750         !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2751       getCurFunction()->recordUseOfWeak(Result);
2752   }
2753   if (getLangOpts().ObjCAutoRefCount)
2754     if (const BlockDecl *BD = CurContext->getInnermostBlockDecl())
2755       ImplicitlyRetainedSelfLocs.push_back({Loc, BD});
2756 
2757   return Result;
2758 }
2759 
2760 /// The parser has read a name in, and Sema has detected that we're currently
2761 /// inside an ObjC method. Perform some additional checks and determine if we
2762 /// should form a reference to an ivar. If so, build an expression referencing
2763 /// that ivar.
2764 ExprResult
2765 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2766                          IdentifierInfo *II, bool AllowBuiltinCreation) {
2767   // FIXME: Integrate this lookup step into LookupParsedName.
2768   DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II);
2769   if (Ivar.isInvalid())
2770     return ExprError();
2771   if (Ivar.isUsable())
2772     return BuildIvarRefExpr(S, Lookup.getNameLoc(),
2773                             cast<ObjCIvarDecl>(Ivar.get()));
2774 
2775   if (Lookup.empty() && II && AllowBuiltinCreation)
2776     LookupBuiltin(Lookup);
2777 
2778   // Sentinel value saying that we didn't do anything special.
2779   return ExprResult(false);
2780 }
2781 
2782 /// Cast a base object to a member's actual type.
2783 ///
2784 /// Logically this happens in three phases:
2785 ///
2786 /// * First we cast from the base type to the naming class.
2787 ///   The naming class is the class into which we were looking
2788 ///   when we found the member;  it's the qualifier type if a
2789 ///   qualifier was provided, and otherwise it's the base type.
2790 ///
2791 /// * Next we cast from the naming class to the declaring class.
2792 ///   If the member we found was brought into a class's scope by
2793 ///   a using declaration, this is that class;  otherwise it's
2794 ///   the class declaring the member.
2795 ///
2796 /// * Finally we cast from the declaring class to the "true"
2797 ///   declaring class of the member.  This conversion does not
2798 ///   obey access control.
2799 ExprResult
2800 Sema::PerformObjectMemberConversion(Expr *From,
2801                                     NestedNameSpecifier *Qualifier,
2802                                     NamedDecl *FoundDecl,
2803                                     NamedDecl *Member) {
2804   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2805   if (!RD)
2806     return From;
2807 
2808   QualType DestRecordType;
2809   QualType DestType;
2810   QualType FromRecordType;
2811   QualType FromType = From->getType();
2812   bool PointerConversions = false;
2813   if (isa<FieldDecl>(Member)) {
2814     DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2815     auto FromPtrType = FromType->getAs<PointerType>();
2816     DestRecordType = Context.getAddrSpaceQualType(
2817         DestRecordType, FromPtrType
2818                             ? FromType->getPointeeType().getAddressSpace()
2819                             : FromType.getAddressSpace());
2820 
2821     if (FromPtrType) {
2822       DestType = Context.getPointerType(DestRecordType);
2823       FromRecordType = FromPtrType->getPointeeType();
2824       PointerConversions = true;
2825     } else {
2826       DestType = DestRecordType;
2827       FromRecordType = FromType;
2828     }
2829   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2830     if (Method->isStatic())
2831       return From;
2832 
2833     DestType = Method->getThisType();
2834     DestRecordType = DestType->getPointeeType();
2835 
2836     if (FromType->getAs<PointerType>()) {
2837       FromRecordType = FromType->getPointeeType();
2838       PointerConversions = true;
2839     } else {
2840       FromRecordType = FromType;
2841       DestType = DestRecordType;
2842     }
2843 
2844     LangAS FromAS = FromRecordType.getAddressSpace();
2845     LangAS DestAS = DestRecordType.getAddressSpace();
2846     if (FromAS != DestAS) {
2847       QualType FromRecordTypeWithoutAS =
2848           Context.removeAddrSpaceQualType(FromRecordType);
2849       QualType FromTypeWithDestAS =
2850           Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS);
2851       if (PointerConversions)
2852         FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS);
2853       From = ImpCastExprToType(From, FromTypeWithDestAS,
2854                                CK_AddressSpaceConversion, From->getValueKind())
2855                  .get();
2856     }
2857   } else {
2858     // No conversion necessary.
2859     return From;
2860   }
2861 
2862   if (DestType->isDependentType() || FromType->isDependentType())
2863     return From;
2864 
2865   // If the unqualified types are the same, no conversion is necessary.
2866   if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2867     return From;
2868 
2869   SourceRange FromRange = From->getSourceRange();
2870   SourceLocation FromLoc = FromRange.getBegin();
2871 
2872   ExprValueKind VK = From->getValueKind();
2873 
2874   // C++ [class.member.lookup]p8:
2875   //   [...] Ambiguities can often be resolved by qualifying a name with its
2876   //   class name.
2877   //
2878   // If the member was a qualified name and the qualified referred to a
2879   // specific base subobject type, we'll cast to that intermediate type
2880   // first and then to the object in which the member is declared. That allows
2881   // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2882   //
2883   //   class Base { public: int x; };
2884   //   class Derived1 : public Base { };
2885   //   class Derived2 : public Base { };
2886   //   class VeryDerived : public Derived1, public Derived2 { void f(); };
2887   //
2888   //   void VeryDerived::f() {
2889   //     x = 17; // error: ambiguous base subobjects
2890   //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
2891   //   }
2892   if (Qualifier && Qualifier->getAsType()) {
2893     QualType QType = QualType(Qualifier->getAsType(), 0);
2894     assert(QType->isRecordType() && "lookup done with non-record type");
2895 
2896     QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2897 
2898     // In C++98, the qualifier type doesn't actually have to be a base
2899     // type of the object type, in which case we just ignore it.
2900     // Otherwise build the appropriate casts.
2901     if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
2902       CXXCastPath BasePath;
2903       if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2904                                        FromLoc, FromRange, &BasePath))
2905         return ExprError();
2906 
2907       if (PointerConversions)
2908         QType = Context.getPointerType(QType);
2909       From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2910                                VK, &BasePath).get();
2911 
2912       FromType = QType;
2913       FromRecordType = QRecordType;
2914 
2915       // If the qualifier type was the same as the destination type,
2916       // we're done.
2917       if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2918         return From;
2919     }
2920   }
2921 
2922   bool IgnoreAccess = false;
2923 
2924   // If we actually found the member through a using declaration, cast
2925   // down to the using declaration's type.
2926   //
2927   // Pointer equality is fine here because only one declaration of a
2928   // class ever has member declarations.
2929   if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2930     assert(isa<UsingShadowDecl>(FoundDecl));
2931     QualType URecordType = Context.getTypeDeclType(
2932                            cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2933 
2934     // We only need to do this if the naming-class to declaring-class
2935     // conversion is non-trivial.
2936     if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2937       assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType));
2938       CXXCastPath BasePath;
2939       if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2940                                        FromLoc, FromRange, &BasePath))
2941         return ExprError();
2942 
2943       QualType UType = URecordType;
2944       if (PointerConversions)
2945         UType = Context.getPointerType(UType);
2946       From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2947                                VK, &BasePath).get();
2948       FromType = UType;
2949       FromRecordType = URecordType;
2950     }
2951 
2952     // We don't do access control for the conversion from the
2953     // declaring class to the true declaring class.
2954     IgnoreAccess = true;
2955   }
2956 
2957   CXXCastPath BasePath;
2958   if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2959                                    FromLoc, FromRange, &BasePath,
2960                                    IgnoreAccess))
2961     return ExprError();
2962 
2963   return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2964                            VK, &BasePath);
2965 }
2966 
2967 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2968                                       const LookupResult &R,
2969                                       bool HasTrailingLParen) {
2970   // Only when used directly as the postfix-expression of a call.
2971   if (!HasTrailingLParen)
2972     return false;
2973 
2974   // Never if a scope specifier was provided.
2975   if (SS.isSet())
2976     return false;
2977 
2978   // Only in C++ or ObjC++.
2979   if (!getLangOpts().CPlusPlus)
2980     return false;
2981 
2982   // Turn off ADL when we find certain kinds of declarations during
2983   // normal lookup:
2984   for (NamedDecl *D : R) {
2985     // C++0x [basic.lookup.argdep]p3:
2986     //     -- a declaration of a class member
2987     // Since using decls preserve this property, we check this on the
2988     // original decl.
2989     if (D->isCXXClassMember())
2990       return false;
2991 
2992     // C++0x [basic.lookup.argdep]p3:
2993     //     -- a block-scope function declaration that is not a
2994     //        using-declaration
2995     // NOTE: we also trigger this for function templates (in fact, we
2996     // don't check the decl type at all, since all other decl types
2997     // turn off ADL anyway).
2998     if (isa<UsingShadowDecl>(D))
2999       D = cast<UsingShadowDecl>(D)->getTargetDecl();
3000     else if (D->getLexicalDeclContext()->isFunctionOrMethod())
3001       return false;
3002 
3003     // C++0x [basic.lookup.argdep]p3:
3004     //     -- a declaration that is neither a function or a function
3005     //        template
3006     // And also for builtin functions.
3007     if (isa<FunctionDecl>(D)) {
3008       FunctionDecl *FDecl = cast<FunctionDecl>(D);
3009 
3010       // But also builtin functions.
3011       if (FDecl->getBuiltinID() && FDecl->isImplicit())
3012         return false;
3013     } else if (!isa<FunctionTemplateDecl>(D))
3014       return false;
3015   }
3016 
3017   return true;
3018 }
3019 
3020 
3021 /// Diagnoses obvious problems with the use of the given declaration
3022 /// as an expression.  This is only actually called for lookups that
3023 /// were not overloaded, and it doesn't promise that the declaration
3024 /// will in fact be used.
3025 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
3026   if (D->isInvalidDecl())
3027     return true;
3028 
3029   if (isa<TypedefNameDecl>(D)) {
3030     S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
3031     return true;
3032   }
3033 
3034   if (isa<ObjCInterfaceDecl>(D)) {
3035     S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
3036     return true;
3037   }
3038 
3039   if (isa<NamespaceDecl>(D)) {
3040     S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
3041     return true;
3042   }
3043 
3044   return false;
3045 }
3046 
3047 // Certain multiversion types should be treated as overloaded even when there is
3048 // only one result.
3049 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) {
3050   assert(R.isSingleResult() && "Expected only a single result");
3051   const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
3052   return FD &&
3053          (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
3054 }
3055 
3056 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
3057                                           LookupResult &R, bool NeedsADL,
3058                                           bool AcceptInvalidDecl) {
3059   // If this is a single, fully-resolved result and we don't need ADL,
3060   // just build an ordinary singleton decl ref.
3061   if (!NeedsADL && R.isSingleResult() &&
3062       !R.getAsSingle<FunctionTemplateDecl>() &&
3063       !ShouldLookupResultBeMultiVersionOverload(R))
3064     return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
3065                                     R.getRepresentativeDecl(), nullptr,
3066                                     AcceptInvalidDecl);
3067 
3068   // We only need to check the declaration if there's exactly one
3069   // result, because in the overloaded case the results can only be
3070   // functions and function templates.
3071   if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) &&
3072       CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
3073     return ExprError();
3074 
3075   // Otherwise, just build an unresolved lookup expression.  Suppress
3076   // any lookup-related diagnostics; we'll hash these out later, when
3077   // we've picked a target.
3078   R.suppressDiagnostics();
3079 
3080   UnresolvedLookupExpr *ULE
3081     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
3082                                    SS.getWithLocInContext(Context),
3083                                    R.getLookupNameInfo(),
3084                                    NeedsADL, R.isOverloadedResult(),
3085                                    R.begin(), R.end());
3086 
3087   return ULE;
3088 }
3089 
3090 static void
3091 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
3092                                    ValueDecl *var, DeclContext *DC);
3093 
3094 /// Complete semantic analysis for a reference to the given declaration.
3095 ExprResult Sema::BuildDeclarationNameExpr(
3096     const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
3097     NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
3098     bool AcceptInvalidDecl) {
3099   assert(D && "Cannot refer to a NULL declaration");
3100   assert(!isa<FunctionTemplateDecl>(D) &&
3101          "Cannot refer unambiguously to a function template");
3102 
3103   SourceLocation Loc = NameInfo.getLoc();
3104   if (CheckDeclInExpr(*this, Loc, D))
3105     return ExprError();
3106 
3107   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
3108     // Specifically diagnose references to class templates that are missing
3109     // a template argument list.
3110     diagnoseMissingTemplateArguments(TemplateName(Template), Loc);
3111     return ExprError();
3112   }
3113 
3114   // Make sure that we're referring to a value.
3115   ValueDecl *VD = dyn_cast<ValueDecl>(D);
3116   if (!VD) {
3117     Diag(Loc, diag::err_ref_non_value)
3118       << D << SS.getRange();
3119     Diag(D->getLocation(), diag::note_declared_at);
3120     return ExprError();
3121   }
3122 
3123   // Check whether this declaration can be used. Note that we suppress
3124   // this check when we're going to perform argument-dependent lookup
3125   // on this function name, because this might not be the function
3126   // that overload resolution actually selects.
3127   if (DiagnoseUseOfDecl(VD, Loc))
3128     return ExprError();
3129 
3130   // Only create DeclRefExpr's for valid Decl's.
3131   if (VD->isInvalidDecl() && !AcceptInvalidDecl)
3132     return ExprError();
3133 
3134   // Handle members of anonymous structs and unions.  If we got here,
3135   // and the reference is to a class member indirect field, then this
3136   // must be the subject of a pointer-to-member expression.
3137   if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
3138     if (!indirectField->isCXXClassMember())
3139       return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
3140                                                       indirectField);
3141 
3142   {
3143     QualType type = VD->getType();
3144     if (type.isNull())
3145       return ExprError();
3146     ExprValueKind valueKind = VK_RValue;
3147 
3148     switch (D->getKind()) {
3149     // Ignore all the non-ValueDecl kinds.
3150 #define ABSTRACT_DECL(kind)
3151 #define VALUE(type, base)
3152 #define DECL(type, base) \
3153     case Decl::type:
3154 #include "clang/AST/DeclNodes.inc"
3155       llvm_unreachable("invalid value decl kind");
3156 
3157     // These shouldn't make it here.
3158     case Decl::ObjCAtDefsField:
3159       llvm_unreachable("forming non-member reference to ivar?");
3160 
3161     // Enum constants are always r-values and never references.
3162     // Unresolved using declarations are dependent.
3163     case Decl::EnumConstant:
3164     case Decl::UnresolvedUsingValue:
3165     case Decl::OMPDeclareReduction:
3166     case Decl::OMPDeclareMapper:
3167       valueKind = VK_RValue;
3168       break;
3169 
3170     // Fields and indirect fields that got here must be for
3171     // pointer-to-member expressions; we just call them l-values for
3172     // internal consistency, because this subexpression doesn't really
3173     // exist in the high-level semantics.
3174     case Decl::Field:
3175     case Decl::IndirectField:
3176     case Decl::ObjCIvar:
3177       assert(getLangOpts().CPlusPlus &&
3178              "building reference to field in C?");
3179 
3180       // These can't have reference type in well-formed programs, but
3181       // for internal consistency we do this anyway.
3182       type = type.getNonReferenceType();
3183       valueKind = VK_LValue;
3184       break;
3185 
3186     // Non-type template parameters are either l-values or r-values
3187     // depending on the type.
3188     case Decl::NonTypeTemplateParm: {
3189       if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
3190         type = reftype->getPointeeType();
3191         valueKind = VK_LValue; // even if the parameter is an r-value reference
3192         break;
3193       }
3194 
3195       // For non-references, we need to strip qualifiers just in case
3196       // the template parameter was declared as 'const int' or whatever.
3197       valueKind = VK_RValue;
3198       type = type.getUnqualifiedType();
3199       break;
3200     }
3201 
3202     case Decl::Var:
3203     case Decl::VarTemplateSpecialization:
3204     case Decl::VarTemplatePartialSpecialization:
3205     case Decl::Decomposition:
3206     case Decl::OMPCapturedExpr:
3207       // In C, "extern void blah;" is valid and is an r-value.
3208       if (!getLangOpts().CPlusPlus &&
3209           !type.hasQualifiers() &&
3210           type->isVoidType()) {
3211         valueKind = VK_RValue;
3212         break;
3213       }
3214       LLVM_FALLTHROUGH;
3215 
3216     case Decl::ImplicitParam:
3217     case Decl::ParmVar: {
3218       // These are always l-values.
3219       valueKind = VK_LValue;
3220       type = type.getNonReferenceType();
3221 
3222       // FIXME: Does the addition of const really only apply in
3223       // potentially-evaluated contexts? Since the variable isn't actually
3224       // captured in an unevaluated context, it seems that the answer is no.
3225       if (!isUnevaluatedContext()) {
3226         QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
3227         if (!CapturedType.isNull())
3228           type = CapturedType;
3229       }
3230 
3231       break;
3232     }
3233 
3234     case Decl::Binding: {
3235       // These are always lvalues.
3236       valueKind = VK_LValue;
3237       type = type.getNonReferenceType();
3238       // FIXME: Support lambda-capture of BindingDecls, once CWG actually
3239       // decides how that's supposed to work.
3240       auto *BD = cast<BindingDecl>(VD);
3241       if (BD->getDeclContext() != CurContext) {
3242         auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl());
3243         if (DD && DD->hasLocalStorage())
3244           diagnoseUncapturableValueReference(*this, Loc, BD, CurContext);
3245       }
3246       break;
3247     }
3248 
3249     case Decl::Function: {
3250       if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
3251         if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
3252           type = Context.BuiltinFnTy;
3253           valueKind = VK_RValue;
3254           break;
3255         }
3256       }
3257 
3258       const FunctionType *fty = type->castAs<FunctionType>();
3259 
3260       // If we're referring to a function with an __unknown_anytype
3261       // result type, make the entire expression __unknown_anytype.
3262       if (fty->getReturnType() == Context.UnknownAnyTy) {
3263         type = Context.UnknownAnyTy;
3264         valueKind = VK_RValue;
3265         break;
3266       }
3267 
3268       // Functions are l-values in C++.
3269       if (getLangOpts().CPlusPlus) {
3270         valueKind = VK_LValue;
3271         break;
3272       }
3273 
3274       // C99 DR 316 says that, if a function type comes from a
3275       // function definition (without a prototype), that type is only
3276       // used for checking compatibility. Therefore, when referencing
3277       // the function, we pretend that we don't have the full function
3278       // type.
3279       if (!cast<FunctionDecl>(VD)->hasPrototype() &&
3280           isa<FunctionProtoType>(fty))
3281         type = Context.getFunctionNoProtoType(fty->getReturnType(),
3282                                               fty->getExtInfo());
3283 
3284       // Functions are r-values in C.
3285       valueKind = VK_RValue;
3286       break;
3287     }
3288 
3289     case Decl::CXXDeductionGuide:
3290       llvm_unreachable("building reference to deduction guide");
3291 
3292     case Decl::MSProperty:
3293     case Decl::MSGuid:
3294       // FIXME: Should MSGuidDecl be subject to capture in OpenMP,
3295       // or duplicated between host and device?
3296       valueKind = VK_LValue;
3297       break;
3298 
3299     case Decl::CXXMethod:
3300       // If we're referring to a method with an __unknown_anytype
3301       // result type, make the entire expression __unknown_anytype.
3302       // This should only be possible with a type written directly.
3303       if (const FunctionProtoType *proto
3304             = dyn_cast<FunctionProtoType>(VD->getType()))
3305         if (proto->getReturnType() == Context.UnknownAnyTy) {
3306           type = Context.UnknownAnyTy;
3307           valueKind = VK_RValue;
3308           break;
3309         }
3310 
3311       // C++ methods are l-values if static, r-values if non-static.
3312       if (cast<CXXMethodDecl>(VD)->isStatic()) {
3313         valueKind = VK_LValue;
3314         break;
3315       }
3316       LLVM_FALLTHROUGH;
3317 
3318     case Decl::CXXConversion:
3319     case Decl::CXXDestructor:
3320     case Decl::CXXConstructor:
3321       valueKind = VK_RValue;
3322       break;
3323     }
3324 
3325     return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3326                             /*FIXME: TemplateKWLoc*/ SourceLocation(),
3327                             TemplateArgs);
3328   }
3329 }
3330 
3331 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3332                                     SmallString<32> &Target) {
3333   Target.resize(CharByteWidth * (Source.size() + 1));
3334   char *ResultPtr = &Target[0];
3335   const llvm::UTF8 *ErrorPtr;
3336   bool success =
3337       llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3338   (void)success;
3339   assert(success);
3340   Target.resize(ResultPtr - &Target[0]);
3341 }
3342 
3343 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3344                                      PredefinedExpr::IdentKind IK) {
3345   // Pick the current block, lambda, captured statement or function.
3346   Decl *currentDecl = nullptr;
3347   if (const BlockScopeInfo *BSI = getCurBlock())
3348     currentDecl = BSI->TheDecl;
3349   else if (const LambdaScopeInfo *LSI = getCurLambda())
3350     currentDecl = LSI->CallOperator;
3351   else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3352     currentDecl = CSI->TheCapturedDecl;
3353   else
3354     currentDecl = getCurFunctionOrMethodDecl();
3355 
3356   if (!currentDecl) {
3357     Diag(Loc, diag::ext_predef_outside_function);
3358     currentDecl = Context.getTranslationUnitDecl();
3359   }
3360 
3361   QualType ResTy;
3362   StringLiteral *SL = nullptr;
3363   if (cast<DeclContext>(currentDecl)->isDependentContext())
3364     ResTy = Context.DependentTy;
3365   else {
3366     // Pre-defined identifiers are of type char[x], where x is the length of
3367     // the string.
3368     auto Str = PredefinedExpr::ComputeName(IK, currentDecl);
3369     unsigned Length = Str.length();
3370 
3371     llvm::APInt LengthI(32, Length + 1);
3372     if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) {
3373       ResTy =
3374           Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst());
3375       SmallString<32> RawChars;
3376       ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3377                               Str, RawChars);
3378       ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3379                                            ArrayType::Normal,
3380                                            /*IndexTypeQuals*/ 0);
3381       SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3382                                  /*Pascal*/ false, ResTy, Loc);
3383     } else {
3384       ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
3385       ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3386                                            ArrayType::Normal,
3387                                            /*IndexTypeQuals*/ 0);
3388       SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3389                                  /*Pascal*/ false, ResTy, Loc);
3390     }
3391   }
3392 
3393   return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL);
3394 }
3395 
3396 static std::pair<QualType, StringLiteral *>
3397 GetUniqueStableNameInfo(ASTContext &Context, QualType OpType,
3398                         SourceLocation OpLoc, PredefinedExpr::IdentKind K) {
3399   std::pair<QualType, StringLiteral*> Result{{}, nullptr};
3400 
3401   if (OpType->isDependentType()) {
3402       Result.first = Context.DependentTy;
3403       return Result;
3404   }
3405 
3406   std::string Str = PredefinedExpr::ComputeName(Context, K, OpType);
3407   llvm::APInt Length(32, Str.length() + 1);
3408   Result.first =
3409       Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
3410   Result.first = Context.getConstantArrayType(
3411       Result.first, Length, nullptr, ArrayType::Normal, /*IndexTypeQuals*/ 0);
3412   Result.second = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3413                                         /*Pascal*/ false, Result.first, OpLoc);
3414   return Result;
3415 }
3416 
3417 ExprResult Sema::BuildUniqueStableName(SourceLocation OpLoc,
3418                                        TypeSourceInfo *Operand) {
3419   QualType ResultTy;
3420   StringLiteral *SL;
3421   std::tie(ResultTy, SL) = GetUniqueStableNameInfo(
3422       Context, Operand->getType(), OpLoc, PredefinedExpr::UniqueStableNameType);
3423 
3424   return PredefinedExpr::Create(Context, OpLoc, ResultTy,
3425                                 PredefinedExpr::UniqueStableNameType, SL,
3426                                 Operand);
3427 }
3428 
3429 ExprResult Sema::BuildUniqueStableName(SourceLocation OpLoc,
3430                                        Expr *E) {
3431   QualType ResultTy;
3432   StringLiteral *SL;
3433   std::tie(ResultTy, SL) = GetUniqueStableNameInfo(
3434       Context, E->getType(), OpLoc, PredefinedExpr::UniqueStableNameExpr);
3435 
3436   return PredefinedExpr::Create(Context, OpLoc, ResultTy,
3437                                 PredefinedExpr::UniqueStableNameExpr, SL, E);
3438 }
3439 
3440 ExprResult Sema::ActOnUniqueStableNameExpr(SourceLocation OpLoc,
3441                                            SourceLocation L, SourceLocation R,
3442                                            ParsedType Ty) {
3443   TypeSourceInfo *TInfo = nullptr;
3444   QualType T = GetTypeFromParser(Ty, &TInfo);
3445 
3446   if (T.isNull())
3447     return ExprError();
3448   if (!TInfo)
3449     TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
3450 
3451   return BuildUniqueStableName(OpLoc, TInfo);
3452 }
3453 
3454 ExprResult Sema::ActOnUniqueStableNameExpr(SourceLocation OpLoc,
3455                                            SourceLocation L, SourceLocation R,
3456                                            Expr *E) {
3457   return BuildUniqueStableName(OpLoc, E);
3458 }
3459 
3460 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3461   PredefinedExpr::IdentKind IK;
3462 
3463   switch (Kind) {
3464   default: llvm_unreachable("Unknown simple primary expr!");
3465   case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3466   case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break;
3467   case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS]
3468   case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS]
3469   case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS]
3470   case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS]
3471   case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break;
3472   }
3473 
3474   return BuildPredefinedExpr(Loc, IK);
3475 }
3476 
3477 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3478   SmallString<16> CharBuffer;
3479   bool Invalid = false;
3480   StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3481   if (Invalid)
3482     return ExprError();
3483 
3484   CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3485                             PP, Tok.getKind());
3486   if (Literal.hadError())
3487     return ExprError();
3488 
3489   QualType Ty;
3490   if (Literal.isWide())
3491     Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3492   else if (Literal.isUTF8() && getLangOpts().Char8)
3493     Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3494   else if (Literal.isUTF16())
3495     Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3496   else if (Literal.isUTF32())
3497     Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3498   else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3499     Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
3500   else
3501     Ty = Context.CharTy;  // 'x' -> char in C++
3502 
3503   CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3504   if (Literal.isWide())
3505     Kind = CharacterLiteral::Wide;
3506   else if (Literal.isUTF16())
3507     Kind = CharacterLiteral::UTF16;
3508   else if (Literal.isUTF32())
3509     Kind = CharacterLiteral::UTF32;
3510   else if (Literal.isUTF8())
3511     Kind = CharacterLiteral::UTF8;
3512 
3513   Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3514                                              Tok.getLocation());
3515 
3516   if (Literal.getUDSuffix().empty())
3517     return Lit;
3518 
3519   // We're building a user-defined literal.
3520   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3521   SourceLocation UDSuffixLoc =
3522     getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3523 
3524   // Make sure we're allowed user-defined literals here.
3525   if (!UDLScope)
3526     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3527 
3528   // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3529   //   operator "" X (ch)
3530   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3531                                         Lit, Tok.getLocation());
3532 }
3533 
3534 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3535   unsigned IntSize = Context.getTargetInfo().getIntWidth();
3536   return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3537                                 Context.IntTy, Loc);
3538 }
3539 
3540 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3541                                   QualType Ty, SourceLocation Loc) {
3542   const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3543 
3544   using llvm::APFloat;
3545   APFloat Val(Format);
3546 
3547   APFloat::opStatus result = Literal.GetFloatValue(Val);
3548 
3549   // Overflow is always an error, but underflow is only an error if
3550   // we underflowed to zero (APFloat reports denormals as underflow).
3551   if ((result & APFloat::opOverflow) ||
3552       ((result & APFloat::opUnderflow) && Val.isZero())) {
3553     unsigned diagnostic;
3554     SmallString<20> buffer;
3555     if (result & APFloat::opOverflow) {
3556       diagnostic = diag::warn_float_overflow;
3557       APFloat::getLargest(Format).toString(buffer);
3558     } else {
3559       diagnostic = diag::warn_float_underflow;
3560       APFloat::getSmallest(Format).toString(buffer);
3561     }
3562 
3563     S.Diag(Loc, diagnostic)
3564       << Ty
3565       << StringRef(buffer.data(), buffer.size());
3566   }
3567 
3568   bool isExact = (result == APFloat::opOK);
3569   return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3570 }
3571 
3572 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3573   assert(E && "Invalid expression");
3574 
3575   if (E->isValueDependent())
3576     return false;
3577 
3578   QualType QT = E->getType();
3579   if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3580     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3581     return true;
3582   }
3583 
3584   llvm::APSInt ValueAPS;
3585   ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3586 
3587   if (R.isInvalid())
3588     return true;
3589 
3590   bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3591   if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3592     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3593         << ValueAPS.toString(10) << ValueIsPositive;
3594     return true;
3595   }
3596 
3597   return false;
3598 }
3599 
3600 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3601   // Fast path for a single digit (which is quite common).  A single digit
3602   // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3603   if (Tok.getLength() == 1) {
3604     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3605     return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3606   }
3607 
3608   SmallString<128> SpellingBuffer;
3609   // NumericLiteralParser wants to overread by one character.  Add padding to
3610   // the buffer in case the token is copied to the buffer.  If getSpelling()
3611   // returns a StringRef to the memory buffer, it should have a null char at
3612   // the EOF, so it is also safe.
3613   SpellingBuffer.resize(Tok.getLength() + 1);
3614 
3615   // Get the spelling of the token, which eliminates trigraphs, etc.
3616   bool Invalid = false;
3617   StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3618   if (Invalid)
3619     return ExprError();
3620 
3621   NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
3622   if (Literal.hadError)
3623     return ExprError();
3624 
3625   if (Literal.hasUDSuffix()) {
3626     // We're building a user-defined literal.
3627     IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3628     SourceLocation UDSuffixLoc =
3629       getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3630 
3631     // Make sure we're allowed user-defined literals here.
3632     if (!UDLScope)
3633       return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3634 
3635     QualType CookedTy;
3636     if (Literal.isFloatingLiteral()) {
3637       // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3638       // long double, the literal is treated as a call of the form
3639       //   operator "" X (f L)
3640       CookedTy = Context.LongDoubleTy;
3641     } else {
3642       // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3643       // unsigned long long, the literal is treated as a call of the form
3644       //   operator "" X (n ULL)
3645       CookedTy = Context.UnsignedLongLongTy;
3646     }
3647 
3648     DeclarationName OpName =
3649       Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3650     DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3651     OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3652 
3653     SourceLocation TokLoc = Tok.getLocation();
3654 
3655     // Perform literal operator lookup to determine if we're building a raw
3656     // literal or a cooked one.
3657     LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3658     switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3659                                   /*AllowRaw*/ true, /*AllowTemplate*/ true,
3660                                   /*AllowStringTemplate*/ false,
3661                                   /*DiagnoseMissing*/ !Literal.isImaginary)) {
3662     case LOLR_ErrorNoDiagnostic:
3663       // Lookup failure for imaginary constants isn't fatal, there's still the
3664       // GNU extension producing _Complex types.
3665       break;
3666     case LOLR_Error:
3667       return ExprError();
3668     case LOLR_Cooked: {
3669       Expr *Lit;
3670       if (Literal.isFloatingLiteral()) {
3671         Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3672       } else {
3673         llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3674         if (Literal.GetIntegerValue(ResultVal))
3675           Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3676               << /* Unsigned */ 1;
3677         Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3678                                      Tok.getLocation());
3679       }
3680       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3681     }
3682 
3683     case LOLR_Raw: {
3684       // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3685       // literal is treated as a call of the form
3686       //   operator "" X ("n")
3687       unsigned Length = Literal.getUDSuffixOffset();
3688       QualType StrTy = Context.getConstantArrayType(
3689           Context.adjustStringLiteralBaseType(Context.CharTy.withConst()),
3690           llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0);
3691       Expr *Lit = StringLiteral::Create(
3692           Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3693           /*Pascal*/false, StrTy, &TokLoc, 1);
3694       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3695     }
3696 
3697     case LOLR_Template: {
3698       // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3699       // template), L is treated as a call fo the form
3700       //   operator "" X <'c1', 'c2', ... 'ck'>()
3701       // where n is the source character sequence c1 c2 ... ck.
3702       TemplateArgumentListInfo ExplicitArgs;
3703       unsigned CharBits = Context.getIntWidth(Context.CharTy);
3704       bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3705       llvm::APSInt Value(CharBits, CharIsUnsigned);
3706       for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3707         Value = TokSpelling[I];
3708         TemplateArgument Arg(Context, Value, Context.CharTy);
3709         TemplateArgumentLocInfo ArgInfo;
3710         ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3711       }
3712       return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3713                                       &ExplicitArgs);
3714     }
3715     case LOLR_StringTemplate:
3716       llvm_unreachable("unexpected literal operator lookup result");
3717     }
3718   }
3719 
3720   Expr *Res;
3721 
3722   if (Literal.isFixedPointLiteral()) {
3723     QualType Ty;
3724 
3725     if (Literal.isAccum) {
3726       if (Literal.isHalf) {
3727         Ty = Context.ShortAccumTy;
3728       } else if (Literal.isLong) {
3729         Ty = Context.LongAccumTy;
3730       } else {
3731         Ty = Context.AccumTy;
3732       }
3733     } else if (Literal.isFract) {
3734       if (Literal.isHalf) {
3735         Ty = Context.ShortFractTy;
3736       } else if (Literal.isLong) {
3737         Ty = Context.LongFractTy;
3738       } else {
3739         Ty = Context.FractTy;
3740       }
3741     }
3742 
3743     if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
3744 
3745     bool isSigned = !Literal.isUnsigned;
3746     unsigned scale = Context.getFixedPointScale(Ty);
3747     unsigned bit_width = Context.getTypeInfo(Ty).Width;
3748 
3749     llvm::APInt Val(bit_width, 0, isSigned);
3750     bool Overflowed = Literal.GetFixedPointValue(Val, scale);
3751     bool ValIsZero = Val.isNullValue() && !Overflowed;
3752 
3753     auto MaxVal = Context.getFixedPointMax(Ty).getValue();
3754     if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
3755       // Clause 6.4.4 - The value of a constant shall be in the range of
3756       // representable values for its type, with exception for constants of a
3757       // fract type with a value of exactly 1; such a constant shall denote
3758       // the maximal value for the type.
3759       --Val;
3760     else if (Val.ugt(MaxVal) || Overflowed)
3761       Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
3762 
3763     Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty,
3764                                               Tok.getLocation(), scale);
3765   } else if (Literal.isFloatingLiteral()) {
3766     QualType Ty;
3767     if (Literal.isHalf){
3768       if (getOpenCLOptions().isEnabled("cl_khr_fp16"))
3769         Ty = Context.HalfTy;
3770       else {
3771         Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3772         return ExprError();
3773       }
3774     } else if (Literal.isFloat)
3775       Ty = Context.FloatTy;
3776     else if (Literal.isLong)
3777       Ty = Context.LongDoubleTy;
3778     else if (Literal.isFloat16)
3779       Ty = Context.Float16Ty;
3780     else if (Literal.isFloat128)
3781       Ty = Context.Float128Ty;
3782     else
3783       Ty = Context.DoubleTy;
3784 
3785     Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3786 
3787     if (Ty == Context.DoubleTy) {
3788       if (getLangOpts().SinglePrecisionConstants) {
3789         const BuiltinType *BTy = Ty->getAs<BuiltinType>();
3790         if (BTy->getKind() != BuiltinType::Float) {
3791           Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3792         }
3793       } else if (getLangOpts().OpenCL &&
3794                  !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
3795         // Impose single-precision float type when cl_khr_fp64 is not enabled.
3796         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
3797         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3798       }
3799     }
3800   } else if (!Literal.isIntegerLiteral()) {
3801     return ExprError();
3802   } else {
3803     QualType Ty;
3804 
3805     // 'long long' is a C99 or C++11 feature.
3806     if (!getLangOpts().C99 && Literal.isLongLong) {
3807       if (getLangOpts().CPlusPlus)
3808         Diag(Tok.getLocation(),
3809              getLangOpts().CPlusPlus11 ?
3810              diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3811       else
3812         Diag(Tok.getLocation(), diag::ext_c99_longlong);
3813     }
3814 
3815     // Get the value in the widest-possible width.
3816     unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3817     llvm::APInt ResultVal(MaxWidth, 0);
3818 
3819     if (Literal.GetIntegerValue(ResultVal)) {
3820       // If this value didn't fit into uintmax_t, error and force to ull.
3821       Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3822           << /* Unsigned */ 1;
3823       Ty = Context.UnsignedLongLongTy;
3824       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3825              "long long is not intmax_t?");
3826     } else {
3827       // If this value fits into a ULL, try to figure out what else it fits into
3828       // according to the rules of C99 6.4.4.1p5.
3829 
3830       // Octal, Hexadecimal, and integers with a U suffix are allowed to
3831       // be an unsigned int.
3832       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3833 
3834       // Check from smallest to largest, picking the smallest type we can.
3835       unsigned Width = 0;
3836 
3837       // Microsoft specific integer suffixes are explicitly sized.
3838       if (Literal.MicrosoftInteger) {
3839         if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3840           Width = 8;
3841           Ty = Context.CharTy;
3842         } else {
3843           Width = Literal.MicrosoftInteger;
3844           Ty = Context.getIntTypeForBitwidth(Width,
3845                                              /*Signed=*/!Literal.isUnsigned);
3846         }
3847       }
3848 
3849       if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
3850         // Are int/unsigned possibilities?
3851         unsigned IntSize = Context.getTargetInfo().getIntWidth();
3852 
3853         // Does it fit in a unsigned int?
3854         if (ResultVal.isIntN(IntSize)) {
3855           // Does it fit in a signed int?
3856           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3857             Ty = Context.IntTy;
3858           else if (AllowUnsigned)
3859             Ty = Context.UnsignedIntTy;
3860           Width = IntSize;
3861         }
3862       }
3863 
3864       // Are long/unsigned long possibilities?
3865       if (Ty.isNull() && !Literal.isLongLong) {
3866         unsigned LongSize = Context.getTargetInfo().getLongWidth();
3867 
3868         // Does it fit in a unsigned long?
3869         if (ResultVal.isIntN(LongSize)) {
3870           // Does it fit in a signed long?
3871           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3872             Ty = Context.LongTy;
3873           else if (AllowUnsigned)
3874             Ty = Context.UnsignedLongTy;
3875           // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
3876           // is compatible.
3877           else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
3878             const unsigned LongLongSize =
3879                 Context.getTargetInfo().getLongLongWidth();
3880             Diag(Tok.getLocation(),
3881                  getLangOpts().CPlusPlus
3882                      ? Literal.isLong
3883                            ? diag::warn_old_implicitly_unsigned_long_cxx
3884                            : /*C++98 UB*/ diag::
3885                                  ext_old_implicitly_unsigned_long_cxx
3886                      : diag::warn_old_implicitly_unsigned_long)
3887                 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
3888                                             : /*will be ill-formed*/ 1);
3889             Ty = Context.UnsignedLongTy;
3890           }
3891           Width = LongSize;
3892         }
3893       }
3894 
3895       // Check long long if needed.
3896       if (Ty.isNull()) {
3897         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3898 
3899         // Does it fit in a unsigned long long?
3900         if (ResultVal.isIntN(LongLongSize)) {
3901           // Does it fit in a signed long long?
3902           // To be compatible with MSVC, hex integer literals ending with the
3903           // LL or i64 suffix are always signed in Microsoft mode.
3904           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3905               (getLangOpts().MSVCCompat && Literal.isLongLong)))
3906             Ty = Context.LongLongTy;
3907           else if (AllowUnsigned)
3908             Ty = Context.UnsignedLongLongTy;
3909           Width = LongLongSize;
3910         }
3911       }
3912 
3913       // If we still couldn't decide a type, we probably have something that
3914       // does not fit in a signed long long, but has no U suffix.
3915       if (Ty.isNull()) {
3916         Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
3917         Ty = Context.UnsignedLongLongTy;
3918         Width = Context.getTargetInfo().getLongLongWidth();
3919       }
3920 
3921       if (ResultVal.getBitWidth() != Width)
3922         ResultVal = ResultVal.trunc(Width);
3923     }
3924     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3925   }
3926 
3927   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3928   if (Literal.isImaginary) {
3929     Res = new (Context) ImaginaryLiteral(Res,
3930                                         Context.getComplexType(Res->getType()));
3931 
3932     Diag(Tok.getLocation(), diag::ext_imaginary_constant);
3933   }
3934   return Res;
3935 }
3936 
3937 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
3938   assert(E && "ActOnParenExpr() missing expr");
3939   return new (Context) ParenExpr(L, R, E);
3940 }
3941 
3942 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3943                                          SourceLocation Loc,
3944                                          SourceRange ArgRange) {
3945   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3946   // scalar or vector data type argument..."
3947   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3948   // type (C99 6.2.5p18) or void.
3949   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3950     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3951       << T << ArgRange;
3952     return true;
3953   }
3954 
3955   assert((T->isVoidType() || !T->isIncompleteType()) &&
3956          "Scalar types should always be complete");
3957   return false;
3958 }
3959 
3960 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3961                                            SourceLocation Loc,
3962                                            SourceRange ArgRange,
3963                                            UnaryExprOrTypeTrait TraitKind) {
3964   // Invalid types must be hard errors for SFINAE in C++.
3965   if (S.LangOpts.CPlusPlus)
3966     return true;
3967 
3968   // C99 6.5.3.4p1:
3969   if (T->isFunctionType() &&
3970       (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
3971        TraitKind == UETT_PreferredAlignOf)) {
3972     // sizeof(function)/alignof(function) is allowed as an extension.
3973     S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3974       << TraitKind << ArgRange;
3975     return false;
3976   }
3977 
3978   // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
3979   // this is an error (OpenCL v1.1 s6.3.k)
3980   if (T->isVoidType()) {
3981     unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
3982                                         : diag::ext_sizeof_alignof_void_type;
3983     S.Diag(Loc, DiagID) << TraitKind << ArgRange;
3984     return false;
3985   }
3986 
3987   return true;
3988 }
3989 
3990 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
3991                                              SourceLocation Loc,
3992                                              SourceRange ArgRange,
3993                                              UnaryExprOrTypeTrait TraitKind) {
3994   // Reject sizeof(interface) and sizeof(interface<proto>) if the
3995   // runtime doesn't allow it.
3996   if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
3997     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3998       << T << (TraitKind == UETT_SizeOf)
3999       << ArgRange;
4000     return true;
4001   }
4002 
4003   return false;
4004 }
4005 
4006 /// Check whether E is a pointer from a decayed array type (the decayed
4007 /// pointer type is equal to T) and emit a warning if it is.
4008 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
4009                                      Expr *E) {
4010   // Don't warn if the operation changed the type.
4011   if (T != E->getType())
4012     return;
4013 
4014   // Now look for array decays.
4015   ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
4016   if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
4017     return;
4018 
4019   S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
4020                                              << ICE->getType()
4021                                              << ICE->getSubExpr()->getType();
4022 }
4023 
4024 /// Check the constraints on expression operands to unary type expression
4025 /// and type traits.
4026 ///
4027 /// Completes any types necessary and validates the constraints on the operand
4028 /// expression. The logic mostly mirrors the type-based overload, but may modify
4029 /// the expression as it completes the type for that expression through template
4030 /// instantiation, etc.
4031 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
4032                                             UnaryExprOrTypeTrait ExprKind) {
4033   QualType ExprTy = E->getType();
4034   assert(!ExprTy->isReferenceType());
4035 
4036   bool IsUnevaluatedOperand =
4037       (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf ||
4038        ExprKind == UETT_PreferredAlignOf);
4039   if (IsUnevaluatedOperand) {
4040     ExprResult Result = CheckUnevaluatedOperand(E);
4041     if (Result.isInvalid())
4042       return true;
4043     E = Result.get();
4044   }
4045 
4046   if (ExprKind == UETT_VecStep)
4047     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
4048                                         E->getSourceRange());
4049 
4050   // Whitelist some types as extensions
4051   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
4052                                       E->getSourceRange(), ExprKind))
4053     return false;
4054 
4055   // 'alignof' applied to an expression only requires the base element type of
4056   // the expression to be complete. 'sizeof' requires the expression's type to
4057   // be complete (and will attempt to complete it if it's an array of unknown
4058   // bound).
4059   if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4060     if (RequireCompleteSizedType(
4061             E->getExprLoc(), Context.getBaseElementType(E->getType()),
4062             diag::err_sizeof_alignof_incomplete_or_sizeless_type, ExprKind,
4063             E->getSourceRange()))
4064       return true;
4065   } else {
4066     if (RequireCompleteSizedExprType(
4067             E, diag::err_sizeof_alignof_incomplete_or_sizeless_type, ExprKind,
4068             E->getSourceRange()))
4069       return true;
4070   }
4071 
4072   // Completing the expression's type may have changed it.
4073   ExprTy = E->getType();
4074   assert(!ExprTy->isReferenceType());
4075 
4076   if (ExprTy->isFunctionType()) {
4077     Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
4078       << ExprKind << E->getSourceRange();
4079     return true;
4080   }
4081 
4082   // The operand for sizeof and alignof is in an unevaluated expression context,
4083   // so side effects could result in unintended consequences.
4084   if (IsUnevaluatedOperand && !inTemplateInstantiation() &&
4085       E->HasSideEffects(Context, false))
4086     Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
4087 
4088   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
4089                                        E->getSourceRange(), ExprKind))
4090     return true;
4091 
4092   if (ExprKind == UETT_SizeOf) {
4093     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
4094       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
4095         QualType OType = PVD->getOriginalType();
4096         QualType Type = PVD->getType();
4097         if (Type->isPointerType() && OType->isArrayType()) {
4098           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
4099             << Type << OType;
4100           Diag(PVD->getLocation(), diag::note_declared_at);
4101         }
4102       }
4103     }
4104 
4105     // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
4106     // decays into a pointer and returns an unintended result. This is most
4107     // likely a typo for "sizeof(array) op x".
4108     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
4109       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4110                                BO->getLHS());
4111       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4112                                BO->getRHS());
4113     }
4114   }
4115 
4116   return false;
4117 }
4118 
4119 /// Check the constraints on operands to unary expression and type
4120 /// traits.
4121 ///
4122 /// This will complete any types necessary, and validate the various constraints
4123 /// on those operands.
4124 ///
4125 /// The UsualUnaryConversions() function is *not* called by this routine.
4126 /// C99 6.3.2.1p[2-4] all state:
4127 ///   Except when it is the operand of the sizeof operator ...
4128 ///
4129 /// C++ [expr.sizeof]p4
4130 ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
4131 ///   standard conversions are not applied to the operand of sizeof.
4132 ///
4133 /// This policy is followed for all of the unary trait expressions.
4134 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
4135                                             SourceLocation OpLoc,
4136                                             SourceRange ExprRange,
4137                                             UnaryExprOrTypeTrait ExprKind) {
4138   if (ExprType->isDependentType())
4139     return false;
4140 
4141   // C++ [expr.sizeof]p2:
4142   //     When applied to a reference or a reference type, the result
4143   //     is the size of the referenced type.
4144   // C++11 [expr.alignof]p3:
4145   //     When alignof is applied to a reference type, the result
4146   //     shall be the alignment of the referenced type.
4147   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
4148     ExprType = Ref->getPointeeType();
4149 
4150   // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
4151   //   When alignof or _Alignof is applied to an array type, the result
4152   //   is the alignment of the element type.
4153   if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4154       ExprKind == UETT_OpenMPRequiredSimdAlign)
4155     ExprType = Context.getBaseElementType(ExprType);
4156 
4157   if (ExprKind == UETT_VecStep)
4158     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
4159 
4160   // Whitelist some types as extensions
4161   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
4162                                       ExprKind))
4163     return false;
4164 
4165   if (RequireCompleteSizedType(
4166           OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4167           ExprKind, ExprRange))
4168     return true;
4169 
4170   if (ExprType->isFunctionType()) {
4171     Diag(OpLoc, diag::err_sizeof_alignof_function_type)
4172       << ExprKind << ExprRange;
4173     return true;
4174   }
4175 
4176   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
4177                                        ExprKind))
4178     return true;
4179 
4180   return false;
4181 }
4182 
4183 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
4184   // Cannot know anything else if the expression is dependent.
4185   if (E->isTypeDependent())
4186     return false;
4187 
4188   if (E->getObjectKind() == OK_BitField) {
4189     S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
4190        << 1 << E->getSourceRange();
4191     return true;
4192   }
4193 
4194   ValueDecl *D = nullptr;
4195   Expr *Inner = E->IgnoreParens();
4196   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) {
4197     D = DRE->getDecl();
4198   } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) {
4199     D = ME->getMemberDecl();
4200   }
4201 
4202   // If it's a field, require the containing struct to have a
4203   // complete definition so that we can compute the layout.
4204   //
4205   // This can happen in C++11 onwards, either by naming the member
4206   // in a way that is not transformed into a member access expression
4207   // (in an unevaluated operand, for instance), or by naming the member
4208   // in a trailing-return-type.
4209   //
4210   // For the record, since __alignof__ on expressions is a GCC
4211   // extension, GCC seems to permit this but always gives the
4212   // nonsensical answer 0.
4213   //
4214   // We don't really need the layout here --- we could instead just
4215   // directly check for all the appropriate alignment-lowing
4216   // attributes --- but that would require duplicating a lot of
4217   // logic that just isn't worth duplicating for such a marginal
4218   // use-case.
4219   if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
4220     // Fast path this check, since we at least know the record has a
4221     // definition if we can find a member of it.
4222     if (!FD->getParent()->isCompleteDefinition()) {
4223       S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
4224         << E->getSourceRange();
4225       return true;
4226     }
4227 
4228     // Otherwise, if it's a field, and the field doesn't have
4229     // reference type, then it must have a complete type (or be a
4230     // flexible array member, which we explicitly want to
4231     // white-list anyway), which makes the following checks trivial.
4232     if (!FD->getType()->isReferenceType())
4233       return false;
4234   }
4235 
4236   return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4237 }
4238 
4239 bool Sema::CheckVecStepExpr(Expr *E) {
4240   E = E->IgnoreParens();
4241 
4242   // Cannot know anything else if the expression is dependent.
4243   if (E->isTypeDependent())
4244     return false;
4245 
4246   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
4247 }
4248 
4249 static void captureVariablyModifiedType(ASTContext &Context, QualType T,
4250                                         CapturingScopeInfo *CSI) {
4251   assert(T->isVariablyModifiedType());
4252   assert(CSI != nullptr);
4253 
4254   // We're going to walk down into the type and look for VLA expressions.
4255   do {
4256     const Type *Ty = T.getTypePtr();
4257     switch (Ty->getTypeClass()) {
4258 #define TYPE(Class, Base)
4259 #define ABSTRACT_TYPE(Class, Base)
4260 #define NON_CANONICAL_TYPE(Class, Base)
4261 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
4262 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4263 #include "clang/AST/TypeNodes.inc"
4264       T = QualType();
4265       break;
4266     // These types are never variably-modified.
4267     case Type::Builtin:
4268     case Type::Complex:
4269     case Type::Vector:
4270     case Type::ExtVector:
4271     case Type::ConstantMatrix:
4272     case Type::Record:
4273     case Type::Enum:
4274     case Type::Elaborated:
4275     case Type::TemplateSpecialization:
4276     case Type::ObjCObject:
4277     case Type::ObjCInterface:
4278     case Type::ObjCObjectPointer:
4279     case Type::ObjCTypeParam:
4280     case Type::Pipe:
4281     case Type::ExtInt:
4282       llvm_unreachable("type class is never variably-modified!");
4283     case Type::Adjusted:
4284       T = cast<AdjustedType>(Ty)->getOriginalType();
4285       break;
4286     case Type::Decayed:
4287       T = cast<DecayedType>(Ty)->getPointeeType();
4288       break;
4289     case Type::Pointer:
4290       T = cast<PointerType>(Ty)->getPointeeType();
4291       break;
4292     case Type::BlockPointer:
4293       T = cast<BlockPointerType>(Ty)->getPointeeType();
4294       break;
4295     case Type::LValueReference:
4296     case Type::RValueReference:
4297       T = cast<ReferenceType>(Ty)->getPointeeType();
4298       break;
4299     case Type::MemberPointer:
4300       T = cast<MemberPointerType>(Ty)->getPointeeType();
4301       break;
4302     case Type::ConstantArray:
4303     case Type::IncompleteArray:
4304       // Losing element qualification here is fine.
4305       T = cast<ArrayType>(Ty)->getElementType();
4306       break;
4307     case Type::VariableArray: {
4308       // Losing element qualification here is fine.
4309       const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
4310 
4311       // Unknown size indication requires no size computation.
4312       // Otherwise, evaluate and record it.
4313       auto Size = VAT->getSizeExpr();
4314       if (Size && !CSI->isVLATypeCaptured(VAT) &&
4315           (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI)))
4316         CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType());
4317 
4318       T = VAT->getElementType();
4319       break;
4320     }
4321     case Type::FunctionProto:
4322     case Type::FunctionNoProto:
4323       T = cast<FunctionType>(Ty)->getReturnType();
4324       break;
4325     case Type::Paren:
4326     case Type::TypeOf:
4327     case Type::UnaryTransform:
4328     case Type::Attributed:
4329     case Type::SubstTemplateTypeParm:
4330     case Type::PackExpansion:
4331     case Type::MacroQualified:
4332       // Keep walking after single level desugaring.
4333       T = T.getSingleStepDesugaredType(Context);
4334       break;
4335     case Type::Typedef:
4336       T = cast<TypedefType>(Ty)->desugar();
4337       break;
4338     case Type::Decltype:
4339       T = cast<DecltypeType>(Ty)->desugar();
4340       break;
4341     case Type::Auto:
4342     case Type::DeducedTemplateSpecialization:
4343       T = cast<DeducedType>(Ty)->getDeducedType();
4344       break;
4345     case Type::TypeOfExpr:
4346       T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
4347       break;
4348     case Type::Atomic:
4349       T = cast<AtomicType>(Ty)->getValueType();
4350       break;
4351     }
4352   } while (!T.isNull() && T->isVariablyModifiedType());
4353 }
4354 
4355 /// Build a sizeof or alignof expression given a type operand.
4356 ExprResult
4357 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4358                                      SourceLocation OpLoc,
4359                                      UnaryExprOrTypeTrait ExprKind,
4360                                      SourceRange R) {
4361   if (!TInfo)
4362     return ExprError();
4363 
4364   QualType T = TInfo->getType();
4365 
4366   if (!T->isDependentType() &&
4367       CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
4368     return ExprError();
4369 
4370   if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4371     if (auto *TT = T->getAs<TypedefType>()) {
4372       for (auto I = FunctionScopes.rbegin(),
4373                 E = std::prev(FunctionScopes.rend());
4374            I != E; ++I) {
4375         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4376         if (CSI == nullptr)
4377           break;
4378         DeclContext *DC = nullptr;
4379         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4380           DC = LSI->CallOperator;
4381         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4382           DC = CRSI->TheCapturedDecl;
4383         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4384           DC = BSI->TheDecl;
4385         if (DC) {
4386           if (DC->containsDecl(TT->getDecl()))
4387             break;
4388           captureVariablyModifiedType(Context, T, CSI);
4389         }
4390       }
4391     }
4392   }
4393 
4394   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4395   return new (Context) UnaryExprOrTypeTraitExpr(
4396       ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4397 }
4398 
4399 /// Build a sizeof or alignof expression given an expression
4400 /// operand.
4401 ExprResult
4402 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4403                                      UnaryExprOrTypeTrait ExprKind) {
4404   ExprResult PE = CheckPlaceholderExpr(E);
4405   if (PE.isInvalid())
4406     return ExprError();
4407 
4408   E = PE.get();
4409 
4410   // Verify that the operand is valid.
4411   bool isInvalid = false;
4412   if (E->isTypeDependent()) {
4413     // Delay type-checking for type-dependent expressions.
4414   } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4415     isInvalid = CheckAlignOfExpr(*this, E, ExprKind);
4416   } else if (ExprKind == UETT_VecStep) {
4417     isInvalid = CheckVecStepExpr(E);
4418   } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4419       Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4420       isInvalid = true;
4421   } else if (E->refersToBitField()) {  // C99 6.5.3.4p1.
4422     Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4423     isInvalid = true;
4424   } else {
4425     isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
4426   }
4427 
4428   if (isInvalid)
4429     return ExprError();
4430 
4431   if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4432     PE = TransformToPotentiallyEvaluated(E);
4433     if (PE.isInvalid()) return ExprError();
4434     E = PE.get();
4435   }
4436 
4437   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4438   return new (Context) UnaryExprOrTypeTraitExpr(
4439       ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4440 }
4441 
4442 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4443 /// expr and the same for @c alignof and @c __alignof
4444 /// Note that the ArgRange is invalid if isType is false.
4445 ExprResult
4446 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4447                                     UnaryExprOrTypeTrait ExprKind, bool IsType,
4448                                     void *TyOrEx, SourceRange ArgRange) {
4449   // If error parsing type, ignore.
4450   if (!TyOrEx) return ExprError();
4451 
4452   if (IsType) {
4453     TypeSourceInfo *TInfo;
4454     (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4455     return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4456   }
4457 
4458   Expr *ArgEx = (Expr *)TyOrEx;
4459   ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4460   return Result;
4461 }
4462 
4463 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4464                                      bool IsReal) {
4465   if (V.get()->isTypeDependent())
4466     return S.Context.DependentTy;
4467 
4468   // _Real and _Imag are only l-values for normal l-values.
4469   if (V.get()->getObjectKind() != OK_Ordinary) {
4470     V = S.DefaultLvalueConversion(V.get());
4471     if (V.isInvalid())
4472       return QualType();
4473   }
4474 
4475   // These operators return the element type of a complex type.
4476   if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4477     return CT->getElementType();
4478 
4479   // Otherwise they pass through real integer and floating point types here.
4480   if (V.get()->getType()->isArithmeticType())
4481     return V.get()->getType();
4482 
4483   // Test for placeholders.
4484   ExprResult PR = S.CheckPlaceholderExpr(V.get());
4485   if (PR.isInvalid()) return QualType();
4486   if (PR.get() != V.get()) {
4487     V = PR;
4488     return CheckRealImagOperand(S, V, Loc, IsReal);
4489   }
4490 
4491   // Reject anything else.
4492   S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4493     << (IsReal ? "__real" : "__imag");
4494   return QualType();
4495 }
4496 
4497 
4498 
4499 ExprResult
4500 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4501                           tok::TokenKind Kind, Expr *Input) {
4502   UnaryOperatorKind Opc;
4503   switch (Kind) {
4504   default: llvm_unreachable("Unknown unary op!");
4505   case tok::plusplus:   Opc = UO_PostInc; break;
4506   case tok::minusminus: Opc = UO_PostDec; break;
4507   }
4508 
4509   // Since this might is a postfix expression, get rid of ParenListExprs.
4510   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4511   if (Result.isInvalid()) return ExprError();
4512   Input = Result.get();
4513 
4514   return BuildUnaryOp(S, OpLoc, Opc, Input);
4515 }
4516 
4517 /// Diagnose if arithmetic on the given ObjC pointer is illegal.
4518 ///
4519 /// \return true on error
4520 static bool checkArithmeticOnObjCPointer(Sema &S,
4521                                          SourceLocation opLoc,
4522                                          Expr *op) {
4523   assert(op->getType()->isObjCObjectPointerType());
4524   if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4525       !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4526     return false;
4527 
4528   S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4529     << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4530     << op->getSourceRange();
4531   return true;
4532 }
4533 
4534 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4535   auto *BaseNoParens = Base->IgnoreParens();
4536   if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4537     return MSProp->getPropertyDecl()->getType()->isArrayType();
4538   return isa<MSPropertySubscriptExpr>(BaseNoParens);
4539 }
4540 
4541 ExprResult
4542 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
4543                               Expr *idx, SourceLocation rbLoc) {
4544   if (base && !base->getType().isNull() &&
4545       base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection))
4546     return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
4547                                     /*Length=*/nullptr, rbLoc);
4548 
4549   // Since this might be a postfix expression, get rid of ParenListExprs.
4550   if (isa<ParenListExpr>(base)) {
4551     ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4552     if (result.isInvalid()) return ExprError();
4553     base = result.get();
4554   }
4555 
4556   // Check if base and idx form a MatrixSubscriptExpr.
4557   //
4558   // Helper to check for comma expressions, which are not allowed as indices for
4559   // matrix subscript expressions.
4560   auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) {
4561     if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) {
4562       Diag(E->getExprLoc(), diag::err_matrix_subscript_comma)
4563           << SourceRange(base->getBeginLoc(), rbLoc);
4564       return true;
4565     }
4566     return false;
4567   };
4568   // The matrix subscript operator ([][])is considered a single operator.
4569   // Separating the index expressions by parenthesis is not allowed.
4570   if (base->getType()->isSpecificPlaceholderType(
4571           BuiltinType::IncompleteMatrixIdx) &&
4572       !isa<MatrixSubscriptExpr>(base)) {
4573     Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index)
4574         << SourceRange(base->getBeginLoc(), rbLoc);
4575     return ExprError();
4576   }
4577   // If the base is either a MatrixSubscriptExpr or a matrix type, try to create
4578   // a new MatrixSubscriptExpr.
4579   auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base);
4580   if (matSubscriptE) {
4581     if (CheckAndReportCommaError(idx))
4582       return ExprError();
4583 
4584     assert(matSubscriptE->isIncomplete() &&
4585            "base has to be an incomplete matrix subscript");
4586     return CreateBuiltinMatrixSubscriptExpr(
4587         matSubscriptE->getBase(), matSubscriptE->getRowIdx(), idx, rbLoc);
4588   }
4589   Expr *matrixBase = base;
4590   bool IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4591   if (!IsMSPropertySubscript) {
4592     ExprResult result = CheckPlaceholderExpr(base);
4593     if (!result.isInvalid())
4594       matrixBase = result.get();
4595   }
4596   if (matrixBase->getType()->isMatrixType()) {
4597     if (CheckAndReportCommaError(idx))
4598       return ExprError();
4599 
4600     return CreateBuiltinMatrixSubscriptExpr(matrixBase, idx, nullptr, rbLoc);
4601   }
4602 
4603   // A comma-expression as the index is deprecated in C++2a onwards.
4604   if (getLangOpts().CPlusPlus20 &&
4605       ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) ||
4606        (isa<CXXOperatorCallExpr>(idx) &&
4607         cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma))) {
4608     Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript)
4609       << SourceRange(base->getBeginLoc(), rbLoc);
4610   }
4611 
4612   // Handle any non-overload placeholder types in the base and index
4613   // expressions.  We can't handle overloads here because the other
4614   // operand might be an overloadable type, in which case the overload
4615   // resolution for the operator overload should get the first crack
4616   // at the overload.
4617   if (base->getType()->isNonOverloadPlaceholderType()) {
4618     IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4619     if (!IsMSPropertySubscript) {
4620       ExprResult result = CheckPlaceholderExpr(base);
4621       if (result.isInvalid())
4622         return ExprError();
4623       base = result.get();
4624     }
4625   }
4626   if (idx->getType()->isNonOverloadPlaceholderType()) {
4627     ExprResult result = CheckPlaceholderExpr(idx);
4628     if (result.isInvalid()) return ExprError();
4629     idx = result.get();
4630   }
4631 
4632   // Build an unanalyzed expression if either operand is type-dependent.
4633   if (getLangOpts().CPlusPlus &&
4634       (base->isTypeDependent() || idx->isTypeDependent())) {
4635     return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
4636                                             VK_LValue, OK_Ordinary, rbLoc);
4637   }
4638 
4639   // MSDN, property (C++)
4640   // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4641   // This attribute can also be used in the declaration of an empty array in a
4642   // class or structure definition. For example:
4643   // __declspec(property(get=GetX, put=PutX)) int x[];
4644   // The above statement indicates that x[] can be used with one or more array
4645   // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4646   // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4647   if (IsMSPropertySubscript) {
4648     // Build MS property subscript expression if base is MS property reference
4649     // or MS property subscript.
4650     return new (Context) MSPropertySubscriptExpr(
4651         base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
4652   }
4653 
4654   // Use C++ overloaded-operator rules if either operand has record
4655   // type.  The spec says to do this if either type is *overloadable*,
4656   // but enum types can't declare subscript operators or conversion
4657   // operators, so there's nothing interesting for overload resolution
4658   // to do if there aren't any record types involved.
4659   //
4660   // ObjC pointers have their own subscripting logic that is not tied
4661   // to overload resolution and so should not take this path.
4662   if (getLangOpts().CPlusPlus &&
4663       (base->getType()->isRecordType() ||
4664        (!base->getType()->isObjCObjectPointerType() &&
4665         idx->getType()->isRecordType()))) {
4666     return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
4667   }
4668 
4669   ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
4670 
4671   if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get()))
4672     CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get()));
4673 
4674   return Res;
4675 }
4676 
4677 static bool tryConvertToTy(Sema &S, QualType ElementType, ExprResult *Scalar) {
4678   InitializedEntity Entity =
4679       InitializedEntity::InitializeTemporary(ElementType);
4680   InitializationKind Kind = InitializationKind::CreateCopy(
4681       Scalar->get()->getBeginLoc(), SourceLocation());
4682   Expr *Arg = Scalar->get();
4683   InitializationSequence InitSeq(S, Entity, Kind, Arg);
4684   *Scalar = InitSeq.Perform(S, Entity, Kind, Arg);
4685   return !Scalar->isInvalid();
4686 }
4687 
4688 ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx,
4689                                                   Expr *ColumnIdx,
4690                                                   SourceLocation RBLoc) {
4691   ExprResult BaseR = CheckPlaceholderExpr(Base);
4692   if (BaseR.isInvalid())
4693     return BaseR;
4694   Base = BaseR.get();
4695 
4696   ExprResult RowR = CheckPlaceholderExpr(RowIdx);
4697   if (RowR.isInvalid())
4698     return RowR;
4699   RowIdx = RowR.get();
4700 
4701   if (!ColumnIdx)
4702     return new (Context) MatrixSubscriptExpr(
4703         Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc);
4704 
4705   // Build an unanalyzed expression if any of the operands is type-dependent.
4706   if (Base->isTypeDependent() || RowIdx->isTypeDependent() ||
4707       ColumnIdx->isTypeDependent())
4708     return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
4709                                              Context.DependentTy, RBLoc);
4710 
4711   ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx);
4712   if (ColumnR.isInvalid())
4713     return ColumnR;
4714   ColumnIdx = ColumnR.get();
4715 
4716   // Check that IndexExpr is an integer expression. If it is a constant
4717   // expression, check that it is less than Dim (= the number of elements in the
4718   // corresponding dimension).
4719   auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim,
4720                           bool IsColumnIdx) -> Expr * {
4721     if (!IndexExpr->getType()->isIntegerType() &&
4722         !IndexExpr->isTypeDependent()) {
4723       Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer)
4724           << IsColumnIdx;
4725       return nullptr;
4726     }
4727 
4728     llvm::APSInt Idx;
4729     if (IndexExpr->isIntegerConstantExpr(Idx, Context) &&
4730         (Idx < 0 || Idx >= Dim)) {
4731       Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range)
4732           << IsColumnIdx << Dim;
4733       return nullptr;
4734     }
4735 
4736     ExprResult ConvExpr = IndexExpr;
4737     bool ConversionOk = tryConvertToTy(*this, Context.getSizeType(), &ConvExpr);
4738     assert(ConversionOk &&
4739            "should be able to convert any integer type to size type");
4740     (void)ConversionOk;
4741     return ConvExpr.get();
4742   };
4743 
4744   auto *MTy = Base->getType()->getAs<ConstantMatrixType>();
4745   RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false);
4746   ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true);
4747   if (!RowIdx || !ColumnIdx)
4748     return ExprError();
4749 
4750   return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
4751                                            MTy->getElementType(), RBLoc);
4752 }
4753 
4754 void Sema::CheckAddressOfNoDeref(const Expr *E) {
4755   ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4756   const Expr *StrippedExpr = E->IgnoreParenImpCasts();
4757 
4758   // For expressions like `&(*s).b`, the base is recorded and what should be
4759   // checked.
4760   const MemberExpr *Member = nullptr;
4761   while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow())
4762     StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
4763 
4764   LastRecord.PossibleDerefs.erase(StrippedExpr);
4765 }
4766 
4767 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
4768   QualType ResultTy = E->getType();
4769   ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4770 
4771   // Bail if the element is an array since it is not memory access.
4772   if (isa<ArrayType>(ResultTy))
4773     return;
4774 
4775   if (ResultTy->hasAttr(attr::NoDeref)) {
4776     LastRecord.PossibleDerefs.insert(E);
4777     return;
4778   }
4779 
4780   // Check if the base type is a pointer to a member access of a struct
4781   // marked with noderef.
4782   const Expr *Base = E->getBase();
4783   QualType BaseTy = Base->getType();
4784   if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy)))
4785     // Not a pointer access
4786     return;
4787 
4788   const MemberExpr *Member = nullptr;
4789   while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) &&
4790          Member->isArrow())
4791     Base = Member->getBase();
4792 
4793   if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) {
4794     if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))
4795       LastRecord.PossibleDerefs.insert(E);
4796   }
4797 }
4798 
4799 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4800                                           Expr *LowerBound,
4801                                           SourceLocation ColonLoc, Expr *Length,
4802                                           SourceLocation RBLoc) {
4803   if (Base->getType()->isPlaceholderType() &&
4804       !Base->getType()->isSpecificPlaceholderType(
4805           BuiltinType::OMPArraySection)) {
4806     ExprResult Result = CheckPlaceholderExpr(Base);
4807     if (Result.isInvalid())
4808       return ExprError();
4809     Base = Result.get();
4810   }
4811   if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
4812     ExprResult Result = CheckPlaceholderExpr(LowerBound);
4813     if (Result.isInvalid())
4814       return ExprError();
4815     Result = DefaultLvalueConversion(Result.get());
4816     if (Result.isInvalid())
4817       return ExprError();
4818     LowerBound = Result.get();
4819   }
4820   if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
4821     ExprResult Result = CheckPlaceholderExpr(Length);
4822     if (Result.isInvalid())
4823       return ExprError();
4824     Result = DefaultLvalueConversion(Result.get());
4825     if (Result.isInvalid())
4826       return ExprError();
4827     Length = Result.get();
4828   }
4829 
4830   // Build an unanalyzed expression if either operand is type-dependent.
4831   if (Base->isTypeDependent() ||
4832       (LowerBound &&
4833        (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
4834       (Length && (Length->isTypeDependent() || Length->isValueDependent()))) {
4835     return new (Context)
4836         OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy,
4837                             VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4838   }
4839 
4840   // Perform default conversions.
4841   QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
4842   QualType ResultTy;
4843   if (OriginalTy->isAnyPointerType()) {
4844     ResultTy = OriginalTy->getPointeeType();
4845   } else if (OriginalTy->isArrayType()) {
4846     ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
4847   } else {
4848     return ExprError(
4849         Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
4850         << Base->getSourceRange());
4851   }
4852   // C99 6.5.2.1p1
4853   if (LowerBound) {
4854     auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
4855                                                       LowerBound);
4856     if (Res.isInvalid())
4857       return ExprError(Diag(LowerBound->getExprLoc(),
4858                             diag::err_omp_typecheck_section_not_integer)
4859                        << 0 << LowerBound->getSourceRange());
4860     LowerBound = Res.get();
4861 
4862     if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4863         LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4864       Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
4865           << 0 << LowerBound->getSourceRange();
4866   }
4867   if (Length) {
4868     auto Res =
4869         PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
4870     if (Res.isInvalid())
4871       return ExprError(Diag(Length->getExprLoc(),
4872                             diag::err_omp_typecheck_section_not_integer)
4873                        << 1 << Length->getSourceRange());
4874     Length = Res.get();
4875 
4876     if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4877         Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4878       Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
4879           << 1 << Length->getSourceRange();
4880   }
4881 
4882   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4883   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4884   // type. Note that functions are not objects, and that (in C99 parlance)
4885   // incomplete types are not object types.
4886   if (ResultTy->isFunctionType()) {
4887     Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
4888         << ResultTy << Base->getSourceRange();
4889     return ExprError();
4890   }
4891 
4892   if (RequireCompleteType(Base->getExprLoc(), ResultTy,
4893                           diag::err_omp_section_incomplete_type, Base))
4894     return ExprError();
4895 
4896   if (LowerBound && !OriginalTy->isAnyPointerType()) {
4897     Expr::EvalResult Result;
4898     if (LowerBound->EvaluateAsInt(Result, Context)) {
4899       // OpenMP 4.5, [2.4 Array Sections]
4900       // The array section must be a subset of the original array.
4901       llvm::APSInt LowerBoundValue = Result.Val.getInt();
4902       if (LowerBoundValue.isNegative()) {
4903         Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
4904             << LowerBound->getSourceRange();
4905         return ExprError();
4906       }
4907     }
4908   }
4909 
4910   if (Length) {
4911     Expr::EvalResult Result;
4912     if (Length->EvaluateAsInt(Result, Context)) {
4913       // OpenMP 4.5, [2.4 Array Sections]
4914       // The length must evaluate to non-negative integers.
4915       llvm::APSInt LengthValue = Result.Val.getInt();
4916       if (LengthValue.isNegative()) {
4917         Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
4918             << LengthValue.toString(/*Radix=*/10, /*Signed=*/true)
4919             << Length->getSourceRange();
4920         return ExprError();
4921       }
4922     }
4923   } else if (ColonLoc.isValid() &&
4924              (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
4925                                       !OriginalTy->isVariableArrayType()))) {
4926     // OpenMP 4.5, [2.4 Array Sections]
4927     // When the size of the array dimension is not known, the length must be
4928     // specified explicitly.
4929     Diag(ColonLoc, diag::err_omp_section_length_undefined)
4930         << (!OriginalTy.isNull() && OriginalTy->isArrayType());
4931     return ExprError();
4932   }
4933 
4934   if (!Base->getType()->isSpecificPlaceholderType(
4935           BuiltinType::OMPArraySection)) {
4936     ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
4937     if (Result.isInvalid())
4938       return ExprError();
4939     Base = Result.get();
4940   }
4941   return new (Context)
4942       OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy,
4943                           VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4944 }
4945 
4946 ExprResult Sema::ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc,
4947                                           SourceLocation RParenLoc,
4948                                           ArrayRef<Expr *> Dims,
4949                                           ArrayRef<SourceRange> Brackets) {
4950   if (Base->getType()->isPlaceholderType()) {
4951     ExprResult Result = CheckPlaceholderExpr(Base);
4952     if (Result.isInvalid())
4953       return ExprError();
4954     Result = DefaultLvalueConversion(Result.get());
4955     if (Result.isInvalid())
4956       return ExprError();
4957     Base = Result.get();
4958   }
4959   QualType BaseTy = Base->getType();
4960   // Delay analysis of the types/expressions if instantiation/specialization is
4961   // required.
4962   if (!BaseTy->isPointerType() && Base->isTypeDependent())
4963     return OMPArrayShapingExpr::Create(Context, Context.DependentTy, Base,
4964                                        LParenLoc, RParenLoc, Dims, Brackets);
4965   if (!BaseTy->isPointerType() ||
4966       (!Base->isTypeDependent() &&
4967        BaseTy->getPointeeType()->isIncompleteType()))
4968     return ExprError(Diag(Base->getExprLoc(),
4969                           diag::err_omp_non_pointer_type_array_shaping_base)
4970                      << Base->getSourceRange());
4971 
4972   SmallVector<Expr *, 4> NewDims;
4973   bool ErrorFound = false;
4974   for (Expr *Dim : Dims) {
4975     if (Dim->getType()->isPlaceholderType()) {
4976       ExprResult Result = CheckPlaceholderExpr(Dim);
4977       if (Result.isInvalid()) {
4978         ErrorFound = true;
4979         continue;
4980       }
4981       Result = DefaultLvalueConversion(Result.get());
4982       if (Result.isInvalid()) {
4983         ErrorFound = true;
4984         continue;
4985       }
4986       Dim = Result.get();
4987     }
4988     if (!Dim->isTypeDependent()) {
4989       ExprResult Result =
4990           PerformOpenMPImplicitIntegerConversion(Dim->getExprLoc(), Dim);
4991       if (Result.isInvalid()) {
4992         ErrorFound = true;
4993         Diag(Dim->getExprLoc(), diag::err_omp_typecheck_shaping_not_integer)
4994             << Dim->getSourceRange();
4995         continue;
4996       }
4997       Dim = Result.get();
4998       Expr::EvalResult EvResult;
4999       if (!Dim->isValueDependent() && Dim->EvaluateAsInt(EvResult, Context)) {
5000         // OpenMP 5.0, [2.1.4 Array Shaping]
5001         // Each si is an integral type expression that must evaluate to a
5002         // positive integer.
5003         llvm::APSInt Value = EvResult.Val.getInt();
5004         if (!Value.isStrictlyPositive()) {
5005           Diag(Dim->getExprLoc(), diag::err_omp_shaping_dimension_not_positive)
5006               << Value.toString(/*Radix=*/10, /*Signed=*/true)
5007               << Dim->getSourceRange();
5008           ErrorFound = true;
5009           continue;
5010         }
5011       }
5012     }
5013     NewDims.push_back(Dim);
5014   }
5015   if (ErrorFound)
5016     return ExprError();
5017   return OMPArrayShapingExpr::Create(Context, Context.OMPArrayShapingTy, Base,
5018                                      LParenLoc, RParenLoc, NewDims, Brackets);
5019 }
5020 
5021 ExprResult Sema::ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc,
5022                                       SourceLocation LLoc, SourceLocation RLoc,
5023                                       ArrayRef<OMPIteratorData> Data) {
5024   SmallVector<OMPIteratorExpr::IteratorDefinition, 4> ID;
5025   bool IsCorrect = true;
5026   for (const OMPIteratorData &D : Data) {
5027     TypeSourceInfo *TInfo = nullptr;
5028     SourceLocation StartLoc;
5029     QualType DeclTy;
5030     if (!D.Type.getAsOpaquePtr()) {
5031       // OpenMP 5.0, 2.1.6 Iterators
5032       // In an iterator-specifier, if the iterator-type is not specified then
5033       // the type of that iterator is of int type.
5034       DeclTy = Context.IntTy;
5035       StartLoc = D.DeclIdentLoc;
5036     } else {
5037       DeclTy = GetTypeFromParser(D.Type, &TInfo);
5038       StartLoc = TInfo->getTypeLoc().getBeginLoc();
5039     }
5040 
5041     bool IsDeclTyDependent = DeclTy->isDependentType() ||
5042                              DeclTy->containsUnexpandedParameterPack() ||
5043                              DeclTy->isInstantiationDependentType();
5044     if (!IsDeclTyDependent) {
5045       if (!DeclTy->isIntegralType(Context) && !DeclTy->isAnyPointerType()) {
5046         // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++
5047         // The iterator-type must be an integral or pointer type.
5048         Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer)
5049             << DeclTy;
5050         IsCorrect = false;
5051         continue;
5052       }
5053       if (DeclTy.isConstant(Context)) {
5054         // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++
5055         // The iterator-type must not be const qualified.
5056         Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer)
5057             << DeclTy;
5058         IsCorrect = false;
5059         continue;
5060       }
5061     }
5062 
5063     // Iterator declaration.
5064     assert(D.DeclIdent && "Identifier expected.");
5065     // Always try to create iterator declarator to avoid extra error messages
5066     // about unknown declarations use.
5067     auto *VD = VarDecl::Create(Context, CurContext, StartLoc, D.DeclIdentLoc,
5068                                D.DeclIdent, DeclTy, TInfo, SC_None);
5069     VD->setImplicit();
5070     if (S) {
5071       // Check for conflicting previous declaration.
5072       DeclarationNameInfo NameInfo(VD->getDeclName(), D.DeclIdentLoc);
5073       LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5074                             ForVisibleRedeclaration);
5075       Previous.suppressDiagnostics();
5076       LookupName(Previous, S);
5077 
5078       FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false,
5079                            /*AllowInlineNamespace=*/false);
5080       if (!Previous.empty()) {
5081         NamedDecl *Old = Previous.getRepresentativeDecl();
5082         Diag(D.DeclIdentLoc, diag::err_redefinition) << VD->getDeclName();
5083         Diag(Old->getLocation(), diag::note_previous_definition);
5084       } else {
5085         PushOnScopeChains(VD, S);
5086       }
5087     } else {
5088       CurContext->addDecl(VD);
5089     }
5090     Expr *Begin = D.Range.Begin;
5091     if (!IsDeclTyDependent && Begin && !Begin->isTypeDependent()) {
5092       ExprResult BeginRes =
5093           PerformImplicitConversion(Begin, DeclTy, AA_Converting);
5094       Begin = BeginRes.get();
5095     }
5096     Expr *End = D.Range.End;
5097     if (!IsDeclTyDependent && End && !End->isTypeDependent()) {
5098       ExprResult EndRes = PerformImplicitConversion(End, DeclTy, AA_Converting);
5099       End = EndRes.get();
5100     }
5101     Expr *Step = D.Range.Step;
5102     if (!IsDeclTyDependent && Step && !Step->isTypeDependent()) {
5103       if (!Step->getType()->isIntegralType(Context)) {
5104         Diag(Step->getExprLoc(), diag::err_omp_iterator_step_not_integral)
5105             << Step << Step->getSourceRange();
5106         IsCorrect = false;
5107         continue;
5108       }
5109       llvm::APSInt Result;
5110       bool IsConstant = Step->isIntegerConstantExpr(Result, Context);
5111       // OpenMP 5.0, 2.1.6 Iterators, Restrictions
5112       // If the step expression of a range-specification equals zero, the
5113       // behavior is unspecified.
5114       if (IsConstant && Result.isNullValue()) {
5115         Diag(Step->getExprLoc(), diag::err_omp_iterator_step_constant_zero)
5116             << Step << Step->getSourceRange();
5117         IsCorrect = false;
5118         continue;
5119       }
5120     }
5121     if (!Begin || !End || !IsCorrect) {
5122       IsCorrect = false;
5123       continue;
5124     }
5125     OMPIteratorExpr::IteratorDefinition &IDElem = ID.emplace_back();
5126     IDElem.IteratorDecl = VD;
5127     IDElem.AssignmentLoc = D.AssignLoc;
5128     IDElem.Range.Begin = Begin;
5129     IDElem.Range.End = End;
5130     IDElem.Range.Step = Step;
5131     IDElem.ColonLoc = D.ColonLoc;
5132     IDElem.SecondColonLoc = D.SecColonLoc;
5133   }
5134   if (!IsCorrect) {
5135     // Invalidate all created iterator declarations if error is found.
5136     for (const OMPIteratorExpr::IteratorDefinition &D : ID) {
5137       if (Decl *ID = D.IteratorDecl)
5138         ID->setInvalidDecl();
5139     }
5140     return ExprError();
5141   }
5142   SmallVector<OMPIteratorHelperData, 4> Helpers;
5143   if (!CurContext->isDependentContext()) {
5144     // Build number of ityeration for each iteration range.
5145     // Ni = ((Stepi > 0) ? ((Endi + Stepi -1 - Begini)/Stepi) :
5146     // ((Begini-Stepi-1-Endi) / -Stepi);
5147     for (OMPIteratorExpr::IteratorDefinition &D : ID) {
5148       // (Endi - Begini)
5149       ExprResult Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, D.Range.End,
5150                                           D.Range.Begin);
5151       if(!Res.isUsable()) {
5152         IsCorrect = false;
5153         continue;
5154       }
5155       ExprResult St, St1;
5156       if (D.Range.Step) {
5157         St = D.Range.Step;
5158         // (Endi - Begini) + Stepi
5159         Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res.get(), St.get());
5160         if (!Res.isUsable()) {
5161           IsCorrect = false;
5162           continue;
5163         }
5164         // (Endi - Begini) + Stepi - 1
5165         Res =
5166             CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res.get(),
5167                                ActOnIntegerConstant(D.AssignmentLoc, 1).get());
5168         if (!Res.isUsable()) {
5169           IsCorrect = false;
5170           continue;
5171         }
5172         // ((Endi - Begini) + Stepi - 1) / Stepi
5173         Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res.get(), St.get());
5174         if (!Res.isUsable()) {
5175           IsCorrect = false;
5176           continue;
5177         }
5178         St1 = CreateBuiltinUnaryOp(D.AssignmentLoc, UO_Minus, D.Range.Step);
5179         // (Begini - Endi)
5180         ExprResult Res1 = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub,
5181                                              D.Range.Begin, D.Range.End);
5182         if (!Res1.isUsable()) {
5183           IsCorrect = false;
5184           continue;
5185         }
5186         // (Begini - Endi) - Stepi
5187         Res1 =
5188             CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res1.get(), St1.get());
5189         if (!Res1.isUsable()) {
5190           IsCorrect = false;
5191           continue;
5192         }
5193         // (Begini - Endi) - Stepi - 1
5194         Res1 =
5195             CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res1.get(),
5196                                ActOnIntegerConstant(D.AssignmentLoc, 1).get());
5197         if (!Res1.isUsable()) {
5198           IsCorrect = false;
5199           continue;
5200         }
5201         // ((Begini - Endi) - Stepi - 1) / (-Stepi)
5202         Res1 =
5203             CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res1.get(), St1.get());
5204         if (!Res1.isUsable()) {
5205           IsCorrect = false;
5206           continue;
5207         }
5208         // Stepi > 0.
5209         ExprResult CmpRes =
5210             CreateBuiltinBinOp(D.AssignmentLoc, BO_GT, D.Range.Step,
5211                                ActOnIntegerConstant(D.AssignmentLoc, 0).get());
5212         if (!CmpRes.isUsable()) {
5213           IsCorrect = false;
5214           continue;
5215         }
5216         Res = ActOnConditionalOp(D.AssignmentLoc, D.AssignmentLoc, CmpRes.get(),
5217                                  Res.get(), Res1.get());
5218         if (!Res.isUsable()) {
5219           IsCorrect = false;
5220           continue;
5221         }
5222       }
5223       Res = ActOnFinishFullExpr(Res.get(), /*DiscardedValue=*/false);
5224       if (!Res.isUsable()) {
5225         IsCorrect = false;
5226         continue;
5227       }
5228 
5229       // Build counter update.
5230       // Build counter.
5231       auto *CounterVD =
5232           VarDecl::Create(Context, CurContext, D.IteratorDecl->getBeginLoc(),
5233                           D.IteratorDecl->getBeginLoc(), nullptr,
5234                           Res.get()->getType(), nullptr, SC_None);
5235       CounterVD->setImplicit();
5236       ExprResult RefRes =
5237           BuildDeclRefExpr(CounterVD, CounterVD->getType(), VK_LValue,
5238                            D.IteratorDecl->getBeginLoc());
5239       // Build counter update.
5240       // I = Begini + counter * Stepi;
5241       ExprResult UpdateRes;
5242       if (D.Range.Step) {
5243         UpdateRes = CreateBuiltinBinOp(
5244             D.AssignmentLoc, BO_Mul,
5245             DefaultLvalueConversion(RefRes.get()).get(), St.get());
5246       } else {
5247         UpdateRes = DefaultLvalueConversion(RefRes.get());
5248       }
5249       if (!UpdateRes.isUsable()) {
5250         IsCorrect = false;
5251         continue;
5252       }
5253       UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, D.Range.Begin,
5254                                      UpdateRes.get());
5255       if (!UpdateRes.isUsable()) {
5256         IsCorrect = false;
5257         continue;
5258       }
5259       ExprResult VDRes =
5260           BuildDeclRefExpr(cast<VarDecl>(D.IteratorDecl),
5261                            cast<VarDecl>(D.IteratorDecl)->getType(), VK_LValue,
5262                            D.IteratorDecl->getBeginLoc());
5263       UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Assign, VDRes.get(),
5264                                      UpdateRes.get());
5265       if (!UpdateRes.isUsable()) {
5266         IsCorrect = false;
5267         continue;
5268       }
5269       UpdateRes =
5270           ActOnFinishFullExpr(UpdateRes.get(), /*DiscardedValue=*/true);
5271       if (!UpdateRes.isUsable()) {
5272         IsCorrect = false;
5273         continue;
5274       }
5275       ExprResult CounterUpdateRes =
5276           CreateBuiltinUnaryOp(D.AssignmentLoc, UO_PreInc, RefRes.get());
5277       if (!CounterUpdateRes.isUsable()) {
5278         IsCorrect = false;
5279         continue;
5280       }
5281       CounterUpdateRes =
5282           ActOnFinishFullExpr(CounterUpdateRes.get(), /*DiscardedValue=*/true);
5283       if (!CounterUpdateRes.isUsable()) {
5284         IsCorrect = false;
5285         continue;
5286       }
5287       OMPIteratorHelperData &HD = Helpers.emplace_back();
5288       HD.CounterVD = CounterVD;
5289       HD.Upper = Res.get();
5290       HD.Update = UpdateRes.get();
5291       HD.CounterUpdate = CounterUpdateRes.get();
5292     }
5293   } else {
5294     Helpers.assign(ID.size(), {});
5295   }
5296   if (!IsCorrect) {
5297     // Invalidate all created iterator declarations if error is found.
5298     for (const OMPIteratorExpr::IteratorDefinition &D : ID) {
5299       if (Decl *ID = D.IteratorDecl)
5300         ID->setInvalidDecl();
5301     }
5302     return ExprError();
5303   }
5304   return OMPIteratorExpr::Create(Context, Context.OMPIteratorTy, IteratorKwLoc,
5305                                  LLoc, RLoc, ID, Helpers);
5306 }
5307 
5308 ExprResult
5309 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
5310                                       Expr *Idx, SourceLocation RLoc) {
5311   Expr *LHSExp = Base;
5312   Expr *RHSExp = Idx;
5313 
5314   ExprValueKind VK = VK_LValue;
5315   ExprObjectKind OK = OK_Ordinary;
5316 
5317   // Per C++ core issue 1213, the result is an xvalue if either operand is
5318   // a non-lvalue array, and an lvalue otherwise.
5319   if (getLangOpts().CPlusPlus11) {
5320     for (auto *Op : {LHSExp, RHSExp}) {
5321       Op = Op->IgnoreImplicit();
5322       if (Op->getType()->isArrayType() && !Op->isLValue())
5323         VK = VK_XValue;
5324     }
5325   }
5326 
5327   // Perform default conversions.
5328   if (!LHSExp->getType()->getAs<VectorType>()) {
5329     ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
5330     if (Result.isInvalid())
5331       return ExprError();
5332     LHSExp = Result.get();
5333   }
5334   ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
5335   if (Result.isInvalid())
5336     return ExprError();
5337   RHSExp = Result.get();
5338 
5339   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
5340 
5341   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
5342   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
5343   // in the subscript position. As a result, we need to derive the array base
5344   // and index from the expression types.
5345   Expr *BaseExpr, *IndexExpr;
5346   QualType ResultType;
5347   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
5348     BaseExpr = LHSExp;
5349     IndexExpr = RHSExp;
5350     ResultType = Context.DependentTy;
5351   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
5352     BaseExpr = LHSExp;
5353     IndexExpr = RHSExp;
5354     ResultType = PTy->getPointeeType();
5355   } else if (const ObjCObjectPointerType *PTy =
5356                LHSTy->getAs<ObjCObjectPointerType>()) {
5357     BaseExpr = LHSExp;
5358     IndexExpr = RHSExp;
5359 
5360     // Use custom logic if this should be the pseudo-object subscript
5361     // expression.
5362     if (!LangOpts.isSubscriptPointerArithmetic())
5363       return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
5364                                           nullptr);
5365 
5366     ResultType = PTy->getPointeeType();
5367   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
5368      // Handle the uncommon case of "123[Ptr]".
5369     BaseExpr = RHSExp;
5370     IndexExpr = LHSExp;
5371     ResultType = PTy->getPointeeType();
5372   } else if (const ObjCObjectPointerType *PTy =
5373                RHSTy->getAs<ObjCObjectPointerType>()) {
5374      // Handle the uncommon case of "123[Ptr]".
5375     BaseExpr = RHSExp;
5376     IndexExpr = LHSExp;
5377     ResultType = PTy->getPointeeType();
5378     if (!LangOpts.isSubscriptPointerArithmetic()) {
5379       Diag(LLoc, diag::err_subscript_nonfragile_interface)
5380         << ResultType << BaseExpr->getSourceRange();
5381       return ExprError();
5382     }
5383   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
5384     BaseExpr = LHSExp;    // vectors: V[123]
5385     IndexExpr = RHSExp;
5386     // We apply C++ DR1213 to vector subscripting too.
5387     if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_RValue) {
5388       ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
5389       if (Materialized.isInvalid())
5390         return ExprError();
5391       LHSExp = Materialized.get();
5392     }
5393     VK = LHSExp->getValueKind();
5394     if (VK != VK_RValue)
5395       OK = OK_VectorComponent;
5396 
5397     ResultType = VTy->getElementType();
5398     QualType BaseType = BaseExpr->getType();
5399     Qualifiers BaseQuals = BaseType.getQualifiers();
5400     Qualifiers MemberQuals = ResultType.getQualifiers();
5401     Qualifiers Combined = BaseQuals + MemberQuals;
5402     if (Combined != MemberQuals)
5403       ResultType = Context.getQualifiedType(ResultType, Combined);
5404   } else if (LHSTy->isArrayType()) {
5405     // If we see an array that wasn't promoted by
5406     // DefaultFunctionArrayLvalueConversion, it must be an array that
5407     // wasn't promoted because of the C90 rule that doesn't
5408     // allow promoting non-lvalue arrays.  Warn, then
5409     // force the promotion here.
5410     Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5411         << LHSExp->getSourceRange();
5412     LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
5413                                CK_ArrayToPointerDecay).get();
5414     LHSTy = LHSExp->getType();
5415 
5416     BaseExpr = LHSExp;
5417     IndexExpr = RHSExp;
5418     ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
5419   } else if (RHSTy->isArrayType()) {
5420     // Same as previous, except for 123[f().a] case
5421     Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5422         << RHSExp->getSourceRange();
5423     RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
5424                                CK_ArrayToPointerDecay).get();
5425     RHSTy = RHSExp->getType();
5426 
5427     BaseExpr = RHSExp;
5428     IndexExpr = LHSExp;
5429     ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
5430   } else {
5431     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
5432        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
5433   }
5434   // C99 6.5.2.1p1
5435   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
5436     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
5437                      << IndexExpr->getSourceRange());
5438 
5439   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5440        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5441          && !IndexExpr->isTypeDependent())
5442     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
5443 
5444   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5445   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5446   // type. Note that Functions are not objects, and that (in C99 parlance)
5447   // incomplete types are not object types.
5448   if (ResultType->isFunctionType()) {
5449     Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type)
5450         << ResultType << BaseExpr->getSourceRange();
5451     return ExprError();
5452   }
5453 
5454   if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
5455     // GNU extension: subscripting on pointer to void
5456     Diag(LLoc, diag::ext_gnu_subscript_void_type)
5457       << BaseExpr->getSourceRange();
5458 
5459     // C forbids expressions of unqualified void type from being l-values.
5460     // See IsCForbiddenLValueType.
5461     if (!ResultType.hasQualifiers()) VK = VK_RValue;
5462   } else if (!ResultType->isDependentType() &&
5463              RequireCompleteSizedType(
5464                  LLoc, ResultType,
5465                  diag::err_subscript_incomplete_or_sizeless_type, BaseExpr))
5466     return ExprError();
5467 
5468   assert(VK == VK_RValue || LangOpts.CPlusPlus ||
5469          !ResultType.isCForbiddenLValueType());
5470 
5471   if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() &&
5472       FunctionScopes.size() > 1) {
5473     if (auto *TT =
5474             LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) {
5475       for (auto I = FunctionScopes.rbegin(),
5476                 E = std::prev(FunctionScopes.rend());
5477            I != E; ++I) {
5478         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
5479         if (CSI == nullptr)
5480           break;
5481         DeclContext *DC = nullptr;
5482         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
5483           DC = LSI->CallOperator;
5484         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
5485           DC = CRSI->TheCapturedDecl;
5486         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
5487           DC = BSI->TheDecl;
5488         if (DC) {
5489           if (DC->containsDecl(TT->getDecl()))
5490             break;
5491           captureVariablyModifiedType(
5492               Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI);
5493         }
5494       }
5495     }
5496   }
5497 
5498   return new (Context)
5499       ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
5500 }
5501 
5502 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
5503                                   ParmVarDecl *Param) {
5504   if (Param->hasUnparsedDefaultArg()) {
5505     // If we've already cleared out the location for the default argument,
5506     // that means we're parsing it right now.
5507     if (!UnparsedDefaultArgLocs.count(Param)) {
5508       Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
5509       Diag(CallLoc, diag::note_recursive_default_argument_used_here);
5510       Param->setInvalidDecl();
5511       return true;
5512     }
5513 
5514     Diag(CallLoc,
5515          diag::err_use_of_default_argument_to_function_declared_later) <<
5516       FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
5517     Diag(UnparsedDefaultArgLocs[Param],
5518          diag::note_default_argument_declared_here);
5519     return true;
5520   }
5521 
5522   if (Param->hasUninstantiatedDefaultArg()) {
5523     Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
5524 
5525     EnterExpressionEvaluationContext EvalContext(
5526         *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
5527 
5528     // Instantiate the expression.
5529     //
5530     // FIXME: Pass in a correct Pattern argument, otherwise
5531     // getTemplateInstantiationArgs uses the lexical context of FD, e.g.
5532     //
5533     // template<typename T>
5534     // struct A {
5535     //   static int FooImpl();
5536     //
5537     //   template<typename Tp>
5538     //   // bug: default argument A<T>::FooImpl() is evaluated with 2-level
5539     //   // template argument list [[T], [Tp]], should be [[Tp]].
5540     //   friend A<Tp> Foo(int a);
5541     // };
5542     //
5543     // template<typename T>
5544     // A<T> Foo(int a = A<T>::FooImpl());
5545     MultiLevelTemplateArgumentList MutiLevelArgList
5546       = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true);
5547 
5548     InstantiatingTemplate Inst(*this, CallLoc, Param,
5549                                MutiLevelArgList.getInnermost());
5550     if (Inst.isInvalid())
5551       return true;
5552     if (Inst.isAlreadyInstantiating()) {
5553       Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
5554       Param->setInvalidDecl();
5555       return true;
5556     }
5557 
5558     ExprResult Result;
5559     {
5560       // C++ [dcl.fct.default]p5:
5561       //   The names in the [default argument] expression are bound, and
5562       //   the semantic constraints are checked, at the point where the
5563       //   default argument expression appears.
5564       ContextRAII SavedContext(*this, FD);
5565       LocalInstantiationScope Local(*this);
5566       runWithSufficientStackSpace(CallLoc, [&] {
5567         Result = SubstInitializer(UninstExpr, MutiLevelArgList,
5568                                   /*DirectInit*/false);
5569       });
5570     }
5571     if (Result.isInvalid())
5572       return true;
5573 
5574     // Check the expression as an initializer for the parameter.
5575     InitializedEntity Entity
5576       = InitializedEntity::InitializeParameter(Context, Param);
5577     InitializationKind Kind = InitializationKind::CreateCopy(
5578         Param->getLocation(),
5579         /*FIXME:EqualLoc*/ UninstExpr->getBeginLoc());
5580     Expr *ResultE = Result.getAs<Expr>();
5581 
5582     InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
5583     Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
5584     if (Result.isInvalid())
5585       return true;
5586 
5587     Result =
5588         ActOnFinishFullExpr(Result.getAs<Expr>(), Param->getOuterLocStart(),
5589                             /*DiscardedValue*/ false);
5590     if (Result.isInvalid())
5591       return true;
5592 
5593     // Remember the instantiated default argument.
5594     Param->setDefaultArg(Result.getAs<Expr>());
5595     if (ASTMutationListener *L = getASTMutationListener()) {
5596       L->DefaultArgumentInstantiated(Param);
5597     }
5598   }
5599 
5600   assert(Param->hasInit() && "default argument but no initializer?");
5601 
5602   // If the default expression creates temporaries, we need to
5603   // push them to the current stack of expression temporaries so they'll
5604   // be properly destroyed.
5605   // FIXME: We should really be rebuilding the default argument with new
5606   // bound temporaries; see the comment in PR5810.
5607   // We don't need to do that with block decls, though, because
5608   // blocks in default argument expression can never capture anything.
5609   if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
5610     // Set the "needs cleanups" bit regardless of whether there are
5611     // any explicit objects.
5612     Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
5613 
5614     // Append all the objects to the cleanup list.  Right now, this
5615     // should always be a no-op, because blocks in default argument
5616     // expressions should never be able to capture anything.
5617     assert(!Init->getNumObjects() &&
5618            "default argument expression has capturing blocks?");
5619   }
5620 
5621   // We already type-checked the argument, so we know it works.
5622   // Just mark all of the declarations in this potentially-evaluated expression
5623   // as being "referenced".
5624   EnterExpressionEvaluationContext EvalContext(
5625       *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
5626   MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
5627                                    /*SkipLocalVariables=*/true);
5628   return false;
5629 }
5630 
5631 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
5632                                         FunctionDecl *FD, ParmVarDecl *Param) {
5633   assert(Param->hasDefaultArg() && "can't build nonexistent default arg");
5634   if (CheckCXXDefaultArgExpr(CallLoc, FD, Param))
5635     return ExprError();
5636   return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext);
5637 }
5638 
5639 Sema::VariadicCallType
5640 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
5641                           Expr *Fn) {
5642   if (Proto && Proto->isVariadic()) {
5643     if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
5644       return VariadicConstructor;
5645     else if (Fn && Fn->getType()->isBlockPointerType())
5646       return VariadicBlock;
5647     else if (FDecl) {
5648       if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5649         if (Method->isInstance())
5650           return VariadicMethod;
5651     } else if (Fn && Fn->getType() == Context.BoundMemberTy)
5652       return VariadicMethod;
5653     return VariadicFunction;
5654   }
5655   return VariadicDoesNotApply;
5656 }
5657 
5658 namespace {
5659 class FunctionCallCCC final : public FunctionCallFilterCCC {
5660 public:
5661   FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
5662                   unsigned NumArgs, MemberExpr *ME)
5663       : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
5664         FunctionName(FuncName) {}
5665 
5666   bool ValidateCandidate(const TypoCorrection &candidate) override {
5667     if (!candidate.getCorrectionSpecifier() ||
5668         candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
5669       return false;
5670     }
5671 
5672     return FunctionCallFilterCCC::ValidateCandidate(candidate);
5673   }
5674 
5675   std::unique_ptr<CorrectionCandidateCallback> clone() override {
5676     return std::make_unique<FunctionCallCCC>(*this);
5677   }
5678 
5679 private:
5680   const IdentifierInfo *const FunctionName;
5681 };
5682 }
5683 
5684 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
5685                                                FunctionDecl *FDecl,
5686                                                ArrayRef<Expr *> Args) {
5687   MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
5688   DeclarationName FuncName = FDecl->getDeclName();
5689   SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
5690 
5691   FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
5692   if (TypoCorrection Corrected = S.CorrectTypo(
5693           DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
5694           S.getScopeForContext(S.CurContext), nullptr, CCC,
5695           Sema::CTK_ErrorRecovery)) {
5696     if (NamedDecl *ND = Corrected.getFoundDecl()) {
5697       if (Corrected.isOverloaded()) {
5698         OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
5699         OverloadCandidateSet::iterator Best;
5700         for (NamedDecl *CD : Corrected) {
5701           if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
5702             S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
5703                                    OCS);
5704         }
5705         switch (OCS.BestViableFunction(S, NameLoc, Best)) {
5706         case OR_Success:
5707           ND = Best->FoundDecl;
5708           Corrected.setCorrectionDecl(ND);
5709           break;
5710         default:
5711           break;
5712         }
5713       }
5714       ND = ND->getUnderlyingDecl();
5715       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
5716         return Corrected;
5717     }
5718   }
5719   return TypoCorrection();
5720 }
5721 
5722 /// ConvertArgumentsForCall - Converts the arguments specified in
5723 /// Args/NumArgs to the parameter types of the function FDecl with
5724 /// function prototype Proto. Call is the call expression itself, and
5725 /// Fn is the function expression. For a C++ member function, this
5726 /// routine does not attempt to convert the object argument. Returns
5727 /// true if the call is ill-formed.
5728 bool
5729 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
5730                               FunctionDecl *FDecl,
5731                               const FunctionProtoType *Proto,
5732                               ArrayRef<Expr *> Args,
5733                               SourceLocation RParenLoc,
5734                               bool IsExecConfig) {
5735   // Bail out early if calling a builtin with custom typechecking.
5736   if (FDecl)
5737     if (unsigned ID = FDecl->getBuiltinID())
5738       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
5739         return false;
5740 
5741   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
5742   // assignment, to the types of the corresponding parameter, ...
5743   unsigned NumParams = Proto->getNumParams();
5744   bool Invalid = false;
5745   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
5746   unsigned FnKind = Fn->getType()->isBlockPointerType()
5747                        ? 1 /* block */
5748                        : (IsExecConfig ? 3 /* kernel function (exec config) */
5749                                        : 0 /* function */);
5750 
5751   // If too few arguments are available (and we don't have default
5752   // arguments for the remaining parameters), don't make the call.
5753   if (Args.size() < NumParams) {
5754     if (Args.size() < MinArgs) {
5755       TypoCorrection TC;
5756       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5757         unsigned diag_id =
5758             MinArgs == NumParams && !Proto->isVariadic()
5759                 ? diag::err_typecheck_call_too_few_args_suggest
5760                 : diag::err_typecheck_call_too_few_args_at_least_suggest;
5761         diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
5762                                         << static_cast<unsigned>(Args.size())
5763                                         << TC.getCorrectionRange());
5764       } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
5765         Diag(RParenLoc,
5766              MinArgs == NumParams && !Proto->isVariadic()
5767                  ? diag::err_typecheck_call_too_few_args_one
5768                  : diag::err_typecheck_call_too_few_args_at_least_one)
5769             << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
5770       else
5771         Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
5772                             ? diag::err_typecheck_call_too_few_args
5773                             : diag::err_typecheck_call_too_few_args_at_least)
5774             << FnKind << MinArgs << static_cast<unsigned>(Args.size())
5775             << Fn->getSourceRange();
5776 
5777       // Emit the location of the prototype.
5778       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5779         Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
5780 
5781       return true;
5782     }
5783     // We reserve space for the default arguments when we create
5784     // the call expression, before calling ConvertArgumentsForCall.
5785     assert((Call->getNumArgs() == NumParams) &&
5786            "We should have reserved space for the default arguments before!");
5787   }
5788 
5789   // If too many are passed and not variadic, error on the extras and drop
5790   // them.
5791   if (Args.size() > NumParams) {
5792     if (!Proto->isVariadic()) {
5793       TypoCorrection TC;
5794       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5795         unsigned diag_id =
5796             MinArgs == NumParams && !Proto->isVariadic()
5797                 ? diag::err_typecheck_call_too_many_args_suggest
5798                 : diag::err_typecheck_call_too_many_args_at_most_suggest;
5799         diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
5800                                         << static_cast<unsigned>(Args.size())
5801                                         << TC.getCorrectionRange());
5802       } else if (NumParams == 1 && FDecl &&
5803                  FDecl->getParamDecl(0)->getDeclName())
5804         Diag(Args[NumParams]->getBeginLoc(),
5805              MinArgs == NumParams
5806                  ? diag::err_typecheck_call_too_many_args_one
5807                  : diag::err_typecheck_call_too_many_args_at_most_one)
5808             << FnKind << FDecl->getParamDecl(0)
5809             << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
5810             << SourceRange(Args[NumParams]->getBeginLoc(),
5811                            Args.back()->getEndLoc());
5812       else
5813         Diag(Args[NumParams]->getBeginLoc(),
5814              MinArgs == NumParams
5815                  ? diag::err_typecheck_call_too_many_args
5816                  : diag::err_typecheck_call_too_many_args_at_most)
5817             << FnKind << NumParams << static_cast<unsigned>(Args.size())
5818             << Fn->getSourceRange()
5819             << SourceRange(Args[NumParams]->getBeginLoc(),
5820                            Args.back()->getEndLoc());
5821 
5822       // Emit the location of the prototype.
5823       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5824         Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
5825 
5826       // This deletes the extra arguments.
5827       Call->shrinkNumArgs(NumParams);
5828       return true;
5829     }
5830   }
5831   SmallVector<Expr *, 8> AllArgs;
5832   VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
5833 
5834   Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args,
5835                                    AllArgs, CallType);
5836   if (Invalid)
5837     return true;
5838   unsigned TotalNumArgs = AllArgs.size();
5839   for (unsigned i = 0; i < TotalNumArgs; ++i)
5840     Call->setArg(i, AllArgs[i]);
5841 
5842   return false;
5843 }
5844 
5845 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
5846                                   const FunctionProtoType *Proto,
5847                                   unsigned FirstParam, ArrayRef<Expr *> Args,
5848                                   SmallVectorImpl<Expr *> &AllArgs,
5849                                   VariadicCallType CallType, bool AllowExplicit,
5850                                   bool IsListInitialization) {
5851   unsigned NumParams = Proto->getNumParams();
5852   bool Invalid = false;
5853   size_t ArgIx = 0;
5854   // Continue to check argument types (even if we have too few/many args).
5855   for (unsigned i = FirstParam; i < NumParams; i++) {
5856     QualType ProtoArgType = Proto->getParamType(i);
5857 
5858     Expr *Arg;
5859     ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
5860     if (ArgIx < Args.size()) {
5861       Arg = Args[ArgIx++];
5862 
5863       if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType,
5864                               diag::err_call_incomplete_argument, Arg))
5865         return true;
5866 
5867       // Strip the unbridged-cast placeholder expression off, if applicable.
5868       bool CFAudited = false;
5869       if (Arg->getType() == Context.ARCUnbridgedCastTy &&
5870           FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5871           (!Param || !Param->hasAttr<CFConsumedAttr>()))
5872         Arg = stripARCUnbridgedCast(Arg);
5873       else if (getLangOpts().ObjCAutoRefCount &&
5874                FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5875                (!Param || !Param->hasAttr<CFConsumedAttr>()))
5876         CFAudited = true;
5877 
5878       if (Proto->getExtParameterInfo(i).isNoEscape())
5879         if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
5880           BE->getBlockDecl()->setDoesNotEscape();
5881 
5882       InitializedEntity Entity =
5883           Param ? InitializedEntity::InitializeParameter(Context, Param,
5884                                                          ProtoArgType)
5885                 : InitializedEntity::InitializeParameter(
5886                       Context, ProtoArgType, Proto->isParamConsumed(i));
5887 
5888       // Remember that parameter belongs to a CF audited API.
5889       if (CFAudited)
5890         Entity.setParameterCFAudited();
5891 
5892       ExprResult ArgE = PerformCopyInitialization(
5893           Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
5894       if (ArgE.isInvalid())
5895         return true;
5896 
5897       Arg = ArgE.getAs<Expr>();
5898     } else {
5899       assert(Param && "can't use default arguments without a known callee");
5900 
5901       ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
5902       if (ArgExpr.isInvalid())
5903         return true;
5904 
5905       Arg = ArgExpr.getAs<Expr>();
5906     }
5907 
5908     // Check for array bounds violations for each argument to the call. This
5909     // check only triggers warnings when the argument isn't a more complex Expr
5910     // with its own checking, such as a BinaryOperator.
5911     CheckArrayAccess(Arg);
5912 
5913     // Check for violations of C99 static array rules (C99 6.7.5.3p7).
5914     CheckStaticArrayArgument(CallLoc, Param, Arg);
5915 
5916     AllArgs.push_back(Arg);
5917   }
5918 
5919   // If this is a variadic call, handle args passed through "...".
5920   if (CallType != VariadicDoesNotApply) {
5921     // Assume that extern "C" functions with variadic arguments that
5922     // return __unknown_anytype aren't *really* variadic.
5923     if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
5924         FDecl->isExternC()) {
5925       for (Expr *A : Args.slice(ArgIx)) {
5926         QualType paramType; // ignored
5927         ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
5928         Invalid |= arg.isInvalid();
5929         AllArgs.push_back(arg.get());
5930       }
5931 
5932     // Otherwise do argument promotion, (C99 6.5.2.2p7).
5933     } else {
5934       for (Expr *A : Args.slice(ArgIx)) {
5935         ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
5936         Invalid |= Arg.isInvalid();
5937         // Copy blocks to the heap.
5938         if (A->getType()->isBlockPointerType())
5939           maybeExtendBlockObject(Arg);
5940         AllArgs.push_back(Arg.get());
5941       }
5942     }
5943 
5944     // Check for array bounds violations.
5945     for (Expr *A : Args.slice(ArgIx))
5946       CheckArrayAccess(A);
5947   }
5948   return Invalid;
5949 }
5950 
5951 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
5952   TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
5953   if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
5954     TL = DTL.getOriginalLoc();
5955   if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
5956     S.Diag(PVD->getLocation(), diag::note_callee_static_array)
5957       << ATL.getLocalSourceRange();
5958 }
5959 
5960 /// CheckStaticArrayArgument - If the given argument corresponds to a static
5961 /// array parameter, check that it is non-null, and that if it is formed by
5962 /// array-to-pointer decay, the underlying array is sufficiently large.
5963 ///
5964 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
5965 /// array type derivation, then for each call to the function, the value of the
5966 /// corresponding actual argument shall provide access to the first element of
5967 /// an array with at least as many elements as specified by the size expression.
5968 void
5969 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
5970                                ParmVarDecl *Param,
5971                                const Expr *ArgExpr) {
5972   // Static array parameters are not supported in C++.
5973   if (!Param || getLangOpts().CPlusPlus)
5974     return;
5975 
5976   QualType OrigTy = Param->getOriginalType();
5977 
5978   const ArrayType *AT = Context.getAsArrayType(OrigTy);
5979   if (!AT || AT->getSizeModifier() != ArrayType::Static)
5980     return;
5981 
5982   if (ArgExpr->isNullPointerConstant(Context,
5983                                      Expr::NPC_NeverValueDependent)) {
5984     Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
5985     DiagnoseCalleeStaticArrayParam(*this, Param);
5986     return;
5987   }
5988 
5989   const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
5990   if (!CAT)
5991     return;
5992 
5993   const ConstantArrayType *ArgCAT =
5994     Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType());
5995   if (!ArgCAT)
5996     return;
5997 
5998   if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(),
5999                                              ArgCAT->getElementType())) {
6000     if (ArgCAT->getSize().ult(CAT->getSize())) {
6001       Diag(CallLoc, diag::warn_static_array_too_small)
6002           << ArgExpr->getSourceRange()
6003           << (unsigned)ArgCAT->getSize().getZExtValue()
6004           << (unsigned)CAT->getSize().getZExtValue() << 0;
6005       DiagnoseCalleeStaticArrayParam(*this, Param);
6006     }
6007     return;
6008   }
6009 
6010   Optional<CharUnits> ArgSize =
6011       getASTContext().getTypeSizeInCharsIfKnown(ArgCAT);
6012   Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT);
6013   if (ArgSize && ParmSize && *ArgSize < *ParmSize) {
6014     Diag(CallLoc, diag::warn_static_array_too_small)
6015         << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()
6016         << (unsigned)ParmSize->getQuantity() << 1;
6017     DiagnoseCalleeStaticArrayParam(*this, Param);
6018   }
6019 }
6020 
6021 /// Given a function expression of unknown-any type, try to rebuild it
6022 /// to have a function type.
6023 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
6024 
6025 /// Is the given type a placeholder that we need to lower out
6026 /// immediately during argument processing?
6027 static bool isPlaceholderToRemoveAsArg(QualType type) {
6028   // Placeholders are never sugared.
6029   const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
6030   if (!placeholder) return false;
6031 
6032   switch (placeholder->getKind()) {
6033   // Ignore all the non-placeholder types.
6034 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6035   case BuiltinType::Id:
6036 #include "clang/Basic/OpenCLImageTypes.def"
6037 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6038   case BuiltinType::Id:
6039 #include "clang/Basic/OpenCLExtensionTypes.def"
6040   // In practice we'll never use this, since all SVE types are sugared
6041   // via TypedefTypes rather than exposed directly as BuiltinTypes.
6042 #define SVE_TYPE(Name, Id, SingletonId) \
6043   case BuiltinType::Id:
6044 #include "clang/Basic/AArch64SVEACLETypes.def"
6045 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
6046 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
6047 #include "clang/AST/BuiltinTypes.def"
6048     return false;
6049 
6050   // We cannot lower out overload sets; they might validly be resolved
6051   // by the call machinery.
6052   case BuiltinType::Overload:
6053     return false;
6054 
6055   // Unbridged casts in ARC can be handled in some call positions and
6056   // should be left in place.
6057   case BuiltinType::ARCUnbridgedCast:
6058     return false;
6059 
6060   // Pseudo-objects should be converted as soon as possible.
6061   case BuiltinType::PseudoObject:
6062     return true;
6063 
6064   // The debugger mode could theoretically but currently does not try
6065   // to resolve unknown-typed arguments based on known parameter types.
6066   case BuiltinType::UnknownAny:
6067     return true;
6068 
6069   // These are always invalid as call arguments and should be reported.
6070   case BuiltinType::BoundMember:
6071   case BuiltinType::BuiltinFn:
6072   case BuiltinType::IncompleteMatrixIdx:
6073   case BuiltinType::OMPArraySection:
6074   case BuiltinType::OMPArrayShaping:
6075   case BuiltinType::OMPIterator:
6076     return true;
6077 
6078   }
6079   llvm_unreachable("bad builtin type kind");
6080 }
6081 
6082 /// Check an argument list for placeholders that we won't try to
6083 /// handle later.
6084 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
6085   // Apply this processing to all the arguments at once instead of
6086   // dying at the first failure.
6087   bool hasInvalid = false;
6088   for (size_t i = 0, e = args.size(); i != e; i++) {
6089     if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
6090       ExprResult result = S.CheckPlaceholderExpr(args[i]);
6091       if (result.isInvalid()) hasInvalid = true;
6092       else args[i] = result.get();
6093     } else if (hasInvalid) {
6094       (void)S.CorrectDelayedTyposInExpr(args[i]);
6095     }
6096   }
6097   return hasInvalid;
6098 }
6099 
6100 /// If a builtin function has a pointer argument with no explicit address
6101 /// space, then it should be able to accept a pointer to any address
6102 /// space as input.  In order to do this, we need to replace the
6103 /// standard builtin declaration with one that uses the same address space
6104 /// as the call.
6105 ///
6106 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
6107 ///                  it does not contain any pointer arguments without
6108 ///                  an address space qualifer.  Otherwise the rewritten
6109 ///                  FunctionDecl is returned.
6110 /// TODO: Handle pointer return types.
6111 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
6112                                                 FunctionDecl *FDecl,
6113                                                 MultiExprArg ArgExprs) {
6114 
6115   QualType DeclType = FDecl->getType();
6116   const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
6117 
6118   if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT ||
6119       ArgExprs.size() < FT->getNumParams())
6120     return nullptr;
6121 
6122   bool NeedsNewDecl = false;
6123   unsigned i = 0;
6124   SmallVector<QualType, 8> OverloadParams;
6125 
6126   for (QualType ParamType : FT->param_types()) {
6127 
6128     // Convert array arguments to pointer to simplify type lookup.
6129     ExprResult ArgRes =
6130         Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
6131     if (ArgRes.isInvalid())
6132       return nullptr;
6133     Expr *Arg = ArgRes.get();
6134     QualType ArgType = Arg->getType();
6135     if (!ParamType->isPointerType() ||
6136         ParamType.hasAddressSpace() ||
6137         !ArgType->isPointerType() ||
6138         !ArgType->getPointeeType().hasAddressSpace()) {
6139       OverloadParams.push_back(ParamType);
6140       continue;
6141     }
6142 
6143     QualType PointeeType = ParamType->getPointeeType();
6144     if (PointeeType.hasAddressSpace())
6145       continue;
6146 
6147     NeedsNewDecl = true;
6148     LangAS AS = ArgType->getPointeeType().getAddressSpace();
6149 
6150     PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
6151     OverloadParams.push_back(Context.getPointerType(PointeeType));
6152   }
6153 
6154   if (!NeedsNewDecl)
6155     return nullptr;
6156 
6157   FunctionProtoType::ExtProtoInfo EPI;
6158   EPI.Variadic = FT->isVariadic();
6159   QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
6160                                                 OverloadParams, EPI);
6161   DeclContext *Parent = FDecl->getParent();
6162   FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
6163                                                     FDecl->getLocation(),
6164                                                     FDecl->getLocation(),
6165                                                     FDecl->getIdentifier(),
6166                                                     OverloadTy,
6167                                                     /*TInfo=*/nullptr,
6168                                                     SC_Extern, false,
6169                                                     /*hasPrototype=*/true);
6170   SmallVector<ParmVarDecl*, 16> Params;
6171   FT = cast<FunctionProtoType>(OverloadTy);
6172   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
6173     QualType ParamType = FT->getParamType(i);
6174     ParmVarDecl *Parm =
6175         ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
6176                                 SourceLocation(), nullptr, ParamType,
6177                                 /*TInfo=*/nullptr, SC_None, nullptr);
6178     Parm->setScopeInfo(0, i);
6179     Params.push_back(Parm);
6180   }
6181   OverloadDecl->setParams(Params);
6182   return OverloadDecl;
6183 }
6184 
6185 static void checkDirectCallValidity(Sema &S, const Expr *Fn,
6186                                     FunctionDecl *Callee,
6187                                     MultiExprArg ArgExprs) {
6188   // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
6189   // similar attributes) really don't like it when functions are called with an
6190   // invalid number of args.
6191   if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
6192                          /*PartialOverloading=*/false) &&
6193       !Callee->isVariadic())
6194     return;
6195   if (Callee->getMinRequiredArguments() > ArgExprs.size())
6196     return;
6197 
6198   if (const EnableIfAttr *Attr =
6199           S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) {
6200     S.Diag(Fn->getBeginLoc(),
6201            isa<CXXMethodDecl>(Callee)
6202                ? diag::err_ovl_no_viable_member_function_in_call
6203                : diag::err_ovl_no_viable_function_in_call)
6204         << Callee << Callee->getSourceRange();
6205     S.Diag(Callee->getLocation(),
6206            diag::note_ovl_candidate_disabled_by_function_cond_attr)
6207         << Attr->getCond()->getSourceRange() << Attr->getMessage();
6208     return;
6209   }
6210 }
6211 
6212 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(
6213     const UnresolvedMemberExpr *const UME, Sema &S) {
6214 
6215   const auto GetFunctionLevelDCIfCXXClass =
6216       [](Sema &S) -> const CXXRecordDecl * {
6217     const DeclContext *const DC = S.getFunctionLevelDeclContext();
6218     if (!DC || !DC->getParent())
6219       return nullptr;
6220 
6221     // If the call to some member function was made from within a member
6222     // function body 'M' return return 'M's parent.
6223     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
6224       return MD->getParent()->getCanonicalDecl();
6225     // else the call was made from within a default member initializer of a
6226     // class, so return the class.
6227     if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
6228       return RD->getCanonicalDecl();
6229     return nullptr;
6230   };
6231   // If our DeclContext is neither a member function nor a class (in the
6232   // case of a lambda in a default member initializer), we can't have an
6233   // enclosing 'this'.
6234 
6235   const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
6236   if (!CurParentClass)
6237     return false;
6238 
6239   // The naming class for implicit member functions call is the class in which
6240   // name lookup starts.
6241   const CXXRecordDecl *const NamingClass =
6242       UME->getNamingClass()->getCanonicalDecl();
6243   assert(NamingClass && "Must have naming class even for implicit access");
6244 
6245   // If the unresolved member functions were found in a 'naming class' that is
6246   // related (either the same or derived from) to the class that contains the
6247   // member function that itself contained the implicit member access.
6248 
6249   return CurParentClass == NamingClass ||
6250          CurParentClass->isDerivedFrom(NamingClass);
6251 }
6252 
6253 static void
6254 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
6255     Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
6256 
6257   if (!UME)
6258     return;
6259 
6260   LambdaScopeInfo *const CurLSI = S.getCurLambda();
6261   // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
6262   // already been captured, or if this is an implicit member function call (if
6263   // it isn't, an attempt to capture 'this' should already have been made).
6264   if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
6265       !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
6266     return;
6267 
6268   // Check if the naming class in which the unresolved members were found is
6269   // related (same as or is a base of) to the enclosing class.
6270 
6271   if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S))
6272     return;
6273 
6274 
6275   DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
6276   // If the enclosing function is not dependent, then this lambda is
6277   // capture ready, so if we can capture this, do so.
6278   if (!EnclosingFunctionCtx->isDependentContext()) {
6279     // If the current lambda and all enclosing lambdas can capture 'this' -
6280     // then go ahead and capture 'this' (since our unresolved overload set
6281     // contains at least one non-static member function).
6282     if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
6283       S.CheckCXXThisCapture(CallLoc);
6284   } else if (S.CurContext->isDependentContext()) {
6285     // ... since this is an implicit member reference, that might potentially
6286     // involve a 'this' capture, mark 'this' for potential capture in
6287     // enclosing lambdas.
6288     if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
6289       CurLSI->addPotentialThisCapture(CallLoc);
6290   }
6291 }
6292 
6293 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
6294                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
6295                                Expr *ExecConfig) {
6296   ExprResult Call =
6297       BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig);
6298   if (Call.isInvalid())
6299     return Call;
6300 
6301   // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier
6302   // language modes.
6303   if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) {
6304     if (ULE->hasExplicitTemplateArgs() &&
6305         ULE->decls_begin() == ULE->decls_end()) {
6306       Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus20
6307                                  ? diag::warn_cxx17_compat_adl_only_template_id
6308                                  : diag::ext_adl_only_template_id)
6309           << ULE->getName();
6310     }
6311   }
6312 
6313   if (LangOpts.OpenMP)
6314     Call = ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc,
6315                            ExecConfig);
6316 
6317   return Call;
6318 }
6319 
6320 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments.
6321 /// This provides the location of the left/right parens and a list of comma
6322 /// locations.
6323 ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
6324                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
6325                                Expr *ExecConfig, bool IsExecConfig) {
6326   // Since this might be a postfix expression, get rid of ParenListExprs.
6327   ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
6328   if (Result.isInvalid()) return ExprError();
6329   Fn = Result.get();
6330 
6331   if (checkArgsForPlaceholders(*this, ArgExprs))
6332     return ExprError();
6333 
6334   if (getLangOpts().CPlusPlus) {
6335     // If this is a pseudo-destructor expression, build the call immediately.
6336     if (isa<CXXPseudoDestructorExpr>(Fn)) {
6337       if (!ArgExprs.empty()) {
6338         // Pseudo-destructor calls should not have any arguments.
6339         Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args)
6340             << FixItHint::CreateRemoval(
6341                    SourceRange(ArgExprs.front()->getBeginLoc(),
6342                                ArgExprs.back()->getEndLoc()));
6343       }
6344 
6345       return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy,
6346                               VK_RValue, RParenLoc);
6347     }
6348     if (Fn->getType() == Context.PseudoObjectTy) {
6349       ExprResult result = CheckPlaceholderExpr(Fn);
6350       if (result.isInvalid()) return ExprError();
6351       Fn = result.get();
6352     }
6353 
6354     // Determine whether this is a dependent call inside a C++ template,
6355     // in which case we won't do any semantic analysis now.
6356     if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) {
6357       if (ExecConfig) {
6358         return CUDAKernelCallExpr::Create(
6359             Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
6360             Context.DependentTy, VK_RValue, RParenLoc);
6361       } else {
6362 
6363         tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
6364             *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
6365             Fn->getBeginLoc());
6366 
6367         return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6368                                 VK_RValue, RParenLoc);
6369       }
6370     }
6371 
6372     // Determine whether this is a call to an object (C++ [over.call.object]).
6373     if (Fn->getType()->isRecordType())
6374       return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
6375                                           RParenLoc);
6376 
6377     if (Fn->getType() == Context.UnknownAnyTy) {
6378       ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6379       if (result.isInvalid()) return ExprError();
6380       Fn = result.get();
6381     }
6382 
6383     if (Fn->getType() == Context.BoundMemberTy) {
6384       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6385                                        RParenLoc);
6386     }
6387   }
6388 
6389   // Check for overloaded calls.  This can happen even in C due to extensions.
6390   if (Fn->getType() == Context.OverloadTy) {
6391     OverloadExpr::FindResult find = OverloadExpr::find(Fn);
6392 
6393     // We aren't supposed to apply this logic if there's an '&' involved.
6394     if (!find.HasFormOfMemberPointer) {
6395       if (Expr::hasAnyTypeDependentArguments(ArgExprs))
6396         return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6397                                 VK_RValue, RParenLoc);
6398       OverloadExpr *ovl = find.Expression;
6399       if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
6400         return BuildOverloadedCallExpr(
6401             Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6402             /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
6403       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6404                                        RParenLoc);
6405     }
6406   }
6407 
6408   // If we're directly calling a function, get the appropriate declaration.
6409   if (Fn->getType() == Context.UnknownAnyTy) {
6410     ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6411     if (result.isInvalid()) return ExprError();
6412     Fn = result.get();
6413   }
6414 
6415   Expr *NakedFn = Fn->IgnoreParens();
6416 
6417   bool CallingNDeclIndirectly = false;
6418   NamedDecl *NDecl = nullptr;
6419   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
6420     if (UnOp->getOpcode() == UO_AddrOf) {
6421       CallingNDeclIndirectly = true;
6422       NakedFn = UnOp->getSubExpr()->IgnoreParens();
6423     }
6424   }
6425 
6426   if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
6427     NDecl = DRE->getDecl();
6428 
6429     FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
6430     if (FDecl && FDecl->getBuiltinID()) {
6431       // Rewrite the function decl for this builtin by replacing parameters
6432       // with no explicit address space with the address space of the arguments
6433       // in ArgExprs.
6434       if ((FDecl =
6435                rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
6436         NDecl = FDecl;
6437         Fn = DeclRefExpr::Create(
6438             Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
6439             SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl,
6440             nullptr, DRE->isNonOdrUse());
6441       }
6442     }
6443   } else if (isa<MemberExpr>(NakedFn))
6444     NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
6445 
6446   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
6447     if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
6448                                       FD, /*Complain=*/true, Fn->getBeginLoc()))
6449       return ExprError();
6450 
6451     if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn))
6452       return ExprError();
6453 
6454     checkDirectCallValidity(*this, Fn, FD, ArgExprs);
6455   }
6456 
6457   return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
6458                                ExecConfig, IsExecConfig);
6459 }
6460 
6461 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
6462 ///
6463 /// __builtin_astype( value, dst type )
6464 ///
6465 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
6466                                  SourceLocation BuiltinLoc,
6467                                  SourceLocation RParenLoc) {
6468   ExprValueKind VK = VK_RValue;
6469   ExprObjectKind OK = OK_Ordinary;
6470   QualType DstTy = GetTypeFromParser(ParsedDestTy);
6471   QualType SrcTy = E->getType();
6472   if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
6473     return ExprError(Diag(BuiltinLoc,
6474                           diag::err_invalid_astype_of_different_size)
6475                      << DstTy
6476                      << SrcTy
6477                      << E->getSourceRange());
6478   return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
6479 }
6480 
6481 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
6482 /// provided arguments.
6483 ///
6484 /// __builtin_convertvector( value, dst type )
6485 ///
6486 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
6487                                         SourceLocation BuiltinLoc,
6488                                         SourceLocation RParenLoc) {
6489   TypeSourceInfo *TInfo;
6490   GetTypeFromParser(ParsedDestTy, &TInfo);
6491   return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
6492 }
6493 
6494 /// BuildResolvedCallExpr - Build a call to a resolved expression,
6495 /// i.e. an expression not of \p OverloadTy.  The expression should
6496 /// unary-convert to an expression of function-pointer or
6497 /// block-pointer type.
6498 ///
6499 /// \param NDecl the declaration being called, if available
6500 ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
6501                                        SourceLocation LParenLoc,
6502                                        ArrayRef<Expr *> Args,
6503                                        SourceLocation RParenLoc, Expr *Config,
6504                                        bool IsExecConfig, ADLCallKind UsesADL) {
6505   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
6506   unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
6507 
6508   // Functions with 'interrupt' attribute cannot be called directly.
6509   if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
6510     Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
6511     return ExprError();
6512   }
6513 
6514   // Interrupt handlers don't save off the VFP regs automatically on ARM,
6515   // so there's some risk when calling out to non-interrupt handler functions
6516   // that the callee might not preserve them. This is easy to diagnose here,
6517   // but can be very challenging to debug.
6518   if (auto *Caller = getCurFunctionDecl())
6519     if (Caller->hasAttr<ARMInterruptAttr>()) {
6520       bool VFP = Context.getTargetInfo().hasFeature("vfp");
6521       if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>()))
6522         Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention);
6523     }
6524 
6525   // Promote the function operand.
6526   // We special-case function promotion here because we only allow promoting
6527   // builtin functions to function pointers in the callee of a call.
6528   ExprResult Result;
6529   QualType ResultTy;
6530   if (BuiltinID &&
6531       Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
6532     // Extract the return type from the (builtin) function pointer type.
6533     // FIXME Several builtins still have setType in
6534     // Sema::CheckBuiltinFunctionCall. One should review their definitions in
6535     // Builtins.def to ensure they are correct before removing setType calls.
6536     QualType FnPtrTy = Context.getPointerType(FDecl->getType());
6537     Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get();
6538     ResultTy = FDecl->getCallResultType();
6539   } else {
6540     Result = CallExprUnaryConversions(Fn);
6541     ResultTy = Context.BoolTy;
6542   }
6543   if (Result.isInvalid())
6544     return ExprError();
6545   Fn = Result.get();
6546 
6547   // Check for a valid function type, but only if it is not a builtin which
6548   // requires custom type checking. These will be handled by
6549   // CheckBuiltinFunctionCall below just after creation of the call expression.
6550   const FunctionType *FuncT = nullptr;
6551   if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
6552   retry:
6553     if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
6554       // C99 6.5.2.2p1 - "The expression that denotes the called function shall
6555       // have type pointer to function".
6556       FuncT = PT->getPointeeType()->getAs<FunctionType>();
6557       if (!FuncT)
6558         return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
6559                          << Fn->getType() << Fn->getSourceRange());
6560     } else if (const BlockPointerType *BPT =
6561                    Fn->getType()->getAs<BlockPointerType>()) {
6562       FuncT = BPT->getPointeeType()->castAs<FunctionType>();
6563     } else {
6564       // Handle calls to expressions of unknown-any type.
6565       if (Fn->getType() == Context.UnknownAnyTy) {
6566         ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
6567         if (rewrite.isInvalid())
6568           return ExprError();
6569         Fn = rewrite.get();
6570         goto retry;
6571       }
6572 
6573       return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
6574                        << Fn->getType() << Fn->getSourceRange());
6575     }
6576   }
6577 
6578   // Get the number of parameters in the function prototype, if any.
6579   // We will allocate space for max(Args.size(), NumParams) arguments
6580   // in the call expression.
6581   const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT);
6582   unsigned NumParams = Proto ? Proto->getNumParams() : 0;
6583 
6584   CallExpr *TheCall;
6585   if (Config) {
6586     assert(UsesADL == ADLCallKind::NotADL &&
6587            "CUDAKernelCallExpr should not use ADL");
6588     TheCall =
6589         CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config), Args,
6590                                    ResultTy, VK_RValue, RParenLoc, NumParams);
6591   } else {
6592     TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue,
6593                                RParenLoc, NumParams, UsesADL);
6594   }
6595 
6596   if (!getLangOpts().CPlusPlus) {
6597     // Forget about the nulled arguments since typo correction
6598     // do not handle them well.
6599     TheCall->shrinkNumArgs(Args.size());
6600     // C cannot always handle TypoExpr nodes in builtin calls and direct
6601     // function calls as their argument checking don't necessarily handle
6602     // dependent types properly, so make sure any TypoExprs have been
6603     // dealt with.
6604     ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
6605     if (!Result.isUsable()) return ExprError();
6606     CallExpr *TheOldCall = TheCall;
6607     TheCall = dyn_cast<CallExpr>(Result.get());
6608     bool CorrectedTypos = TheCall != TheOldCall;
6609     if (!TheCall) return Result;
6610     Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
6611 
6612     // A new call expression node was created if some typos were corrected.
6613     // However it may not have been constructed with enough storage. In this
6614     // case, rebuild the node with enough storage. The waste of space is
6615     // immaterial since this only happens when some typos were corrected.
6616     if (CorrectedTypos && Args.size() < NumParams) {
6617       if (Config)
6618         TheCall = CUDAKernelCallExpr::Create(
6619             Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_RValue,
6620             RParenLoc, NumParams);
6621       else
6622         TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue,
6623                                    RParenLoc, NumParams, UsesADL);
6624     }
6625     // We can now handle the nulled arguments for the default arguments.
6626     TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams));
6627   }
6628 
6629   // Bail out early if calling a builtin with custom type checking.
6630   if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
6631     return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
6632 
6633   if (getLangOpts().CUDA) {
6634     if (Config) {
6635       // CUDA: Kernel calls must be to global functions
6636       if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
6637         return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
6638             << FDecl << Fn->getSourceRange());
6639 
6640       // CUDA: Kernel function must have 'void' return type
6641       if (!FuncT->getReturnType()->isVoidType() &&
6642           !FuncT->getReturnType()->getAs<AutoType>() &&
6643           !FuncT->getReturnType()->isInstantiationDependentType())
6644         return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
6645             << Fn->getType() << Fn->getSourceRange());
6646     } else {
6647       // CUDA: Calls to global functions must be configured
6648       if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
6649         return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
6650             << FDecl << Fn->getSourceRange());
6651     }
6652   }
6653 
6654   // Check for a valid return type
6655   if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall,
6656                           FDecl))
6657     return ExprError();
6658 
6659   // We know the result type of the call, set it.
6660   TheCall->setType(FuncT->getCallResultType(Context));
6661   TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
6662 
6663   if (Proto) {
6664     if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
6665                                 IsExecConfig))
6666       return ExprError();
6667   } else {
6668     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
6669 
6670     if (FDecl) {
6671       // Check if we have too few/too many template arguments, based
6672       // on our knowledge of the function definition.
6673       const FunctionDecl *Def = nullptr;
6674       if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
6675         Proto = Def->getType()->getAs<FunctionProtoType>();
6676        if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
6677           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
6678           << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
6679       }
6680 
6681       // If the function we're calling isn't a function prototype, but we have
6682       // a function prototype from a prior declaratiom, use that prototype.
6683       if (!FDecl->hasPrototype())
6684         Proto = FDecl->getType()->getAs<FunctionProtoType>();
6685     }
6686 
6687     // Promote the arguments (C99 6.5.2.2p6).
6688     for (unsigned i = 0, e = Args.size(); i != e; i++) {
6689       Expr *Arg = Args[i];
6690 
6691       if (Proto && i < Proto->getNumParams()) {
6692         InitializedEntity Entity = InitializedEntity::InitializeParameter(
6693             Context, Proto->getParamType(i), Proto->isParamConsumed(i));
6694         ExprResult ArgE =
6695             PerformCopyInitialization(Entity, SourceLocation(), Arg);
6696         if (ArgE.isInvalid())
6697           return true;
6698 
6699         Arg = ArgE.getAs<Expr>();
6700 
6701       } else {
6702         ExprResult ArgE = DefaultArgumentPromotion(Arg);
6703 
6704         if (ArgE.isInvalid())
6705           return true;
6706 
6707         Arg = ArgE.getAs<Expr>();
6708       }
6709 
6710       if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(),
6711                               diag::err_call_incomplete_argument, Arg))
6712         return ExprError();
6713 
6714       TheCall->setArg(i, Arg);
6715     }
6716   }
6717 
6718   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
6719     if (!Method->isStatic())
6720       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
6721         << Fn->getSourceRange());
6722 
6723   // Check for sentinels
6724   if (NDecl)
6725     DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
6726 
6727   // Warn for unions passing across security boundary (CMSE).
6728   if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) {
6729     for (unsigned i = 0, e = Args.size(); i != e; i++) {
6730       if (const auto *RT =
6731               dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) {
6732         if (RT->getDecl()->isOrContainsUnion())
6733           Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union)
6734               << 0 << i;
6735       }
6736     }
6737   }
6738 
6739   // Do special checking on direct calls to functions.
6740   if (FDecl) {
6741     if (CheckFunctionCall(FDecl, TheCall, Proto))
6742       return ExprError();
6743 
6744     checkFortifiedBuiltinMemoryFunction(FDecl, TheCall);
6745 
6746     if (BuiltinID)
6747       return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
6748   } else if (NDecl) {
6749     if (CheckPointerCall(NDecl, TheCall, Proto))
6750       return ExprError();
6751   } else {
6752     if (CheckOtherCall(TheCall, Proto))
6753       return ExprError();
6754   }
6755 
6756   return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl);
6757 }
6758 
6759 ExprResult
6760 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
6761                            SourceLocation RParenLoc, Expr *InitExpr) {
6762   assert(Ty && "ActOnCompoundLiteral(): missing type");
6763   assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
6764 
6765   TypeSourceInfo *TInfo;
6766   QualType literalType = GetTypeFromParser(Ty, &TInfo);
6767   if (!TInfo)
6768     TInfo = Context.getTrivialTypeSourceInfo(literalType);
6769 
6770   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
6771 }
6772 
6773 ExprResult
6774 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
6775                                SourceLocation RParenLoc, Expr *LiteralExpr) {
6776   QualType literalType = TInfo->getType();
6777 
6778   if (literalType->isArrayType()) {
6779     if (RequireCompleteSizedType(
6780             LParenLoc, Context.getBaseElementType(literalType),
6781             diag::err_array_incomplete_or_sizeless_type,
6782             SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
6783       return ExprError();
6784     if (literalType->isVariableArrayType())
6785       return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
6786         << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
6787   } else if (!literalType->isDependentType() &&
6788              RequireCompleteType(LParenLoc, literalType,
6789                diag::err_typecheck_decl_incomplete_type,
6790                SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
6791     return ExprError();
6792 
6793   InitializedEntity Entity
6794     = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
6795   InitializationKind Kind
6796     = InitializationKind::CreateCStyleCast(LParenLoc,
6797                                            SourceRange(LParenLoc, RParenLoc),
6798                                            /*InitList=*/true);
6799   InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
6800   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
6801                                       &literalType);
6802   if (Result.isInvalid())
6803     return ExprError();
6804   LiteralExpr = Result.get();
6805 
6806   bool isFileScope = !CurContext->isFunctionOrMethod();
6807 
6808   // In C, compound literals are l-values for some reason.
6809   // For GCC compatibility, in C++, file-scope array compound literals with
6810   // constant initializers are also l-values, and compound literals are
6811   // otherwise prvalues.
6812   //
6813   // (GCC also treats C++ list-initialized file-scope array prvalues with
6814   // constant initializers as l-values, but that's non-conforming, so we don't
6815   // follow it there.)
6816   //
6817   // FIXME: It would be better to handle the lvalue cases as materializing and
6818   // lifetime-extending a temporary object, but our materialized temporaries
6819   // representation only supports lifetime extension from a variable, not "out
6820   // of thin air".
6821   // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
6822   // is bound to the result of applying array-to-pointer decay to the compound
6823   // literal.
6824   // FIXME: GCC supports compound literals of reference type, which should
6825   // obviously have a value kind derived from the kind of reference involved.
6826   ExprValueKind VK =
6827       (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
6828           ? VK_RValue
6829           : VK_LValue;
6830 
6831   if (isFileScope)
6832     if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr))
6833       for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {
6834         Expr *Init = ILE->getInit(i);
6835         ILE->setInit(i, ConstantExpr::Create(Context, Init));
6836       }
6837 
6838   auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
6839                                               VK, LiteralExpr, isFileScope);
6840   if (isFileScope) {
6841     if (!LiteralExpr->isTypeDependent() &&
6842         !LiteralExpr->isValueDependent() &&
6843         !literalType->isDependentType()) // C99 6.5.2.5p3
6844       if (CheckForConstantInitializer(LiteralExpr, literalType))
6845         return ExprError();
6846   } else if (literalType.getAddressSpace() != LangAS::opencl_private &&
6847              literalType.getAddressSpace() != LangAS::Default) {
6848     // Embedded-C extensions to C99 6.5.2.5:
6849     //   "If the compound literal occurs inside the body of a function, the
6850     //   type name shall not be qualified by an address-space qualifier."
6851     Diag(LParenLoc, diag::err_compound_literal_with_address_space)
6852       << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
6853     return ExprError();
6854   }
6855 
6856   if (!isFileScope && !getLangOpts().CPlusPlus) {
6857     // Compound literals that have automatic storage duration are destroyed at
6858     // the end of the scope in C; in C++, they're just temporaries.
6859 
6860     // Emit diagnostics if it is or contains a C union type that is non-trivial
6861     // to destruct.
6862     if (E->getType().hasNonTrivialToPrimitiveDestructCUnion())
6863       checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
6864                             NTCUC_CompoundLiteral, NTCUK_Destruct);
6865 
6866     // Diagnose jumps that enter or exit the lifetime of the compound literal.
6867     if (literalType.isDestructedType()) {
6868       Cleanup.setExprNeedsCleanups(true);
6869       ExprCleanupObjects.push_back(E);
6870       getCurFunction()->setHasBranchProtectedScope();
6871     }
6872   }
6873 
6874   if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
6875       E->getType().hasNonTrivialToPrimitiveCopyCUnion())
6876     checkNonTrivialCUnionInInitializer(E->getInitializer(),
6877                                        E->getInitializer()->getExprLoc());
6878 
6879   return MaybeBindToTemporary(E);
6880 }
6881 
6882 ExprResult
6883 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
6884                     SourceLocation RBraceLoc) {
6885   // Only produce each kind of designated initialization diagnostic once.
6886   SourceLocation FirstDesignator;
6887   bool DiagnosedArrayDesignator = false;
6888   bool DiagnosedNestedDesignator = false;
6889   bool DiagnosedMixedDesignator = false;
6890 
6891   // Check that any designated initializers are syntactically valid in the
6892   // current language mode.
6893   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
6894     if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) {
6895       if (FirstDesignator.isInvalid())
6896         FirstDesignator = DIE->getBeginLoc();
6897 
6898       if (!getLangOpts().CPlusPlus)
6899         break;
6900 
6901       if (!DiagnosedNestedDesignator && DIE->size() > 1) {
6902         DiagnosedNestedDesignator = true;
6903         Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested)
6904           << DIE->getDesignatorsSourceRange();
6905       }
6906 
6907       for (auto &Desig : DIE->designators()) {
6908         if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) {
6909           DiagnosedArrayDesignator = true;
6910           Diag(Desig.getBeginLoc(), diag::ext_designated_init_array)
6911             << Desig.getSourceRange();
6912         }
6913       }
6914 
6915       if (!DiagnosedMixedDesignator &&
6916           !isa<DesignatedInitExpr>(InitArgList[0])) {
6917         DiagnosedMixedDesignator = true;
6918         Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
6919           << DIE->getSourceRange();
6920         Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed)
6921           << InitArgList[0]->getSourceRange();
6922       }
6923     } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator &&
6924                isa<DesignatedInitExpr>(InitArgList[0])) {
6925       DiagnosedMixedDesignator = true;
6926       auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]);
6927       Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
6928         << DIE->getSourceRange();
6929       Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed)
6930         << InitArgList[I]->getSourceRange();
6931     }
6932   }
6933 
6934   if (FirstDesignator.isValid()) {
6935     // Only diagnose designated initiaization as a C++20 extension if we didn't
6936     // already diagnose use of (non-C++20) C99 designator syntax.
6937     if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator &&
6938         !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) {
6939       Diag(FirstDesignator, getLangOpts().CPlusPlus20
6940                                 ? diag::warn_cxx17_compat_designated_init
6941                                 : diag::ext_cxx_designated_init);
6942     } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) {
6943       Diag(FirstDesignator, diag::ext_designated_init);
6944     }
6945   }
6946 
6947   return BuildInitList(LBraceLoc, InitArgList, RBraceLoc);
6948 }
6949 
6950 ExprResult
6951 Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
6952                     SourceLocation RBraceLoc) {
6953   // Semantic analysis for initializers is done by ActOnDeclarator() and
6954   // CheckInitializer() - it requires knowledge of the object being initialized.
6955 
6956   // Immediately handle non-overload placeholders.  Overloads can be
6957   // resolved contextually, but everything else here can't.
6958   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
6959     if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
6960       ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
6961 
6962       // Ignore failures; dropping the entire initializer list because
6963       // of one failure would be terrible for indexing/etc.
6964       if (result.isInvalid()) continue;
6965 
6966       InitArgList[I] = result.get();
6967     }
6968   }
6969 
6970   InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
6971                                                RBraceLoc);
6972   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
6973   return E;
6974 }
6975 
6976 /// Do an explicit extend of the given block pointer if we're in ARC.
6977 void Sema::maybeExtendBlockObject(ExprResult &E) {
6978   assert(E.get()->getType()->isBlockPointerType());
6979   assert(E.get()->isRValue());
6980 
6981   // Only do this in an r-value context.
6982   if (!getLangOpts().ObjCAutoRefCount) return;
6983 
6984   E = ImplicitCastExpr::Create(Context, E.get()->getType(),
6985                                CK_ARCExtendBlockObject, E.get(),
6986                                /*base path*/ nullptr, VK_RValue);
6987   Cleanup.setExprNeedsCleanups(true);
6988 }
6989 
6990 /// Prepare a conversion of the given expression to an ObjC object
6991 /// pointer type.
6992 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
6993   QualType type = E.get()->getType();
6994   if (type->isObjCObjectPointerType()) {
6995     return CK_BitCast;
6996   } else if (type->isBlockPointerType()) {
6997     maybeExtendBlockObject(E);
6998     return CK_BlockPointerToObjCPointerCast;
6999   } else {
7000     assert(type->isPointerType());
7001     return CK_CPointerToObjCPointerCast;
7002   }
7003 }
7004 
7005 /// Prepares for a scalar cast, performing all the necessary stages
7006 /// except the final cast and returning the kind required.
7007 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
7008   // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
7009   // Also, callers should have filtered out the invalid cases with
7010   // pointers.  Everything else should be possible.
7011 
7012   QualType SrcTy = Src.get()->getType();
7013   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
7014     return CK_NoOp;
7015 
7016   switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
7017   case Type::STK_MemberPointer:
7018     llvm_unreachable("member pointer type in C");
7019 
7020   case Type::STK_CPointer:
7021   case Type::STK_BlockPointer:
7022   case Type::STK_ObjCObjectPointer:
7023     switch (DestTy->getScalarTypeKind()) {
7024     case Type::STK_CPointer: {
7025       LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
7026       LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
7027       if (SrcAS != DestAS)
7028         return CK_AddressSpaceConversion;
7029       if (Context.hasCvrSimilarType(SrcTy, DestTy))
7030         return CK_NoOp;
7031       return CK_BitCast;
7032     }
7033     case Type::STK_BlockPointer:
7034       return (SrcKind == Type::STK_BlockPointer
7035                 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
7036     case Type::STK_ObjCObjectPointer:
7037       if (SrcKind == Type::STK_ObjCObjectPointer)
7038         return CK_BitCast;
7039       if (SrcKind == Type::STK_CPointer)
7040         return CK_CPointerToObjCPointerCast;
7041       maybeExtendBlockObject(Src);
7042       return CK_BlockPointerToObjCPointerCast;
7043     case Type::STK_Bool:
7044       return CK_PointerToBoolean;
7045     case Type::STK_Integral:
7046       return CK_PointerToIntegral;
7047     case Type::STK_Floating:
7048     case Type::STK_FloatingComplex:
7049     case Type::STK_IntegralComplex:
7050     case Type::STK_MemberPointer:
7051     case Type::STK_FixedPoint:
7052       llvm_unreachable("illegal cast from pointer");
7053     }
7054     llvm_unreachable("Should have returned before this");
7055 
7056   case Type::STK_FixedPoint:
7057     switch (DestTy->getScalarTypeKind()) {
7058     case Type::STK_FixedPoint:
7059       return CK_FixedPointCast;
7060     case Type::STK_Bool:
7061       return CK_FixedPointToBoolean;
7062     case Type::STK_Integral:
7063       return CK_FixedPointToIntegral;
7064     case Type::STK_Floating:
7065     case Type::STK_IntegralComplex:
7066     case Type::STK_FloatingComplex:
7067       Diag(Src.get()->getExprLoc(),
7068            diag::err_unimplemented_conversion_with_fixed_point_type)
7069           << DestTy;
7070       return CK_IntegralCast;
7071     case Type::STK_CPointer:
7072     case Type::STK_ObjCObjectPointer:
7073     case Type::STK_BlockPointer:
7074     case Type::STK_MemberPointer:
7075       llvm_unreachable("illegal cast to pointer type");
7076     }
7077     llvm_unreachable("Should have returned before this");
7078 
7079   case Type::STK_Bool: // casting from bool is like casting from an integer
7080   case Type::STK_Integral:
7081     switch (DestTy->getScalarTypeKind()) {
7082     case Type::STK_CPointer:
7083     case Type::STK_ObjCObjectPointer:
7084     case Type::STK_BlockPointer:
7085       if (Src.get()->isNullPointerConstant(Context,
7086                                            Expr::NPC_ValueDependentIsNull))
7087         return CK_NullToPointer;
7088       return CK_IntegralToPointer;
7089     case Type::STK_Bool:
7090       return CK_IntegralToBoolean;
7091     case Type::STK_Integral:
7092       return CK_IntegralCast;
7093     case Type::STK_Floating:
7094       return CK_IntegralToFloating;
7095     case Type::STK_IntegralComplex:
7096       Src = ImpCastExprToType(Src.get(),
7097                       DestTy->castAs<ComplexType>()->getElementType(),
7098                       CK_IntegralCast);
7099       return CK_IntegralRealToComplex;
7100     case Type::STK_FloatingComplex:
7101       Src = ImpCastExprToType(Src.get(),
7102                       DestTy->castAs<ComplexType>()->getElementType(),
7103                       CK_IntegralToFloating);
7104       return CK_FloatingRealToComplex;
7105     case Type::STK_MemberPointer:
7106       llvm_unreachable("member pointer type in C");
7107     case Type::STK_FixedPoint:
7108       return CK_IntegralToFixedPoint;
7109     }
7110     llvm_unreachable("Should have returned before this");
7111 
7112   case Type::STK_Floating:
7113     switch (DestTy->getScalarTypeKind()) {
7114     case Type::STK_Floating:
7115       return CK_FloatingCast;
7116     case Type::STK_Bool:
7117       return CK_FloatingToBoolean;
7118     case Type::STK_Integral:
7119       return CK_FloatingToIntegral;
7120     case Type::STK_FloatingComplex:
7121       Src = ImpCastExprToType(Src.get(),
7122                               DestTy->castAs<ComplexType>()->getElementType(),
7123                               CK_FloatingCast);
7124       return CK_FloatingRealToComplex;
7125     case Type::STK_IntegralComplex:
7126       Src = ImpCastExprToType(Src.get(),
7127                               DestTy->castAs<ComplexType>()->getElementType(),
7128                               CK_FloatingToIntegral);
7129       return CK_IntegralRealToComplex;
7130     case Type::STK_CPointer:
7131     case Type::STK_ObjCObjectPointer:
7132     case Type::STK_BlockPointer:
7133       llvm_unreachable("valid float->pointer cast?");
7134     case Type::STK_MemberPointer:
7135       llvm_unreachable("member pointer type in C");
7136     case Type::STK_FixedPoint:
7137       Diag(Src.get()->getExprLoc(),
7138            diag::err_unimplemented_conversion_with_fixed_point_type)
7139           << SrcTy;
7140       return CK_IntegralCast;
7141     }
7142     llvm_unreachable("Should have returned before this");
7143 
7144   case Type::STK_FloatingComplex:
7145     switch (DestTy->getScalarTypeKind()) {
7146     case Type::STK_FloatingComplex:
7147       return CK_FloatingComplexCast;
7148     case Type::STK_IntegralComplex:
7149       return CK_FloatingComplexToIntegralComplex;
7150     case Type::STK_Floating: {
7151       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7152       if (Context.hasSameType(ET, DestTy))
7153         return CK_FloatingComplexToReal;
7154       Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
7155       return CK_FloatingCast;
7156     }
7157     case Type::STK_Bool:
7158       return CK_FloatingComplexToBoolean;
7159     case Type::STK_Integral:
7160       Src = ImpCastExprToType(Src.get(),
7161                               SrcTy->castAs<ComplexType>()->getElementType(),
7162                               CK_FloatingComplexToReal);
7163       return CK_FloatingToIntegral;
7164     case Type::STK_CPointer:
7165     case Type::STK_ObjCObjectPointer:
7166     case Type::STK_BlockPointer:
7167       llvm_unreachable("valid complex float->pointer cast?");
7168     case Type::STK_MemberPointer:
7169       llvm_unreachable("member pointer type in C");
7170     case Type::STK_FixedPoint:
7171       Diag(Src.get()->getExprLoc(),
7172            diag::err_unimplemented_conversion_with_fixed_point_type)
7173           << SrcTy;
7174       return CK_IntegralCast;
7175     }
7176     llvm_unreachable("Should have returned before this");
7177 
7178   case Type::STK_IntegralComplex:
7179     switch (DestTy->getScalarTypeKind()) {
7180     case Type::STK_FloatingComplex:
7181       return CK_IntegralComplexToFloatingComplex;
7182     case Type::STK_IntegralComplex:
7183       return CK_IntegralComplexCast;
7184     case Type::STK_Integral: {
7185       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7186       if (Context.hasSameType(ET, DestTy))
7187         return CK_IntegralComplexToReal;
7188       Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
7189       return CK_IntegralCast;
7190     }
7191     case Type::STK_Bool:
7192       return CK_IntegralComplexToBoolean;
7193     case Type::STK_Floating:
7194       Src = ImpCastExprToType(Src.get(),
7195                               SrcTy->castAs<ComplexType>()->getElementType(),
7196                               CK_IntegralComplexToReal);
7197       return CK_IntegralToFloating;
7198     case Type::STK_CPointer:
7199     case Type::STK_ObjCObjectPointer:
7200     case Type::STK_BlockPointer:
7201       llvm_unreachable("valid complex int->pointer cast?");
7202     case Type::STK_MemberPointer:
7203       llvm_unreachable("member pointer type in C");
7204     case Type::STK_FixedPoint:
7205       Diag(Src.get()->getExprLoc(),
7206            diag::err_unimplemented_conversion_with_fixed_point_type)
7207           << SrcTy;
7208       return CK_IntegralCast;
7209     }
7210     llvm_unreachable("Should have returned before this");
7211   }
7212 
7213   llvm_unreachable("Unhandled scalar cast");
7214 }
7215 
7216 static bool breakDownVectorType(QualType type, uint64_t &len,
7217                                 QualType &eltType) {
7218   // Vectors are simple.
7219   if (const VectorType *vecType = type->getAs<VectorType>()) {
7220     len = vecType->getNumElements();
7221     eltType = vecType->getElementType();
7222     assert(eltType->isScalarType());
7223     return true;
7224   }
7225 
7226   // We allow lax conversion to and from non-vector types, but only if
7227   // they're real types (i.e. non-complex, non-pointer scalar types).
7228   if (!type->isRealType()) return false;
7229 
7230   len = 1;
7231   eltType = type;
7232   return true;
7233 }
7234 
7235 /// Are the two types lax-compatible vector types?  That is, given
7236 /// that one of them is a vector, do they have equal storage sizes,
7237 /// where the storage size is the number of elements times the element
7238 /// size?
7239 ///
7240 /// This will also return false if either of the types is neither a
7241 /// vector nor a real type.
7242 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
7243   assert(destTy->isVectorType() || srcTy->isVectorType());
7244 
7245   // Disallow lax conversions between scalars and ExtVectors (these
7246   // conversions are allowed for other vector types because common headers
7247   // depend on them).  Most scalar OP ExtVector cases are handled by the
7248   // splat path anyway, which does what we want (convert, not bitcast).
7249   // What this rules out for ExtVectors is crazy things like char4*float.
7250   if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
7251   if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
7252 
7253   uint64_t srcLen, destLen;
7254   QualType srcEltTy, destEltTy;
7255   if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false;
7256   if (!breakDownVectorType(destTy, destLen, destEltTy)) return false;
7257 
7258   // ASTContext::getTypeSize will return the size rounded up to a
7259   // power of 2, so instead of using that, we need to use the raw
7260   // element size multiplied by the element count.
7261   uint64_t srcEltSize = Context.getTypeSize(srcEltTy);
7262   uint64_t destEltSize = Context.getTypeSize(destEltTy);
7263 
7264   return (srcLen * srcEltSize == destLen * destEltSize);
7265 }
7266 
7267 /// Is this a legal conversion between two types, one of which is
7268 /// known to be a vector type?
7269 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
7270   assert(destTy->isVectorType() || srcTy->isVectorType());
7271 
7272   switch (Context.getLangOpts().getLaxVectorConversions()) {
7273   case LangOptions::LaxVectorConversionKind::None:
7274     return false;
7275 
7276   case LangOptions::LaxVectorConversionKind::Integer:
7277     if (!srcTy->isIntegralOrEnumerationType()) {
7278       auto *Vec = srcTy->getAs<VectorType>();
7279       if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7280         return false;
7281     }
7282     if (!destTy->isIntegralOrEnumerationType()) {
7283       auto *Vec = destTy->getAs<VectorType>();
7284       if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7285         return false;
7286     }
7287     // OK, integer (vector) -> integer (vector) bitcast.
7288     break;
7289 
7290     case LangOptions::LaxVectorConversionKind::All:
7291     break;
7292   }
7293 
7294   return areLaxCompatibleVectorTypes(srcTy, destTy);
7295 }
7296 
7297 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
7298                            CastKind &Kind) {
7299   assert(VectorTy->isVectorType() && "Not a vector type!");
7300 
7301   if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
7302     if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
7303       return Diag(R.getBegin(),
7304                   Ty->isVectorType() ?
7305                   diag::err_invalid_conversion_between_vectors :
7306                   diag::err_invalid_conversion_between_vector_and_integer)
7307         << VectorTy << Ty << R;
7308   } else
7309     return Diag(R.getBegin(),
7310                 diag::err_invalid_conversion_between_vector_and_scalar)
7311       << VectorTy << Ty << R;
7312 
7313   Kind = CK_BitCast;
7314   return false;
7315 }
7316 
7317 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
7318   QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
7319 
7320   if (DestElemTy == SplattedExpr->getType())
7321     return SplattedExpr;
7322 
7323   assert(DestElemTy->isFloatingType() ||
7324          DestElemTy->isIntegralOrEnumerationType());
7325 
7326   CastKind CK;
7327   if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
7328     // OpenCL requires that we convert `true` boolean expressions to -1, but
7329     // only when splatting vectors.
7330     if (DestElemTy->isFloatingType()) {
7331       // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
7332       // in two steps: boolean to signed integral, then to floating.
7333       ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
7334                                                  CK_BooleanToSignedIntegral);
7335       SplattedExpr = CastExprRes.get();
7336       CK = CK_IntegralToFloating;
7337     } else {
7338       CK = CK_BooleanToSignedIntegral;
7339     }
7340   } else {
7341     ExprResult CastExprRes = SplattedExpr;
7342     CK = PrepareScalarCast(CastExprRes, DestElemTy);
7343     if (CastExprRes.isInvalid())
7344       return ExprError();
7345     SplattedExpr = CastExprRes.get();
7346   }
7347   return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
7348 }
7349 
7350 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
7351                                     Expr *CastExpr, CastKind &Kind) {
7352   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
7353 
7354   QualType SrcTy = CastExpr->getType();
7355 
7356   // If SrcTy is a VectorType, the total size must match to explicitly cast to
7357   // an ExtVectorType.
7358   // In OpenCL, casts between vectors of different types are not allowed.
7359   // (See OpenCL 6.2).
7360   if (SrcTy->isVectorType()) {
7361     if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
7362         (getLangOpts().OpenCL &&
7363          !Context.hasSameUnqualifiedType(DestTy, SrcTy))) {
7364       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
7365         << DestTy << SrcTy << R;
7366       return ExprError();
7367     }
7368     Kind = CK_BitCast;
7369     return CastExpr;
7370   }
7371 
7372   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
7373   // conversion will take place first from scalar to elt type, and then
7374   // splat from elt type to vector.
7375   if (SrcTy->isPointerType())
7376     return Diag(R.getBegin(),
7377                 diag::err_invalid_conversion_between_vector_and_scalar)
7378       << DestTy << SrcTy << R;
7379 
7380   Kind = CK_VectorSplat;
7381   return prepareVectorSplat(DestTy, CastExpr);
7382 }
7383 
7384 ExprResult
7385 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
7386                     Declarator &D, ParsedType &Ty,
7387                     SourceLocation RParenLoc, Expr *CastExpr) {
7388   assert(!D.isInvalidType() && (CastExpr != nullptr) &&
7389          "ActOnCastExpr(): missing type or expr");
7390 
7391   TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
7392   if (D.isInvalidType())
7393     return ExprError();
7394 
7395   if (getLangOpts().CPlusPlus) {
7396     // Check that there are no default arguments (C++ only).
7397     CheckExtraCXXDefaultArguments(D);
7398   } else {
7399     // Make sure any TypoExprs have been dealt with.
7400     ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
7401     if (!Res.isUsable())
7402       return ExprError();
7403     CastExpr = Res.get();
7404   }
7405 
7406   checkUnusedDeclAttributes(D);
7407 
7408   QualType castType = castTInfo->getType();
7409   Ty = CreateParsedType(castType, castTInfo);
7410 
7411   bool isVectorLiteral = false;
7412 
7413   // Check for an altivec or OpenCL literal,
7414   // i.e. all the elements are integer constants.
7415   ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
7416   ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
7417   if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
7418        && castType->isVectorType() && (PE || PLE)) {
7419     if (PLE && PLE->getNumExprs() == 0) {
7420       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
7421       return ExprError();
7422     }
7423     if (PE || PLE->getNumExprs() == 1) {
7424       Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
7425       if (!E->getType()->isVectorType())
7426         isVectorLiteral = true;
7427     }
7428     else
7429       isVectorLiteral = true;
7430   }
7431 
7432   // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
7433   // then handle it as such.
7434   if (isVectorLiteral)
7435     return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
7436 
7437   // If the Expr being casted is a ParenListExpr, handle it specially.
7438   // This is not an AltiVec-style cast, so turn the ParenListExpr into a
7439   // sequence of BinOp comma operators.
7440   if (isa<ParenListExpr>(CastExpr)) {
7441     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
7442     if (Result.isInvalid()) return ExprError();
7443     CastExpr = Result.get();
7444   }
7445 
7446   if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
7447       !getSourceManager().isInSystemMacro(LParenLoc))
7448     Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
7449 
7450   CheckTollFreeBridgeCast(castType, CastExpr);
7451 
7452   CheckObjCBridgeRelatedCast(castType, CastExpr);
7453 
7454   DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
7455 
7456   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
7457 }
7458 
7459 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
7460                                     SourceLocation RParenLoc, Expr *E,
7461                                     TypeSourceInfo *TInfo) {
7462   assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
7463          "Expected paren or paren list expression");
7464 
7465   Expr **exprs;
7466   unsigned numExprs;
7467   Expr *subExpr;
7468   SourceLocation LiteralLParenLoc, LiteralRParenLoc;
7469   if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
7470     LiteralLParenLoc = PE->getLParenLoc();
7471     LiteralRParenLoc = PE->getRParenLoc();
7472     exprs = PE->getExprs();
7473     numExprs = PE->getNumExprs();
7474   } else { // isa<ParenExpr> by assertion at function entrance
7475     LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
7476     LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
7477     subExpr = cast<ParenExpr>(E)->getSubExpr();
7478     exprs = &subExpr;
7479     numExprs = 1;
7480   }
7481 
7482   QualType Ty = TInfo->getType();
7483   assert(Ty->isVectorType() && "Expected vector type");
7484 
7485   SmallVector<Expr *, 8> initExprs;
7486   const VectorType *VTy = Ty->castAs<VectorType>();
7487   unsigned numElems = VTy->getNumElements();
7488 
7489   // '(...)' form of vector initialization in AltiVec: the number of
7490   // initializers must be one or must match the size of the vector.
7491   // If a single value is specified in the initializer then it will be
7492   // replicated to all the components of the vector
7493   if (VTy->getVectorKind() == VectorType::AltiVecVector) {
7494     // The number of initializers must be one or must match the size of the
7495     // vector. If a single value is specified in the initializer then it will
7496     // be replicated to all the components of the vector
7497     if (numExprs == 1) {
7498       QualType ElemTy = VTy->getElementType();
7499       ExprResult Literal = DefaultLvalueConversion(exprs[0]);
7500       if (Literal.isInvalid())
7501         return ExprError();
7502       Literal = ImpCastExprToType(Literal.get(), ElemTy,
7503                                   PrepareScalarCast(Literal, ElemTy));
7504       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
7505     }
7506     else if (numExprs < numElems) {
7507       Diag(E->getExprLoc(),
7508            diag::err_incorrect_number_of_vector_initializers);
7509       return ExprError();
7510     }
7511     else
7512       initExprs.append(exprs, exprs + numExprs);
7513   }
7514   else {
7515     // For OpenCL, when the number of initializers is a single value,
7516     // it will be replicated to all components of the vector.
7517     if (getLangOpts().OpenCL &&
7518         VTy->getVectorKind() == VectorType::GenericVector &&
7519         numExprs == 1) {
7520         QualType ElemTy = VTy->getElementType();
7521         ExprResult Literal = DefaultLvalueConversion(exprs[0]);
7522         if (Literal.isInvalid())
7523           return ExprError();
7524         Literal = ImpCastExprToType(Literal.get(), ElemTy,
7525                                     PrepareScalarCast(Literal, ElemTy));
7526         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
7527     }
7528 
7529     initExprs.append(exprs, exprs + numExprs);
7530   }
7531   // FIXME: This means that pretty-printing the final AST will produce curly
7532   // braces instead of the original commas.
7533   InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
7534                                                    initExprs, LiteralRParenLoc);
7535   initE->setType(Ty);
7536   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
7537 }
7538 
7539 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
7540 /// the ParenListExpr into a sequence of comma binary operators.
7541 ExprResult
7542 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
7543   ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
7544   if (!E)
7545     return OrigExpr;
7546 
7547   ExprResult Result(E->getExpr(0));
7548 
7549   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
7550     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
7551                         E->getExpr(i));
7552 
7553   if (Result.isInvalid()) return ExprError();
7554 
7555   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
7556 }
7557 
7558 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
7559                                     SourceLocation R,
7560                                     MultiExprArg Val) {
7561   return ParenListExpr::Create(Context, L, Val, R);
7562 }
7563 
7564 /// Emit a specialized diagnostic when one expression is a null pointer
7565 /// constant and the other is not a pointer.  Returns true if a diagnostic is
7566 /// emitted.
7567 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
7568                                       SourceLocation QuestionLoc) {
7569   Expr *NullExpr = LHSExpr;
7570   Expr *NonPointerExpr = RHSExpr;
7571   Expr::NullPointerConstantKind NullKind =
7572       NullExpr->isNullPointerConstant(Context,
7573                                       Expr::NPC_ValueDependentIsNotNull);
7574 
7575   if (NullKind == Expr::NPCK_NotNull) {
7576     NullExpr = RHSExpr;
7577     NonPointerExpr = LHSExpr;
7578     NullKind =
7579         NullExpr->isNullPointerConstant(Context,
7580                                         Expr::NPC_ValueDependentIsNotNull);
7581   }
7582 
7583   if (NullKind == Expr::NPCK_NotNull)
7584     return false;
7585 
7586   if (NullKind == Expr::NPCK_ZeroExpression)
7587     return false;
7588 
7589   if (NullKind == Expr::NPCK_ZeroLiteral) {
7590     // In this case, check to make sure that we got here from a "NULL"
7591     // string in the source code.
7592     NullExpr = NullExpr->IgnoreParenImpCasts();
7593     SourceLocation loc = NullExpr->getExprLoc();
7594     if (!findMacroSpelling(loc, "NULL"))
7595       return false;
7596   }
7597 
7598   int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
7599   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
7600       << NonPointerExpr->getType() << DiagType
7601       << NonPointerExpr->getSourceRange();
7602   return true;
7603 }
7604 
7605 /// Return false if the condition expression is valid, true otherwise.
7606 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
7607   QualType CondTy = Cond->getType();
7608 
7609   // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
7610   if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
7611     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
7612       << CondTy << Cond->getSourceRange();
7613     return true;
7614   }
7615 
7616   // C99 6.5.15p2
7617   if (CondTy->isScalarType()) return false;
7618 
7619   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
7620     << CondTy << Cond->getSourceRange();
7621   return true;
7622 }
7623 
7624 /// Handle when one or both operands are void type.
7625 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
7626                                          ExprResult &RHS) {
7627     Expr *LHSExpr = LHS.get();
7628     Expr *RHSExpr = RHS.get();
7629 
7630     if (!LHSExpr->getType()->isVoidType())
7631       S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
7632           << RHSExpr->getSourceRange();
7633     if (!RHSExpr->getType()->isVoidType())
7634       S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
7635           << LHSExpr->getSourceRange();
7636     LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
7637     RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
7638     return S.Context.VoidTy;
7639 }
7640 
7641 /// Return false if the NullExpr can be promoted to PointerTy,
7642 /// true otherwise.
7643 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
7644                                         QualType PointerTy) {
7645   if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
7646       !NullExpr.get()->isNullPointerConstant(S.Context,
7647                                             Expr::NPC_ValueDependentIsNull))
7648     return true;
7649 
7650   NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
7651   return false;
7652 }
7653 
7654 /// Checks compatibility between two pointers and return the resulting
7655 /// type.
7656 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
7657                                                      ExprResult &RHS,
7658                                                      SourceLocation Loc) {
7659   QualType LHSTy = LHS.get()->getType();
7660   QualType RHSTy = RHS.get()->getType();
7661 
7662   if (S.Context.hasSameType(LHSTy, RHSTy)) {
7663     // Two identical pointers types are always compatible.
7664     return LHSTy;
7665   }
7666 
7667   QualType lhptee, rhptee;
7668 
7669   // Get the pointee types.
7670   bool IsBlockPointer = false;
7671   if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
7672     lhptee = LHSBTy->getPointeeType();
7673     rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
7674     IsBlockPointer = true;
7675   } else {
7676     lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
7677     rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
7678   }
7679 
7680   // C99 6.5.15p6: If both operands are pointers to compatible types or to
7681   // differently qualified versions of compatible types, the result type is
7682   // a pointer to an appropriately qualified version of the composite
7683   // type.
7684 
7685   // Only CVR-qualifiers exist in the standard, and the differently-qualified
7686   // clause doesn't make sense for our extensions. E.g. address space 2 should
7687   // be incompatible with address space 3: they may live on different devices or
7688   // anything.
7689   Qualifiers lhQual = lhptee.getQualifiers();
7690   Qualifiers rhQual = rhptee.getQualifiers();
7691 
7692   LangAS ResultAddrSpace = LangAS::Default;
7693   LangAS LAddrSpace = lhQual.getAddressSpace();
7694   LangAS RAddrSpace = rhQual.getAddressSpace();
7695 
7696   // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
7697   // spaces is disallowed.
7698   if (lhQual.isAddressSpaceSupersetOf(rhQual))
7699     ResultAddrSpace = LAddrSpace;
7700   else if (rhQual.isAddressSpaceSupersetOf(lhQual))
7701     ResultAddrSpace = RAddrSpace;
7702   else {
7703     S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
7704         << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
7705         << RHS.get()->getSourceRange();
7706     return QualType();
7707   }
7708 
7709   unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
7710   auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
7711   lhQual.removeCVRQualifiers();
7712   rhQual.removeCVRQualifiers();
7713 
7714   // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
7715   // (C99 6.7.3) for address spaces. We assume that the check should behave in
7716   // the same manner as it's defined for CVR qualifiers, so for OpenCL two
7717   // qual types are compatible iff
7718   //  * corresponded types are compatible
7719   //  * CVR qualifiers are equal
7720   //  * address spaces are equal
7721   // Thus for conditional operator we merge CVR and address space unqualified
7722   // pointees and if there is a composite type we return a pointer to it with
7723   // merged qualifiers.
7724   LHSCastKind =
7725       LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
7726   RHSCastKind =
7727       RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
7728   lhQual.removeAddressSpace();
7729   rhQual.removeAddressSpace();
7730 
7731   lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
7732   rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
7733 
7734   QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
7735 
7736   if (CompositeTy.isNull()) {
7737     // In this situation, we assume void* type. No especially good
7738     // reason, but this is what gcc does, and we do have to pick
7739     // to get a consistent AST.
7740     QualType incompatTy;
7741     incompatTy = S.Context.getPointerType(
7742         S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
7743     LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
7744     RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
7745 
7746     // FIXME: For OpenCL the warning emission and cast to void* leaves a room
7747     // for casts between types with incompatible address space qualifiers.
7748     // For the following code the compiler produces casts between global and
7749     // local address spaces of the corresponded innermost pointees:
7750     // local int *global *a;
7751     // global int *global *b;
7752     // a = (0 ? a : b); // see C99 6.5.16.1.p1.
7753     S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
7754         << LHSTy << RHSTy << LHS.get()->getSourceRange()
7755         << RHS.get()->getSourceRange();
7756 
7757     return incompatTy;
7758   }
7759 
7760   // The pointer types are compatible.
7761   // In case of OpenCL ResultTy should have the address space qualifier
7762   // which is a superset of address spaces of both the 2nd and the 3rd
7763   // operands of the conditional operator.
7764   QualType ResultTy = [&, ResultAddrSpace]() {
7765     if (S.getLangOpts().OpenCL) {
7766       Qualifiers CompositeQuals = CompositeTy.getQualifiers();
7767       CompositeQuals.setAddressSpace(ResultAddrSpace);
7768       return S.Context
7769           .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
7770           .withCVRQualifiers(MergedCVRQual);
7771     }
7772     return CompositeTy.withCVRQualifiers(MergedCVRQual);
7773   }();
7774   if (IsBlockPointer)
7775     ResultTy = S.Context.getBlockPointerType(ResultTy);
7776   else
7777     ResultTy = S.Context.getPointerType(ResultTy);
7778 
7779   LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
7780   RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
7781   return ResultTy;
7782 }
7783 
7784 /// Return the resulting type when the operands are both block pointers.
7785 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
7786                                                           ExprResult &LHS,
7787                                                           ExprResult &RHS,
7788                                                           SourceLocation Loc) {
7789   QualType LHSTy = LHS.get()->getType();
7790   QualType RHSTy = RHS.get()->getType();
7791 
7792   if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
7793     if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
7794       QualType destType = S.Context.getPointerType(S.Context.VoidTy);
7795       LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
7796       RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
7797       return destType;
7798     }
7799     S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
7800       << LHSTy << RHSTy << LHS.get()->getSourceRange()
7801       << RHS.get()->getSourceRange();
7802     return QualType();
7803   }
7804 
7805   // We have 2 block pointer types.
7806   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
7807 }
7808 
7809 /// Return the resulting type when the operands are both pointers.
7810 static QualType
7811 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
7812                                             ExprResult &RHS,
7813                                             SourceLocation Loc) {
7814   // get the pointer types
7815   QualType LHSTy = LHS.get()->getType();
7816   QualType RHSTy = RHS.get()->getType();
7817 
7818   // get the "pointed to" types
7819   QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
7820   QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
7821 
7822   // ignore qualifiers on void (C99 6.5.15p3, clause 6)
7823   if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
7824     // Figure out necessary qualifiers (C99 6.5.15p6)
7825     QualType destPointee
7826       = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
7827     QualType destType = S.Context.getPointerType(destPointee);
7828     // Add qualifiers if necessary.
7829     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
7830     // Promote to void*.
7831     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
7832     return destType;
7833   }
7834   if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
7835     QualType destPointee
7836       = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
7837     QualType destType = S.Context.getPointerType(destPointee);
7838     // Add qualifiers if necessary.
7839     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
7840     // Promote to void*.
7841     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
7842     return destType;
7843   }
7844 
7845   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
7846 }
7847 
7848 /// Return false if the first expression is not an integer and the second
7849 /// expression is not a pointer, true otherwise.
7850 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
7851                                         Expr* PointerExpr, SourceLocation Loc,
7852                                         bool IsIntFirstExpr) {
7853   if (!PointerExpr->getType()->isPointerType() ||
7854       !Int.get()->getType()->isIntegerType())
7855     return false;
7856 
7857   Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
7858   Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
7859 
7860   S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
7861     << Expr1->getType() << Expr2->getType()
7862     << Expr1->getSourceRange() << Expr2->getSourceRange();
7863   Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
7864                             CK_IntegralToPointer);
7865   return true;
7866 }
7867 
7868 /// Simple conversion between integer and floating point types.
7869 ///
7870 /// Used when handling the OpenCL conditional operator where the
7871 /// condition is a vector while the other operands are scalar.
7872 ///
7873 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
7874 /// types are either integer or floating type. Between the two
7875 /// operands, the type with the higher rank is defined as the "result
7876 /// type". The other operand needs to be promoted to the same type. No
7877 /// other type promotion is allowed. We cannot use
7878 /// UsualArithmeticConversions() for this purpose, since it always
7879 /// promotes promotable types.
7880 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
7881                                             ExprResult &RHS,
7882                                             SourceLocation QuestionLoc) {
7883   LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
7884   if (LHS.isInvalid())
7885     return QualType();
7886   RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
7887   if (RHS.isInvalid())
7888     return QualType();
7889 
7890   // For conversion purposes, we ignore any qualifiers.
7891   // For example, "const float" and "float" are equivalent.
7892   QualType LHSType =
7893     S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
7894   QualType RHSType =
7895     S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
7896 
7897   if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
7898     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
7899       << LHSType << LHS.get()->getSourceRange();
7900     return QualType();
7901   }
7902 
7903   if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
7904     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
7905       << RHSType << RHS.get()->getSourceRange();
7906     return QualType();
7907   }
7908 
7909   // If both types are identical, no conversion is needed.
7910   if (LHSType == RHSType)
7911     return LHSType;
7912 
7913   // Now handle "real" floating types (i.e. float, double, long double).
7914   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
7915     return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
7916                                  /*IsCompAssign = */ false);
7917 
7918   // Finally, we have two differing integer types.
7919   return handleIntegerConversion<doIntegralCast, doIntegralCast>
7920   (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
7921 }
7922 
7923 /// Convert scalar operands to a vector that matches the
7924 ///        condition in length.
7925 ///
7926 /// Used when handling the OpenCL conditional operator where the
7927 /// condition is a vector while the other operands are scalar.
7928 ///
7929 /// We first compute the "result type" for the scalar operands
7930 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
7931 /// into a vector of that type where the length matches the condition
7932 /// vector type. s6.11.6 requires that the element types of the result
7933 /// and the condition must have the same number of bits.
7934 static QualType
7935 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
7936                               QualType CondTy, SourceLocation QuestionLoc) {
7937   QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
7938   if (ResTy.isNull()) return QualType();
7939 
7940   const VectorType *CV = CondTy->getAs<VectorType>();
7941   assert(CV);
7942 
7943   // Determine the vector result type
7944   unsigned NumElements = CV->getNumElements();
7945   QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
7946 
7947   // Ensure that all types have the same number of bits
7948   if (S.Context.getTypeSize(CV->getElementType())
7949       != S.Context.getTypeSize(ResTy)) {
7950     // Since VectorTy is created internally, it does not pretty print
7951     // with an OpenCL name. Instead, we just print a description.
7952     std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
7953     SmallString<64> Str;
7954     llvm::raw_svector_ostream OS(Str);
7955     OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
7956     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
7957       << CondTy << OS.str();
7958     return QualType();
7959   }
7960 
7961   // Convert operands to the vector result type
7962   LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
7963   RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
7964 
7965   return VectorTy;
7966 }
7967 
7968 /// Return false if this is a valid OpenCL condition vector
7969 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
7970                                        SourceLocation QuestionLoc) {
7971   // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
7972   // integral type.
7973   const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
7974   assert(CondTy);
7975   QualType EleTy = CondTy->getElementType();
7976   if (EleTy->isIntegerType()) return false;
7977 
7978   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
7979     << Cond->getType() << Cond->getSourceRange();
7980   return true;
7981 }
7982 
7983 /// Return false if the vector condition type and the vector
7984 ///        result type are compatible.
7985 ///
7986 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
7987 /// number of elements, and their element types have the same number
7988 /// of bits.
7989 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
7990                               SourceLocation QuestionLoc) {
7991   const VectorType *CV = CondTy->getAs<VectorType>();
7992   const VectorType *RV = VecResTy->getAs<VectorType>();
7993   assert(CV && RV);
7994 
7995   if (CV->getNumElements() != RV->getNumElements()) {
7996     S.Diag(QuestionLoc, diag::err_conditional_vector_size)
7997       << CondTy << VecResTy;
7998     return true;
7999   }
8000 
8001   QualType CVE = CV->getElementType();
8002   QualType RVE = RV->getElementType();
8003 
8004   if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
8005     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
8006       << CondTy << VecResTy;
8007     return true;
8008   }
8009 
8010   return false;
8011 }
8012 
8013 /// Return the resulting type for the conditional operator in
8014 ///        OpenCL (aka "ternary selection operator", OpenCL v1.1
8015 ///        s6.3.i) when the condition is a vector type.
8016 static QualType
8017 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
8018                              ExprResult &LHS, ExprResult &RHS,
8019                              SourceLocation QuestionLoc) {
8020   Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
8021   if (Cond.isInvalid())
8022     return QualType();
8023   QualType CondTy = Cond.get()->getType();
8024 
8025   if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
8026     return QualType();
8027 
8028   // If either operand is a vector then find the vector type of the
8029   // result as specified in OpenCL v1.1 s6.3.i.
8030   if (LHS.get()->getType()->isVectorType() ||
8031       RHS.get()->getType()->isVectorType()) {
8032     QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
8033                                               /*isCompAssign*/false,
8034                                               /*AllowBothBool*/true,
8035                                               /*AllowBoolConversions*/false);
8036     if (VecResTy.isNull()) return QualType();
8037     // The result type must match the condition type as specified in
8038     // OpenCL v1.1 s6.11.6.
8039     if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
8040       return QualType();
8041     return VecResTy;
8042   }
8043 
8044   // Both operands are scalar.
8045   return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
8046 }
8047 
8048 /// Return true if the Expr is block type
8049 static bool checkBlockType(Sema &S, const Expr *E) {
8050   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
8051     QualType Ty = CE->getCallee()->getType();
8052     if (Ty->isBlockPointerType()) {
8053       S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
8054       return true;
8055     }
8056   }
8057   return false;
8058 }
8059 
8060 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
8061 /// In that case, LHS = cond.
8062 /// C99 6.5.15
8063 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
8064                                         ExprResult &RHS, ExprValueKind &VK,
8065                                         ExprObjectKind &OK,
8066                                         SourceLocation QuestionLoc) {
8067 
8068   ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
8069   if (!LHSResult.isUsable()) return QualType();
8070   LHS = LHSResult;
8071 
8072   ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
8073   if (!RHSResult.isUsable()) return QualType();
8074   RHS = RHSResult;
8075 
8076   // C++ is sufficiently different to merit its own checker.
8077   if (getLangOpts().CPlusPlus)
8078     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
8079 
8080   VK = VK_RValue;
8081   OK = OK_Ordinary;
8082 
8083   // The OpenCL operator with a vector condition is sufficiently
8084   // different to merit its own checker.
8085   if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) ||
8086       Cond.get()->getType()->isExtVectorType())
8087     return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
8088 
8089   // First, check the condition.
8090   Cond = UsualUnaryConversions(Cond.get());
8091   if (Cond.isInvalid())
8092     return QualType();
8093   if (checkCondition(*this, Cond.get(), QuestionLoc))
8094     return QualType();
8095 
8096   // Now check the two expressions.
8097   if (LHS.get()->getType()->isVectorType() ||
8098       RHS.get()->getType()->isVectorType())
8099     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
8100                                /*AllowBothBool*/true,
8101                                /*AllowBoolConversions*/false);
8102 
8103   QualType ResTy =
8104       UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional);
8105   if (LHS.isInvalid() || RHS.isInvalid())
8106     return QualType();
8107 
8108   QualType LHSTy = LHS.get()->getType();
8109   QualType RHSTy = RHS.get()->getType();
8110 
8111   // Diagnose attempts to convert between __float128 and long double where
8112   // such conversions currently can't be handled.
8113   if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
8114     Diag(QuestionLoc,
8115          diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
8116       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8117     return QualType();
8118   }
8119 
8120   // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
8121   // selection operator (?:).
8122   if (getLangOpts().OpenCL &&
8123       (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) {
8124     return QualType();
8125   }
8126 
8127   // If both operands have arithmetic type, do the usual arithmetic conversions
8128   // to find a common type: C99 6.5.15p3,5.
8129   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
8130     LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
8131     RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
8132 
8133     return ResTy;
8134   }
8135 
8136   // And if they're both bfloat (which isn't arithmetic), that's fine too.
8137   if (LHSTy->isBFloat16Type() && RHSTy->isBFloat16Type()) {
8138     return LHSTy;
8139   }
8140 
8141   // If both operands are the same structure or union type, the result is that
8142   // type.
8143   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
8144     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
8145       if (LHSRT->getDecl() == RHSRT->getDecl())
8146         // "If both the operands have structure or union type, the result has
8147         // that type."  This implies that CV qualifiers are dropped.
8148         return LHSTy.getUnqualifiedType();
8149     // FIXME: Type of conditional expression must be complete in C mode.
8150   }
8151 
8152   // C99 6.5.15p5: "If both operands have void type, the result has void type."
8153   // The following || allows only one side to be void (a GCC-ism).
8154   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
8155     return checkConditionalVoidType(*this, LHS, RHS);
8156   }
8157 
8158   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
8159   // the type of the other operand."
8160   if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
8161   if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
8162 
8163   // All objective-c pointer type analysis is done here.
8164   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
8165                                                         QuestionLoc);
8166   if (LHS.isInvalid() || RHS.isInvalid())
8167     return QualType();
8168   if (!compositeType.isNull())
8169     return compositeType;
8170 
8171 
8172   // Handle block pointer types.
8173   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
8174     return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
8175                                                      QuestionLoc);
8176 
8177   // Check constraints for C object pointers types (C99 6.5.15p3,6).
8178   if (LHSTy->isPointerType() && RHSTy->isPointerType())
8179     return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
8180                                                        QuestionLoc);
8181 
8182   // GCC compatibility: soften pointer/integer mismatch.  Note that
8183   // null pointers have been filtered out by this point.
8184   if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
8185       /*IsIntFirstExpr=*/true))
8186     return RHSTy;
8187   if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
8188       /*IsIntFirstExpr=*/false))
8189     return LHSTy;
8190 
8191   // Allow ?: operations in which both operands have the same
8192   // built-in sizeless type.
8193   if (LHSTy->isSizelessBuiltinType() && LHSTy == RHSTy)
8194     return LHSTy;
8195 
8196   // Emit a better diagnostic if one of the expressions is a null pointer
8197   // constant and the other is not a pointer type. In this case, the user most
8198   // likely forgot to take the address of the other expression.
8199   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
8200     return QualType();
8201 
8202   // Otherwise, the operands are not compatible.
8203   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
8204     << LHSTy << RHSTy << LHS.get()->getSourceRange()
8205     << RHS.get()->getSourceRange();
8206   return QualType();
8207 }
8208 
8209 /// FindCompositeObjCPointerType - Helper method to find composite type of
8210 /// two objective-c pointer types of the two input expressions.
8211 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
8212                                             SourceLocation QuestionLoc) {
8213   QualType LHSTy = LHS.get()->getType();
8214   QualType RHSTy = RHS.get()->getType();
8215 
8216   // Handle things like Class and struct objc_class*.  Here we case the result
8217   // to the pseudo-builtin, because that will be implicitly cast back to the
8218   // redefinition type if an attempt is made to access its fields.
8219   if (LHSTy->isObjCClassType() &&
8220       (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
8221     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
8222     return LHSTy;
8223   }
8224   if (RHSTy->isObjCClassType() &&
8225       (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
8226     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
8227     return RHSTy;
8228   }
8229   // And the same for struct objc_object* / id
8230   if (LHSTy->isObjCIdType() &&
8231       (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
8232     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
8233     return LHSTy;
8234   }
8235   if (RHSTy->isObjCIdType() &&
8236       (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
8237     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
8238     return RHSTy;
8239   }
8240   // And the same for struct objc_selector* / SEL
8241   if (Context.isObjCSelType(LHSTy) &&
8242       (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
8243     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
8244     return LHSTy;
8245   }
8246   if (Context.isObjCSelType(RHSTy) &&
8247       (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
8248     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
8249     return RHSTy;
8250   }
8251   // Check constraints for Objective-C object pointers types.
8252   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
8253 
8254     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
8255       // Two identical object pointer types are always compatible.
8256       return LHSTy;
8257     }
8258     const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
8259     const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
8260     QualType compositeType = LHSTy;
8261 
8262     // If both operands are interfaces and either operand can be
8263     // assigned to the other, use that type as the composite
8264     // type. This allows
8265     //   xxx ? (A*) a : (B*) b
8266     // where B is a subclass of A.
8267     //
8268     // Additionally, as for assignment, if either type is 'id'
8269     // allow silent coercion. Finally, if the types are
8270     // incompatible then make sure to use 'id' as the composite
8271     // type so the result is acceptable for sending messages to.
8272 
8273     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
8274     // It could return the composite type.
8275     if (!(compositeType =
8276           Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
8277       // Nothing more to do.
8278     } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
8279       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
8280     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
8281       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
8282     } else if ((LHSOPT->isObjCQualifiedIdType() ||
8283                 RHSOPT->isObjCQualifiedIdType()) &&
8284                Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT,
8285                                                          true)) {
8286       // Need to handle "id<xx>" explicitly.
8287       // GCC allows qualified id and any Objective-C type to devolve to
8288       // id. Currently localizing to here until clear this should be
8289       // part of ObjCQualifiedIdTypesAreCompatible.
8290       compositeType = Context.getObjCIdType();
8291     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
8292       compositeType = Context.getObjCIdType();
8293     } else {
8294       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
8295       << LHSTy << RHSTy
8296       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8297       QualType incompatTy = Context.getObjCIdType();
8298       LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
8299       RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
8300       return incompatTy;
8301     }
8302     // The object pointer types are compatible.
8303     LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
8304     RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
8305     return compositeType;
8306   }
8307   // Check Objective-C object pointer types and 'void *'
8308   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
8309     if (getLangOpts().ObjCAutoRefCount) {
8310       // ARC forbids the implicit conversion of object pointers to 'void *',
8311       // so these types are not compatible.
8312       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
8313           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8314       LHS = RHS = true;
8315       return QualType();
8316     }
8317     QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8318     QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
8319     QualType destPointee
8320     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
8321     QualType destType = Context.getPointerType(destPointee);
8322     // Add qualifiers if necessary.
8323     LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
8324     // Promote to void*.
8325     RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8326     return destType;
8327   }
8328   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
8329     if (getLangOpts().ObjCAutoRefCount) {
8330       // ARC forbids the implicit conversion of object pointers to 'void *',
8331       // so these types are not compatible.
8332       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
8333           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8334       LHS = RHS = true;
8335       return QualType();
8336     }
8337     QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
8338     QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8339     QualType destPointee
8340     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
8341     QualType destType = Context.getPointerType(destPointee);
8342     // Add qualifiers if necessary.
8343     RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
8344     // Promote to void*.
8345     LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8346     return destType;
8347   }
8348   return QualType();
8349 }
8350 
8351 /// SuggestParentheses - Emit a note with a fixit hint that wraps
8352 /// ParenRange in parentheses.
8353 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
8354                                const PartialDiagnostic &Note,
8355                                SourceRange ParenRange) {
8356   SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
8357   if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
8358       EndLoc.isValid()) {
8359     Self.Diag(Loc, Note)
8360       << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
8361       << FixItHint::CreateInsertion(EndLoc, ")");
8362   } else {
8363     // We can't display the parentheses, so just show the bare note.
8364     Self.Diag(Loc, Note) << ParenRange;
8365   }
8366 }
8367 
8368 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
8369   return BinaryOperator::isAdditiveOp(Opc) ||
8370          BinaryOperator::isMultiplicativeOp(Opc) ||
8371          BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or;
8372   // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and
8373   // not any of the logical operators.  Bitwise-xor is commonly used as a
8374   // logical-xor because there is no logical-xor operator.  The logical
8375   // operators, including uses of xor, have a high false positive rate for
8376   // precedence warnings.
8377 }
8378 
8379 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
8380 /// expression, either using a built-in or overloaded operator,
8381 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
8382 /// expression.
8383 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
8384                                    Expr **RHSExprs) {
8385   // Don't strip parenthesis: we should not warn if E is in parenthesis.
8386   E = E->IgnoreImpCasts();
8387   E = E->IgnoreConversionOperator();
8388   E = E->IgnoreImpCasts();
8389   if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
8390     E = MTE->getSubExpr();
8391     E = E->IgnoreImpCasts();
8392   }
8393 
8394   // Built-in binary operator.
8395   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
8396     if (IsArithmeticOp(OP->getOpcode())) {
8397       *Opcode = OP->getOpcode();
8398       *RHSExprs = OP->getRHS();
8399       return true;
8400     }
8401   }
8402 
8403   // Overloaded operator.
8404   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
8405     if (Call->getNumArgs() != 2)
8406       return false;
8407 
8408     // Make sure this is really a binary operator that is safe to pass into
8409     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
8410     OverloadedOperatorKind OO = Call->getOperator();
8411     if (OO < OO_Plus || OO > OO_Arrow ||
8412         OO == OO_PlusPlus || OO == OO_MinusMinus)
8413       return false;
8414 
8415     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
8416     if (IsArithmeticOp(OpKind)) {
8417       *Opcode = OpKind;
8418       *RHSExprs = Call->getArg(1);
8419       return true;
8420     }
8421   }
8422 
8423   return false;
8424 }
8425 
8426 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
8427 /// or is a logical expression such as (x==y) which has int type, but is
8428 /// commonly interpreted as boolean.
8429 static bool ExprLooksBoolean(Expr *E) {
8430   E = E->IgnoreParenImpCasts();
8431 
8432   if (E->getType()->isBooleanType())
8433     return true;
8434   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
8435     return OP->isComparisonOp() || OP->isLogicalOp();
8436   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
8437     return OP->getOpcode() == UO_LNot;
8438   if (E->getType()->isPointerType())
8439     return true;
8440   // FIXME: What about overloaded operator calls returning "unspecified boolean
8441   // type"s (commonly pointer-to-members)?
8442 
8443   return false;
8444 }
8445 
8446 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
8447 /// and binary operator are mixed in a way that suggests the programmer assumed
8448 /// the conditional operator has higher precedence, for example:
8449 /// "int x = a + someBinaryCondition ? 1 : 2".
8450 static void DiagnoseConditionalPrecedence(Sema &Self,
8451                                           SourceLocation OpLoc,
8452                                           Expr *Condition,
8453                                           Expr *LHSExpr,
8454                                           Expr *RHSExpr) {
8455   BinaryOperatorKind CondOpcode;
8456   Expr *CondRHS;
8457 
8458   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
8459     return;
8460   if (!ExprLooksBoolean(CondRHS))
8461     return;
8462 
8463   // The condition is an arithmetic binary expression, with a right-
8464   // hand side that looks boolean, so warn.
8465 
8466   unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode)
8467                         ? diag::warn_precedence_bitwise_conditional
8468                         : diag::warn_precedence_conditional;
8469 
8470   Self.Diag(OpLoc, DiagID)
8471       << Condition->getSourceRange()
8472       << BinaryOperator::getOpcodeStr(CondOpcode);
8473 
8474   SuggestParentheses(
8475       Self, OpLoc,
8476       Self.PDiag(diag::note_precedence_silence)
8477           << BinaryOperator::getOpcodeStr(CondOpcode),
8478       SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
8479 
8480   SuggestParentheses(Self, OpLoc,
8481                      Self.PDiag(diag::note_precedence_conditional_first),
8482                      SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
8483 }
8484 
8485 /// Compute the nullability of a conditional expression.
8486 static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
8487                                               QualType LHSTy, QualType RHSTy,
8488                                               ASTContext &Ctx) {
8489   if (!ResTy->isAnyPointerType())
8490     return ResTy;
8491 
8492   auto GetNullability = [&Ctx](QualType Ty) {
8493     Optional<NullabilityKind> Kind = Ty->getNullability(Ctx);
8494     if (Kind)
8495       return *Kind;
8496     return NullabilityKind::Unspecified;
8497   };
8498 
8499   auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
8500   NullabilityKind MergedKind;
8501 
8502   // Compute nullability of a binary conditional expression.
8503   if (IsBin) {
8504     if (LHSKind == NullabilityKind::NonNull)
8505       MergedKind = NullabilityKind::NonNull;
8506     else
8507       MergedKind = RHSKind;
8508   // Compute nullability of a normal conditional expression.
8509   } else {
8510     if (LHSKind == NullabilityKind::Nullable ||
8511         RHSKind == NullabilityKind::Nullable)
8512       MergedKind = NullabilityKind::Nullable;
8513     else if (LHSKind == NullabilityKind::NonNull)
8514       MergedKind = RHSKind;
8515     else if (RHSKind == NullabilityKind::NonNull)
8516       MergedKind = LHSKind;
8517     else
8518       MergedKind = NullabilityKind::Unspecified;
8519   }
8520 
8521   // Return if ResTy already has the correct nullability.
8522   if (GetNullability(ResTy) == MergedKind)
8523     return ResTy;
8524 
8525   // Strip all nullability from ResTy.
8526   while (ResTy->getNullability(Ctx))
8527     ResTy = ResTy.getSingleStepDesugaredType(Ctx);
8528 
8529   // Create a new AttributedType with the new nullability kind.
8530   auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
8531   return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
8532 }
8533 
8534 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
8535 /// in the case of a the GNU conditional expr extension.
8536 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
8537                                     SourceLocation ColonLoc,
8538                                     Expr *CondExpr, Expr *LHSExpr,
8539                                     Expr *RHSExpr) {
8540   if (!getLangOpts().CPlusPlus) {
8541     // C cannot handle TypoExpr nodes in the condition because it
8542     // doesn't handle dependent types properly, so make sure any TypoExprs have
8543     // been dealt with before checking the operands.
8544     ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
8545     ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
8546     ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
8547 
8548     if (!CondResult.isUsable())
8549       return ExprError();
8550 
8551     if (LHSExpr) {
8552       if (!LHSResult.isUsable())
8553         return ExprError();
8554     }
8555 
8556     if (!RHSResult.isUsable())
8557       return ExprError();
8558 
8559     CondExpr = CondResult.get();
8560     LHSExpr = LHSResult.get();
8561     RHSExpr = RHSResult.get();
8562   }
8563 
8564   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
8565   // was the condition.
8566   OpaqueValueExpr *opaqueValue = nullptr;
8567   Expr *commonExpr = nullptr;
8568   if (!LHSExpr) {
8569     commonExpr = CondExpr;
8570     // Lower out placeholder types first.  This is important so that we don't
8571     // try to capture a placeholder. This happens in few cases in C++; such
8572     // as Objective-C++'s dictionary subscripting syntax.
8573     if (commonExpr->hasPlaceholderType()) {
8574       ExprResult result = CheckPlaceholderExpr(commonExpr);
8575       if (!result.isUsable()) return ExprError();
8576       commonExpr = result.get();
8577     }
8578     // We usually want to apply unary conversions *before* saving, except
8579     // in the special case of a C++ l-value conditional.
8580     if (!(getLangOpts().CPlusPlus
8581           && !commonExpr->isTypeDependent()
8582           && commonExpr->getValueKind() == RHSExpr->getValueKind()
8583           && commonExpr->isGLValue()
8584           && commonExpr->isOrdinaryOrBitFieldObject()
8585           && RHSExpr->isOrdinaryOrBitFieldObject()
8586           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
8587       ExprResult commonRes = UsualUnaryConversions(commonExpr);
8588       if (commonRes.isInvalid())
8589         return ExprError();
8590       commonExpr = commonRes.get();
8591     }
8592 
8593     // If the common expression is a class or array prvalue, materialize it
8594     // so that we can safely refer to it multiple times.
8595     if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() ||
8596                                    commonExpr->getType()->isArrayType())) {
8597       ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
8598       if (MatExpr.isInvalid())
8599         return ExprError();
8600       commonExpr = MatExpr.get();
8601     }
8602 
8603     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
8604                                                 commonExpr->getType(),
8605                                                 commonExpr->getValueKind(),
8606                                                 commonExpr->getObjectKind(),
8607                                                 commonExpr);
8608     LHSExpr = CondExpr = opaqueValue;
8609   }
8610 
8611   QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
8612   ExprValueKind VK = VK_RValue;
8613   ExprObjectKind OK = OK_Ordinary;
8614   ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
8615   QualType result = CheckConditionalOperands(Cond, LHS, RHS,
8616                                              VK, OK, QuestionLoc);
8617   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
8618       RHS.isInvalid())
8619     return ExprError();
8620 
8621   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
8622                                 RHS.get());
8623 
8624   CheckBoolLikeConversion(Cond.get(), QuestionLoc);
8625 
8626   result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
8627                                          Context);
8628 
8629   if (!commonExpr)
8630     return new (Context)
8631         ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
8632                             RHS.get(), result, VK, OK);
8633 
8634   return new (Context) BinaryConditionalOperator(
8635       commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
8636       ColonLoc, result, VK, OK);
8637 }
8638 
8639 // Check if we have a conversion between incompatible cmse function pointer
8640 // types, that is, a conversion between a function pointer with the
8641 // cmse_nonsecure_call attribute and one without.
8642 static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType,
8643                                           QualType ToType) {
8644   if (const auto *ToFn =
8645           dyn_cast<FunctionType>(S.Context.getCanonicalType(ToType))) {
8646     if (const auto *FromFn =
8647             dyn_cast<FunctionType>(S.Context.getCanonicalType(FromType))) {
8648       FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
8649       FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
8650 
8651       return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall();
8652     }
8653   }
8654   return false;
8655 }
8656 
8657 // checkPointerTypesForAssignment - This is a very tricky routine (despite
8658 // being closely modeled after the C99 spec:-). The odd characteristic of this
8659 // routine is it effectively iqnores the qualifiers on the top level pointee.
8660 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
8661 // FIXME: add a couple examples in this comment.
8662 static Sema::AssignConvertType
8663 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
8664   assert(LHSType.isCanonical() && "LHS not canonicalized!");
8665   assert(RHSType.isCanonical() && "RHS not canonicalized!");
8666 
8667   // get the "pointed to" type (ignoring qualifiers at the top level)
8668   const Type *lhptee, *rhptee;
8669   Qualifiers lhq, rhq;
8670   std::tie(lhptee, lhq) =
8671       cast<PointerType>(LHSType)->getPointeeType().split().asPair();
8672   std::tie(rhptee, rhq) =
8673       cast<PointerType>(RHSType)->getPointeeType().split().asPair();
8674 
8675   Sema::AssignConvertType ConvTy = Sema::Compatible;
8676 
8677   // C99 6.5.16.1p1: This following citation is common to constraints
8678   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
8679   // qualifiers of the type *pointed to* by the right;
8680 
8681   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
8682   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
8683       lhq.compatiblyIncludesObjCLifetime(rhq)) {
8684     // Ignore lifetime for further calculation.
8685     lhq.removeObjCLifetime();
8686     rhq.removeObjCLifetime();
8687   }
8688 
8689   if (!lhq.compatiblyIncludes(rhq)) {
8690     // Treat address-space mismatches as fatal.
8691     if (!lhq.isAddressSpaceSupersetOf(rhq))
8692       return Sema::IncompatiblePointerDiscardsQualifiers;
8693 
8694     // It's okay to add or remove GC or lifetime qualifiers when converting to
8695     // and from void*.
8696     else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
8697                         .compatiblyIncludes(
8698                                 rhq.withoutObjCGCAttr().withoutObjCLifetime())
8699              && (lhptee->isVoidType() || rhptee->isVoidType()))
8700       ; // keep old
8701 
8702     // Treat lifetime mismatches as fatal.
8703     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
8704       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
8705 
8706     // For GCC/MS compatibility, other qualifier mismatches are treated
8707     // as still compatible in C.
8708     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
8709   }
8710 
8711   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
8712   // incomplete type and the other is a pointer to a qualified or unqualified
8713   // version of void...
8714   if (lhptee->isVoidType()) {
8715     if (rhptee->isIncompleteOrObjectType())
8716       return ConvTy;
8717 
8718     // As an extension, we allow cast to/from void* to function pointer.
8719     assert(rhptee->isFunctionType());
8720     return Sema::FunctionVoidPointer;
8721   }
8722 
8723   if (rhptee->isVoidType()) {
8724     if (lhptee->isIncompleteOrObjectType())
8725       return ConvTy;
8726 
8727     // As an extension, we allow cast to/from void* to function pointer.
8728     assert(lhptee->isFunctionType());
8729     return Sema::FunctionVoidPointer;
8730   }
8731 
8732   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
8733   // unqualified versions of compatible types, ...
8734   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
8735   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
8736     // Check if the pointee types are compatible ignoring the sign.
8737     // We explicitly check for char so that we catch "char" vs
8738     // "unsigned char" on systems where "char" is unsigned.
8739     if (lhptee->isCharType())
8740       ltrans = S.Context.UnsignedCharTy;
8741     else if (lhptee->hasSignedIntegerRepresentation())
8742       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
8743 
8744     if (rhptee->isCharType())
8745       rtrans = S.Context.UnsignedCharTy;
8746     else if (rhptee->hasSignedIntegerRepresentation())
8747       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
8748 
8749     if (ltrans == rtrans) {
8750       // Types are compatible ignoring the sign. Qualifier incompatibility
8751       // takes priority over sign incompatibility because the sign
8752       // warning can be disabled.
8753       if (ConvTy != Sema::Compatible)
8754         return ConvTy;
8755 
8756       return Sema::IncompatiblePointerSign;
8757     }
8758 
8759     // If we are a multi-level pointer, it's possible that our issue is simply
8760     // one of qualification - e.g. char ** -> const char ** is not allowed. If
8761     // the eventual target type is the same and the pointers have the same
8762     // level of indirection, this must be the issue.
8763     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
8764       do {
8765         std::tie(lhptee, lhq) =
8766           cast<PointerType>(lhptee)->getPointeeType().split().asPair();
8767         std::tie(rhptee, rhq) =
8768           cast<PointerType>(rhptee)->getPointeeType().split().asPair();
8769 
8770         // Inconsistent address spaces at this point is invalid, even if the
8771         // address spaces would be compatible.
8772         // FIXME: This doesn't catch address space mismatches for pointers of
8773         // different nesting levels, like:
8774         //   __local int *** a;
8775         //   int ** b = a;
8776         // It's not clear how to actually determine when such pointers are
8777         // invalidly incompatible.
8778         if (lhq.getAddressSpace() != rhq.getAddressSpace())
8779           return Sema::IncompatibleNestedPointerAddressSpaceMismatch;
8780 
8781       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
8782 
8783       if (lhptee == rhptee)
8784         return Sema::IncompatibleNestedPointerQualifiers;
8785     }
8786 
8787     // General pointer incompatibility takes priority over qualifiers.
8788     if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType())
8789       return Sema::IncompatibleFunctionPointer;
8790     return Sema::IncompatiblePointer;
8791   }
8792   if (!S.getLangOpts().CPlusPlus &&
8793       S.IsFunctionConversion(ltrans, rtrans, ltrans))
8794     return Sema::IncompatibleFunctionPointer;
8795   if (IsInvalidCmseNSCallConversion(S, ltrans, rtrans))
8796     return Sema::IncompatibleFunctionPointer;
8797   return ConvTy;
8798 }
8799 
8800 /// checkBlockPointerTypesForAssignment - This routine determines whether two
8801 /// block pointer types are compatible or whether a block and normal pointer
8802 /// are compatible. It is more restrict than comparing two function pointer
8803 // types.
8804 static Sema::AssignConvertType
8805 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
8806                                     QualType RHSType) {
8807   assert(LHSType.isCanonical() && "LHS not canonicalized!");
8808   assert(RHSType.isCanonical() && "RHS not canonicalized!");
8809 
8810   QualType lhptee, rhptee;
8811 
8812   // get the "pointed to" type (ignoring qualifiers at the top level)
8813   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
8814   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
8815 
8816   // In C++, the types have to match exactly.
8817   if (S.getLangOpts().CPlusPlus)
8818     return Sema::IncompatibleBlockPointer;
8819 
8820   Sema::AssignConvertType ConvTy = Sema::Compatible;
8821 
8822   // For blocks we enforce that qualifiers are identical.
8823   Qualifiers LQuals = lhptee.getLocalQualifiers();
8824   Qualifiers RQuals = rhptee.getLocalQualifiers();
8825   if (S.getLangOpts().OpenCL) {
8826     LQuals.removeAddressSpace();
8827     RQuals.removeAddressSpace();
8828   }
8829   if (LQuals != RQuals)
8830     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
8831 
8832   // FIXME: OpenCL doesn't define the exact compile time semantics for a block
8833   // assignment.
8834   // The current behavior is similar to C++ lambdas. A block might be
8835   // assigned to a variable iff its return type and parameters are compatible
8836   // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
8837   // an assignment. Presumably it should behave in way that a function pointer
8838   // assignment does in C, so for each parameter and return type:
8839   //  * CVR and address space of LHS should be a superset of CVR and address
8840   //  space of RHS.
8841   //  * unqualified types should be compatible.
8842   if (S.getLangOpts().OpenCL) {
8843     if (!S.Context.typesAreBlockPointerCompatible(
8844             S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
8845             S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
8846       return Sema::IncompatibleBlockPointer;
8847   } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
8848     return Sema::IncompatibleBlockPointer;
8849 
8850   return ConvTy;
8851 }
8852 
8853 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
8854 /// for assignment compatibility.
8855 static Sema::AssignConvertType
8856 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
8857                                    QualType RHSType) {
8858   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
8859   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
8860 
8861   if (LHSType->isObjCBuiltinType()) {
8862     // Class is not compatible with ObjC object pointers.
8863     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
8864         !RHSType->isObjCQualifiedClassType())
8865       return Sema::IncompatiblePointer;
8866     return Sema::Compatible;
8867   }
8868   if (RHSType->isObjCBuiltinType()) {
8869     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
8870         !LHSType->isObjCQualifiedClassType())
8871       return Sema::IncompatiblePointer;
8872     return Sema::Compatible;
8873   }
8874   QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
8875   QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
8876 
8877   if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
8878       // make an exception for id<P>
8879       !LHSType->isObjCQualifiedIdType())
8880     return Sema::CompatiblePointerDiscardsQualifiers;
8881 
8882   if (S.Context.typesAreCompatible(LHSType, RHSType))
8883     return Sema::Compatible;
8884   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
8885     return Sema::IncompatibleObjCQualifiedId;
8886   return Sema::IncompatiblePointer;
8887 }
8888 
8889 Sema::AssignConvertType
8890 Sema::CheckAssignmentConstraints(SourceLocation Loc,
8891                                  QualType LHSType, QualType RHSType) {
8892   // Fake up an opaque expression.  We don't actually care about what
8893   // cast operations are required, so if CheckAssignmentConstraints
8894   // adds casts to this they'll be wasted, but fortunately that doesn't
8895   // usually happen on valid code.
8896   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
8897   ExprResult RHSPtr = &RHSExpr;
8898   CastKind K;
8899 
8900   return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
8901 }
8902 
8903 /// This helper function returns true if QT is a vector type that has element
8904 /// type ElementType.
8905 static bool isVector(QualType QT, QualType ElementType) {
8906   if (const VectorType *VT = QT->getAs<VectorType>())
8907     return VT->getElementType().getCanonicalType() == ElementType;
8908   return false;
8909 }
8910 
8911 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
8912 /// has code to accommodate several GCC extensions when type checking
8913 /// pointers. Here are some objectionable examples that GCC considers warnings:
8914 ///
8915 ///  int a, *pint;
8916 ///  short *pshort;
8917 ///  struct foo *pfoo;
8918 ///
8919 ///  pint = pshort; // warning: assignment from incompatible pointer type
8920 ///  a = pint; // warning: assignment makes integer from pointer without a cast
8921 ///  pint = a; // warning: assignment makes pointer from integer without a cast
8922 ///  pint = pfoo; // warning: assignment from incompatible pointer type
8923 ///
8924 /// As a result, the code for dealing with pointers is more complex than the
8925 /// C99 spec dictates.
8926 ///
8927 /// Sets 'Kind' for any result kind except Incompatible.
8928 Sema::AssignConvertType
8929 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
8930                                  CastKind &Kind, bool ConvertRHS) {
8931   QualType RHSType = RHS.get()->getType();
8932   QualType OrigLHSType = LHSType;
8933 
8934   // Get canonical types.  We're not formatting these types, just comparing
8935   // them.
8936   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
8937   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
8938 
8939   // Common case: no conversion required.
8940   if (LHSType == RHSType) {
8941     Kind = CK_NoOp;
8942     return Compatible;
8943   }
8944 
8945   // If we have an atomic type, try a non-atomic assignment, then just add an
8946   // atomic qualification step.
8947   if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
8948     Sema::AssignConvertType result =
8949       CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
8950     if (result != Compatible)
8951       return result;
8952     if (Kind != CK_NoOp && ConvertRHS)
8953       RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
8954     Kind = CK_NonAtomicToAtomic;
8955     return Compatible;
8956   }
8957 
8958   // If the left-hand side is a reference type, then we are in a
8959   // (rare!) case where we've allowed the use of references in C,
8960   // e.g., as a parameter type in a built-in function. In this case,
8961   // just make sure that the type referenced is compatible with the
8962   // right-hand side type. The caller is responsible for adjusting
8963   // LHSType so that the resulting expression does not have reference
8964   // type.
8965   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
8966     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
8967       Kind = CK_LValueBitCast;
8968       return Compatible;
8969     }
8970     return Incompatible;
8971   }
8972 
8973   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
8974   // to the same ExtVector type.
8975   if (LHSType->isExtVectorType()) {
8976     if (RHSType->isExtVectorType())
8977       return Incompatible;
8978     if (RHSType->isArithmeticType()) {
8979       // CK_VectorSplat does T -> vector T, so first cast to the element type.
8980       if (ConvertRHS)
8981         RHS = prepareVectorSplat(LHSType, RHS.get());
8982       Kind = CK_VectorSplat;
8983       return Compatible;
8984     }
8985   }
8986 
8987   // Conversions to or from vector type.
8988   if (LHSType->isVectorType() || RHSType->isVectorType()) {
8989     if (LHSType->isVectorType() && RHSType->isVectorType()) {
8990       // Allow assignments of an AltiVec vector type to an equivalent GCC
8991       // vector type and vice versa
8992       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
8993         Kind = CK_BitCast;
8994         return Compatible;
8995       }
8996 
8997       // If we are allowing lax vector conversions, and LHS and RHS are both
8998       // vectors, the total size only needs to be the same. This is a bitcast;
8999       // no bits are changed but the result type is different.
9000       if (isLaxVectorConversion(RHSType, LHSType)) {
9001         Kind = CK_BitCast;
9002         return IncompatibleVectors;
9003       }
9004     }
9005 
9006     // When the RHS comes from another lax conversion (e.g. binops between
9007     // scalars and vectors) the result is canonicalized as a vector. When the
9008     // LHS is also a vector, the lax is allowed by the condition above. Handle
9009     // the case where LHS is a scalar.
9010     if (LHSType->isScalarType()) {
9011       const VectorType *VecType = RHSType->getAs<VectorType>();
9012       if (VecType && VecType->getNumElements() == 1 &&
9013           isLaxVectorConversion(RHSType, LHSType)) {
9014         ExprResult *VecExpr = &RHS;
9015         *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
9016         Kind = CK_BitCast;
9017         return Compatible;
9018       }
9019     }
9020 
9021     return Incompatible;
9022   }
9023 
9024   // Diagnose attempts to convert between __float128 and long double where
9025   // such conversions currently can't be handled.
9026   if (unsupportedTypeConversion(*this, LHSType, RHSType))
9027     return Incompatible;
9028 
9029   // Disallow assigning a _Complex to a real type in C++ mode since it simply
9030   // discards the imaginary part.
9031   if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
9032       !LHSType->getAs<ComplexType>())
9033     return Incompatible;
9034 
9035   // Arithmetic conversions.
9036   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
9037       !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
9038     if (ConvertRHS)
9039       Kind = PrepareScalarCast(RHS, LHSType);
9040     return Compatible;
9041   }
9042 
9043   // Conversions to normal pointers.
9044   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
9045     // U* -> T*
9046     if (isa<PointerType>(RHSType)) {
9047       LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9048       LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
9049       if (AddrSpaceL != AddrSpaceR)
9050         Kind = CK_AddressSpaceConversion;
9051       else if (Context.hasCvrSimilarType(RHSType, LHSType))
9052         Kind = CK_NoOp;
9053       else
9054         Kind = CK_BitCast;
9055       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
9056     }
9057 
9058     // int -> T*
9059     if (RHSType->isIntegerType()) {
9060       Kind = CK_IntegralToPointer; // FIXME: null?
9061       return IntToPointer;
9062     }
9063 
9064     // C pointers are not compatible with ObjC object pointers,
9065     // with two exceptions:
9066     if (isa<ObjCObjectPointerType>(RHSType)) {
9067       //  - conversions to void*
9068       if (LHSPointer->getPointeeType()->isVoidType()) {
9069         Kind = CK_BitCast;
9070         return Compatible;
9071       }
9072 
9073       //  - conversions from 'Class' to the redefinition type
9074       if (RHSType->isObjCClassType() &&
9075           Context.hasSameType(LHSType,
9076                               Context.getObjCClassRedefinitionType())) {
9077         Kind = CK_BitCast;
9078         return Compatible;
9079       }
9080 
9081       Kind = CK_BitCast;
9082       return IncompatiblePointer;
9083     }
9084 
9085     // U^ -> void*
9086     if (RHSType->getAs<BlockPointerType>()) {
9087       if (LHSPointer->getPointeeType()->isVoidType()) {
9088         LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9089         LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9090                                 ->getPointeeType()
9091                                 .getAddressSpace();
9092         Kind =
9093             AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9094         return Compatible;
9095       }
9096     }
9097 
9098     return Incompatible;
9099   }
9100 
9101   // Conversions to block pointers.
9102   if (isa<BlockPointerType>(LHSType)) {
9103     // U^ -> T^
9104     if (RHSType->isBlockPointerType()) {
9105       LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
9106                               ->getPointeeType()
9107                               .getAddressSpace();
9108       LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9109                               ->getPointeeType()
9110                               .getAddressSpace();
9111       Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9112       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
9113     }
9114 
9115     // int or null -> T^
9116     if (RHSType->isIntegerType()) {
9117       Kind = CK_IntegralToPointer; // FIXME: null
9118       return IntToBlockPointer;
9119     }
9120 
9121     // id -> T^
9122     if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
9123       Kind = CK_AnyPointerToBlockPointerCast;
9124       return Compatible;
9125     }
9126 
9127     // void* -> T^
9128     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
9129       if (RHSPT->getPointeeType()->isVoidType()) {
9130         Kind = CK_AnyPointerToBlockPointerCast;
9131         return Compatible;
9132       }
9133 
9134     return Incompatible;
9135   }
9136 
9137   // Conversions to Objective-C pointers.
9138   if (isa<ObjCObjectPointerType>(LHSType)) {
9139     // A* -> B*
9140     if (RHSType->isObjCObjectPointerType()) {
9141       Kind = CK_BitCast;
9142       Sema::AssignConvertType result =
9143         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
9144       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9145           result == Compatible &&
9146           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
9147         result = IncompatibleObjCWeakRef;
9148       return result;
9149     }
9150 
9151     // int or null -> A*
9152     if (RHSType->isIntegerType()) {
9153       Kind = CK_IntegralToPointer; // FIXME: null
9154       return IntToPointer;
9155     }
9156 
9157     // In general, C pointers are not compatible with ObjC object pointers,
9158     // with two exceptions:
9159     if (isa<PointerType>(RHSType)) {
9160       Kind = CK_CPointerToObjCPointerCast;
9161 
9162       //  - conversions from 'void*'
9163       if (RHSType->isVoidPointerType()) {
9164         return Compatible;
9165       }
9166 
9167       //  - conversions to 'Class' from its redefinition type
9168       if (LHSType->isObjCClassType() &&
9169           Context.hasSameType(RHSType,
9170                               Context.getObjCClassRedefinitionType())) {
9171         return Compatible;
9172       }
9173 
9174       return IncompatiblePointer;
9175     }
9176 
9177     // Only under strict condition T^ is compatible with an Objective-C pointer.
9178     if (RHSType->isBlockPointerType() &&
9179         LHSType->isBlockCompatibleObjCPointerType(Context)) {
9180       if (ConvertRHS)
9181         maybeExtendBlockObject(RHS);
9182       Kind = CK_BlockPointerToObjCPointerCast;
9183       return Compatible;
9184     }
9185 
9186     return Incompatible;
9187   }
9188 
9189   // Conversions from pointers that are not covered by the above.
9190   if (isa<PointerType>(RHSType)) {
9191     // T* -> _Bool
9192     if (LHSType == Context.BoolTy) {
9193       Kind = CK_PointerToBoolean;
9194       return Compatible;
9195     }
9196 
9197     // T* -> int
9198     if (LHSType->isIntegerType()) {
9199       Kind = CK_PointerToIntegral;
9200       return PointerToInt;
9201     }
9202 
9203     return Incompatible;
9204   }
9205 
9206   // Conversions from Objective-C pointers that are not covered by the above.
9207   if (isa<ObjCObjectPointerType>(RHSType)) {
9208     // T* -> _Bool
9209     if (LHSType == Context.BoolTy) {
9210       Kind = CK_PointerToBoolean;
9211       return Compatible;
9212     }
9213 
9214     // T* -> int
9215     if (LHSType->isIntegerType()) {
9216       Kind = CK_PointerToIntegral;
9217       return PointerToInt;
9218     }
9219 
9220     return Incompatible;
9221   }
9222 
9223   // struct A -> struct B
9224   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
9225     if (Context.typesAreCompatible(LHSType, RHSType)) {
9226       Kind = CK_NoOp;
9227       return Compatible;
9228     }
9229   }
9230 
9231   if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
9232     Kind = CK_IntToOCLSampler;
9233     return Compatible;
9234   }
9235 
9236   return Incompatible;
9237 }
9238 
9239 /// Constructs a transparent union from an expression that is
9240 /// used to initialize the transparent union.
9241 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
9242                                       ExprResult &EResult, QualType UnionType,
9243                                       FieldDecl *Field) {
9244   // Build an initializer list that designates the appropriate member
9245   // of the transparent union.
9246   Expr *E = EResult.get();
9247   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
9248                                                    E, SourceLocation());
9249   Initializer->setType(UnionType);
9250   Initializer->setInitializedFieldInUnion(Field);
9251 
9252   // Build a compound literal constructing a value of the transparent
9253   // union type from this initializer list.
9254   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
9255   EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
9256                                         VK_RValue, Initializer, false);
9257 }
9258 
9259 Sema::AssignConvertType
9260 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
9261                                                ExprResult &RHS) {
9262   QualType RHSType = RHS.get()->getType();
9263 
9264   // If the ArgType is a Union type, we want to handle a potential
9265   // transparent_union GCC extension.
9266   const RecordType *UT = ArgType->getAsUnionType();
9267   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
9268     return Incompatible;
9269 
9270   // The field to initialize within the transparent union.
9271   RecordDecl *UD = UT->getDecl();
9272   FieldDecl *InitField = nullptr;
9273   // It's compatible if the expression matches any of the fields.
9274   for (auto *it : UD->fields()) {
9275     if (it->getType()->isPointerType()) {
9276       // If the transparent union contains a pointer type, we allow:
9277       // 1) void pointer
9278       // 2) null pointer constant
9279       if (RHSType->isPointerType())
9280         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
9281           RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
9282           InitField = it;
9283           break;
9284         }
9285 
9286       if (RHS.get()->isNullPointerConstant(Context,
9287                                            Expr::NPC_ValueDependentIsNull)) {
9288         RHS = ImpCastExprToType(RHS.get(), it->getType(),
9289                                 CK_NullToPointer);
9290         InitField = it;
9291         break;
9292       }
9293     }
9294 
9295     CastKind Kind;
9296     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
9297           == Compatible) {
9298       RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
9299       InitField = it;
9300       break;
9301     }
9302   }
9303 
9304   if (!InitField)
9305     return Incompatible;
9306 
9307   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
9308   return Compatible;
9309 }
9310 
9311 Sema::AssignConvertType
9312 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
9313                                        bool Diagnose,
9314                                        bool DiagnoseCFAudited,
9315                                        bool ConvertRHS) {
9316   // We need to be able to tell the caller whether we diagnosed a problem, if
9317   // they ask us to issue diagnostics.
9318   assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
9319 
9320   // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
9321   // we can't avoid *all* modifications at the moment, so we need some somewhere
9322   // to put the updated value.
9323   ExprResult LocalRHS = CallerRHS;
9324   ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
9325 
9326   if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
9327     if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
9328       if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
9329           !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
9330         Diag(RHS.get()->getExprLoc(),
9331              diag::warn_noderef_to_dereferenceable_pointer)
9332             << RHS.get()->getSourceRange();
9333       }
9334     }
9335   }
9336 
9337   if (getLangOpts().CPlusPlus) {
9338     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
9339       // C++ 5.17p3: If the left operand is not of class type, the
9340       // expression is implicitly converted (C++ 4) to the
9341       // cv-unqualified type of the left operand.
9342       QualType RHSType = RHS.get()->getType();
9343       if (Diagnose) {
9344         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9345                                         AA_Assigning);
9346       } else {
9347         ImplicitConversionSequence ICS =
9348             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9349                                   /*SuppressUserConversions=*/false,
9350                                   AllowedExplicit::None,
9351                                   /*InOverloadResolution=*/false,
9352                                   /*CStyle=*/false,
9353                                   /*AllowObjCWritebackConversion=*/false);
9354         if (ICS.isFailure())
9355           return Incompatible;
9356         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9357                                         ICS, AA_Assigning);
9358       }
9359       if (RHS.isInvalid())
9360         return Incompatible;
9361       Sema::AssignConvertType result = Compatible;
9362       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9363           !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
9364         result = IncompatibleObjCWeakRef;
9365       return result;
9366     }
9367 
9368     // FIXME: Currently, we fall through and treat C++ classes like C
9369     // structures.
9370     // FIXME: We also fall through for atomics; not sure what should
9371     // happen there, though.
9372   } else if (RHS.get()->getType() == Context.OverloadTy) {
9373     // As a set of extensions to C, we support overloading on functions. These
9374     // functions need to be resolved here.
9375     DeclAccessPair DAP;
9376     if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
9377             RHS.get(), LHSType, /*Complain=*/false, DAP))
9378       RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
9379     else
9380       return Incompatible;
9381   }
9382 
9383   // C99 6.5.16.1p1: the left operand is a pointer and the right is
9384   // a null pointer constant.
9385   if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
9386        LHSType->isBlockPointerType()) &&
9387       RHS.get()->isNullPointerConstant(Context,
9388                                        Expr::NPC_ValueDependentIsNull)) {
9389     if (Diagnose || ConvertRHS) {
9390       CastKind Kind;
9391       CXXCastPath Path;
9392       CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
9393                              /*IgnoreBaseAccess=*/false, Diagnose);
9394       if (ConvertRHS)
9395         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
9396     }
9397     return Compatible;
9398   }
9399 
9400   // OpenCL queue_t type assignment.
9401   if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
9402                                  Context, Expr::NPC_ValueDependentIsNull)) {
9403     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9404     return Compatible;
9405   }
9406 
9407   // This check seems unnatural, however it is necessary to ensure the proper
9408   // conversion of functions/arrays. If the conversion were done for all
9409   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
9410   // expressions that suppress this implicit conversion (&, sizeof).
9411   //
9412   // Suppress this for references: C++ 8.5.3p5.
9413   if (!LHSType->isReferenceType()) {
9414     // FIXME: We potentially allocate here even if ConvertRHS is false.
9415     RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
9416     if (RHS.isInvalid())
9417       return Incompatible;
9418   }
9419   CastKind Kind;
9420   Sema::AssignConvertType result =
9421     CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
9422 
9423   // C99 6.5.16.1p2: The value of the right operand is converted to the
9424   // type of the assignment expression.
9425   // CheckAssignmentConstraints allows the left-hand side to be a reference,
9426   // so that we can use references in built-in functions even in C.
9427   // The getNonReferenceType() call makes sure that the resulting expression
9428   // does not have reference type.
9429   if (result != Incompatible && RHS.get()->getType() != LHSType) {
9430     QualType Ty = LHSType.getNonLValueExprType(Context);
9431     Expr *E = RHS.get();
9432 
9433     // Check for various Objective-C errors. If we are not reporting
9434     // diagnostics and just checking for errors, e.g., during overload
9435     // resolution, return Incompatible to indicate the failure.
9436     if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9437         CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
9438                             Diagnose, DiagnoseCFAudited) != ACR_okay) {
9439       if (!Diagnose)
9440         return Incompatible;
9441     }
9442     if (getLangOpts().ObjC &&
9443         (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType,
9444                                            E->getType(), E, Diagnose) ||
9445          CheckConversionToObjCLiteral(LHSType, E, Diagnose))) {
9446       if (!Diagnose)
9447         return Incompatible;
9448       // Replace the expression with a corrected version and continue so we
9449       // can find further errors.
9450       RHS = E;
9451       return Compatible;
9452     }
9453 
9454     if (ConvertRHS)
9455       RHS = ImpCastExprToType(E, Ty, Kind);
9456   }
9457 
9458   return result;
9459 }
9460 
9461 namespace {
9462 /// The original operand to an operator, prior to the application of the usual
9463 /// arithmetic conversions and converting the arguments of a builtin operator
9464 /// candidate.
9465 struct OriginalOperand {
9466   explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
9467     if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op))
9468       Op = MTE->getSubExpr();
9469     if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op))
9470       Op = BTE->getSubExpr();
9471     if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) {
9472       Orig = ICE->getSubExprAsWritten();
9473       Conversion = ICE->getConversionFunction();
9474     }
9475   }
9476 
9477   QualType getType() const { return Orig->getType(); }
9478 
9479   Expr *Orig;
9480   NamedDecl *Conversion;
9481 };
9482 }
9483 
9484 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
9485                                ExprResult &RHS) {
9486   OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
9487 
9488   Diag(Loc, diag::err_typecheck_invalid_operands)
9489     << OrigLHS.getType() << OrigRHS.getType()
9490     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9491 
9492   // If a user-defined conversion was applied to either of the operands prior
9493   // to applying the built-in operator rules, tell the user about it.
9494   if (OrigLHS.Conversion) {
9495     Diag(OrigLHS.Conversion->getLocation(),
9496          diag::note_typecheck_invalid_operands_converted)
9497       << 0 << LHS.get()->getType();
9498   }
9499   if (OrigRHS.Conversion) {
9500     Diag(OrigRHS.Conversion->getLocation(),
9501          diag::note_typecheck_invalid_operands_converted)
9502       << 1 << RHS.get()->getType();
9503   }
9504 
9505   return QualType();
9506 }
9507 
9508 // Diagnose cases where a scalar was implicitly converted to a vector and
9509 // diagnose the underlying types. Otherwise, diagnose the error
9510 // as invalid vector logical operands for non-C++ cases.
9511 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
9512                                             ExprResult &RHS) {
9513   QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
9514   QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
9515 
9516   bool LHSNatVec = LHSType->isVectorType();
9517   bool RHSNatVec = RHSType->isVectorType();
9518 
9519   if (!(LHSNatVec && RHSNatVec)) {
9520     Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
9521     Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
9522     Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
9523         << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
9524         << Vector->getSourceRange();
9525     return QualType();
9526   }
9527 
9528   Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
9529       << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
9530       << RHS.get()->getSourceRange();
9531 
9532   return QualType();
9533 }
9534 
9535 /// Try to convert a value of non-vector type to a vector type by converting
9536 /// the type to the element type of the vector and then performing a splat.
9537 /// If the language is OpenCL, we only use conversions that promote scalar
9538 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
9539 /// for float->int.
9540 ///
9541 /// OpenCL V2.0 6.2.6.p2:
9542 /// An error shall occur if any scalar operand type has greater rank
9543 /// than the type of the vector element.
9544 ///
9545 /// \param scalar - if non-null, actually perform the conversions
9546 /// \return true if the operation fails (but without diagnosing the failure)
9547 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
9548                                      QualType scalarTy,
9549                                      QualType vectorEltTy,
9550                                      QualType vectorTy,
9551                                      unsigned &DiagID) {
9552   // The conversion to apply to the scalar before splatting it,
9553   // if necessary.
9554   CastKind scalarCast = CK_NoOp;
9555 
9556   if (vectorEltTy->isIntegralType(S.Context)) {
9557     if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
9558         (scalarTy->isIntegerType() &&
9559          S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
9560       DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
9561       return true;
9562     }
9563     if (!scalarTy->isIntegralType(S.Context))
9564       return true;
9565     scalarCast = CK_IntegralCast;
9566   } else if (vectorEltTy->isRealFloatingType()) {
9567     if (scalarTy->isRealFloatingType()) {
9568       if (S.getLangOpts().OpenCL &&
9569           S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
9570         DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
9571         return true;
9572       }
9573       scalarCast = CK_FloatingCast;
9574     }
9575     else if (scalarTy->isIntegralType(S.Context))
9576       scalarCast = CK_IntegralToFloating;
9577     else
9578       return true;
9579   } else {
9580     return true;
9581   }
9582 
9583   // Adjust scalar if desired.
9584   if (scalar) {
9585     if (scalarCast != CK_NoOp)
9586       *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
9587     *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
9588   }
9589   return false;
9590 }
9591 
9592 /// Convert vector E to a vector with the same number of elements but different
9593 /// element type.
9594 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
9595   const auto *VecTy = E->getType()->getAs<VectorType>();
9596   assert(VecTy && "Expression E must be a vector");
9597   QualType NewVecTy = S.Context.getVectorType(ElementType,
9598                                               VecTy->getNumElements(),
9599                                               VecTy->getVectorKind());
9600 
9601   // Look through the implicit cast. Return the subexpression if its type is
9602   // NewVecTy.
9603   if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
9604     if (ICE->getSubExpr()->getType() == NewVecTy)
9605       return ICE->getSubExpr();
9606 
9607   auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
9608   return S.ImpCastExprToType(E, NewVecTy, Cast);
9609 }
9610 
9611 /// Test if a (constant) integer Int can be casted to another integer type
9612 /// IntTy without losing precision.
9613 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int,
9614                                       QualType OtherIntTy) {
9615   QualType IntTy = Int->get()->getType().getUnqualifiedType();
9616 
9617   // Reject cases where the value of the Int is unknown as that would
9618   // possibly cause truncation, but accept cases where the scalar can be
9619   // demoted without loss of precision.
9620   Expr::EvalResult EVResult;
9621   bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
9622   int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
9623   bool IntSigned = IntTy->hasSignedIntegerRepresentation();
9624   bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
9625 
9626   if (CstInt) {
9627     // If the scalar is constant and is of a higher order and has more active
9628     // bits that the vector element type, reject it.
9629     llvm::APSInt Result = EVResult.Val.getInt();
9630     unsigned NumBits = IntSigned
9631                            ? (Result.isNegative() ? Result.getMinSignedBits()
9632                                                   : Result.getActiveBits())
9633                            : Result.getActiveBits();
9634     if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
9635       return true;
9636 
9637     // If the signedness of the scalar type and the vector element type
9638     // differs and the number of bits is greater than that of the vector
9639     // element reject it.
9640     return (IntSigned != OtherIntSigned &&
9641             NumBits > S.Context.getIntWidth(OtherIntTy));
9642   }
9643 
9644   // Reject cases where the value of the scalar is not constant and it's
9645   // order is greater than that of the vector element type.
9646   return (Order < 0);
9647 }
9648 
9649 /// Test if a (constant) integer Int can be casted to floating point type
9650 /// FloatTy without losing precision.
9651 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int,
9652                                      QualType FloatTy) {
9653   QualType IntTy = Int->get()->getType().getUnqualifiedType();
9654 
9655   // Determine if the integer constant can be expressed as a floating point
9656   // number of the appropriate type.
9657   Expr::EvalResult EVResult;
9658   bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
9659 
9660   uint64_t Bits = 0;
9661   if (CstInt) {
9662     // Reject constants that would be truncated if they were converted to
9663     // the floating point type. Test by simple to/from conversion.
9664     // FIXME: Ideally the conversion to an APFloat and from an APFloat
9665     //        could be avoided if there was a convertFromAPInt method
9666     //        which could signal back if implicit truncation occurred.
9667     llvm::APSInt Result = EVResult.Val.getInt();
9668     llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
9669     Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
9670                            llvm::APFloat::rmTowardZero);
9671     llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
9672                              !IntTy->hasSignedIntegerRepresentation());
9673     bool Ignored = false;
9674     Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
9675                            &Ignored);
9676     if (Result != ConvertBack)
9677       return true;
9678   } else {
9679     // Reject types that cannot be fully encoded into the mantissa of
9680     // the float.
9681     Bits = S.Context.getTypeSize(IntTy);
9682     unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
9683         S.Context.getFloatTypeSemantics(FloatTy));
9684     if (Bits > FloatPrec)
9685       return true;
9686   }
9687 
9688   return false;
9689 }
9690 
9691 /// Attempt to convert and splat Scalar into a vector whose types matches
9692 /// Vector following GCC conversion rules. The rule is that implicit
9693 /// conversion can occur when Scalar can be casted to match Vector's element
9694 /// type without causing truncation of Scalar.
9695 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar,
9696                                         ExprResult *Vector) {
9697   QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
9698   QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
9699   const VectorType *VT = VectorTy->getAs<VectorType>();
9700 
9701   assert(!isa<ExtVectorType>(VT) &&
9702          "ExtVectorTypes should not be handled here!");
9703 
9704   QualType VectorEltTy = VT->getElementType();
9705 
9706   // Reject cases where the vector element type or the scalar element type are
9707   // not integral or floating point types.
9708   if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
9709     return true;
9710 
9711   // The conversion to apply to the scalar before splatting it,
9712   // if necessary.
9713   CastKind ScalarCast = CK_NoOp;
9714 
9715   // Accept cases where the vector elements are integers and the scalar is
9716   // an integer.
9717   // FIXME: Notionally if the scalar was a floating point value with a precise
9718   //        integral representation, we could cast it to an appropriate integer
9719   //        type and then perform the rest of the checks here. GCC will perform
9720   //        this conversion in some cases as determined by the input language.
9721   //        We should accept it on a language independent basis.
9722   if (VectorEltTy->isIntegralType(S.Context) &&
9723       ScalarTy->isIntegralType(S.Context) &&
9724       S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
9725 
9726     if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
9727       return true;
9728 
9729     ScalarCast = CK_IntegralCast;
9730   } else if (VectorEltTy->isIntegralType(S.Context) &&
9731              ScalarTy->isRealFloatingType()) {
9732     if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy))
9733       ScalarCast = CK_FloatingToIntegral;
9734     else
9735       return true;
9736   } else if (VectorEltTy->isRealFloatingType()) {
9737     if (ScalarTy->isRealFloatingType()) {
9738 
9739       // Reject cases where the scalar type is not a constant and has a higher
9740       // Order than the vector element type.
9741       llvm::APFloat Result(0.0);
9742 
9743       // Determine whether this is a constant scalar. In the event that the
9744       // value is dependent (and thus cannot be evaluated by the constant
9745       // evaluator), skip the evaluation. This will then diagnose once the
9746       // expression is instantiated.
9747       bool CstScalar = Scalar->get()->isValueDependent() ||
9748                        Scalar->get()->EvaluateAsFloat(Result, S.Context);
9749       int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
9750       if (!CstScalar && Order < 0)
9751         return true;
9752 
9753       // If the scalar cannot be safely casted to the vector element type,
9754       // reject it.
9755       if (CstScalar) {
9756         bool Truncated = false;
9757         Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
9758                        llvm::APFloat::rmNearestTiesToEven, &Truncated);
9759         if (Truncated)
9760           return true;
9761       }
9762 
9763       ScalarCast = CK_FloatingCast;
9764     } else if (ScalarTy->isIntegralType(S.Context)) {
9765       if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
9766         return true;
9767 
9768       ScalarCast = CK_IntegralToFloating;
9769     } else
9770       return true;
9771   } else if (ScalarTy->isEnumeralType())
9772     return true;
9773 
9774   // Adjust scalar if desired.
9775   if (Scalar) {
9776     if (ScalarCast != CK_NoOp)
9777       *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
9778     *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
9779   }
9780   return false;
9781 }
9782 
9783 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
9784                                    SourceLocation Loc, bool IsCompAssign,
9785                                    bool AllowBothBool,
9786                                    bool AllowBoolConversions) {
9787   if (!IsCompAssign) {
9788     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
9789     if (LHS.isInvalid())
9790       return QualType();
9791   }
9792   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
9793   if (RHS.isInvalid())
9794     return QualType();
9795 
9796   // For conversion purposes, we ignore any qualifiers.
9797   // For example, "const float" and "float" are equivalent.
9798   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
9799   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
9800 
9801   const VectorType *LHSVecType = LHSType->getAs<VectorType>();
9802   const VectorType *RHSVecType = RHSType->getAs<VectorType>();
9803   assert(LHSVecType || RHSVecType);
9804 
9805   // AltiVec-style "vector bool op vector bool" combinations are allowed
9806   // for some operators but not others.
9807   if (!AllowBothBool &&
9808       LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
9809       RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
9810     return InvalidOperands(Loc, LHS, RHS);
9811 
9812   // If the vector types are identical, return.
9813   if (Context.hasSameType(LHSType, RHSType))
9814     return LHSType;
9815 
9816   // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
9817   if (LHSVecType && RHSVecType &&
9818       Context.areCompatibleVectorTypes(LHSType, RHSType)) {
9819     if (isa<ExtVectorType>(LHSVecType)) {
9820       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9821       return LHSType;
9822     }
9823 
9824     if (!IsCompAssign)
9825       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
9826     return RHSType;
9827   }
9828 
9829   // AllowBoolConversions says that bool and non-bool AltiVec vectors
9830   // can be mixed, with the result being the non-bool type.  The non-bool
9831   // operand must have integer element type.
9832   if (AllowBoolConversions && LHSVecType && RHSVecType &&
9833       LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
9834       (Context.getTypeSize(LHSVecType->getElementType()) ==
9835        Context.getTypeSize(RHSVecType->getElementType()))) {
9836     if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
9837         LHSVecType->getElementType()->isIntegerType() &&
9838         RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
9839       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9840       return LHSType;
9841     }
9842     if (!IsCompAssign &&
9843         LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
9844         RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
9845         RHSVecType->getElementType()->isIntegerType()) {
9846       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
9847       return RHSType;
9848     }
9849   }
9850 
9851   // If there's a vector type and a scalar, try to convert the scalar to
9852   // the vector element type and splat.
9853   unsigned DiagID = diag::err_typecheck_vector_not_convertable;
9854   if (!RHSVecType) {
9855     if (isa<ExtVectorType>(LHSVecType)) {
9856       if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
9857                                     LHSVecType->getElementType(), LHSType,
9858                                     DiagID))
9859         return LHSType;
9860     } else {
9861       if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
9862         return LHSType;
9863     }
9864   }
9865   if (!LHSVecType) {
9866     if (isa<ExtVectorType>(RHSVecType)) {
9867       if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
9868                                     LHSType, RHSVecType->getElementType(),
9869                                     RHSType, DiagID))
9870         return RHSType;
9871     } else {
9872       if (LHS.get()->getValueKind() == VK_LValue ||
9873           !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
9874         return RHSType;
9875     }
9876   }
9877 
9878   // FIXME: The code below also handles conversion between vectors and
9879   // non-scalars, we should break this down into fine grained specific checks
9880   // and emit proper diagnostics.
9881   QualType VecType = LHSVecType ? LHSType : RHSType;
9882   const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
9883   QualType OtherType = LHSVecType ? RHSType : LHSType;
9884   ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
9885   if (isLaxVectorConversion(OtherType, VecType)) {
9886     // If we're allowing lax vector conversions, only the total (data) size
9887     // needs to be the same. For non compound assignment, if one of the types is
9888     // scalar, the result is always the vector type.
9889     if (!IsCompAssign) {
9890       *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
9891       return VecType;
9892     // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
9893     // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
9894     // type. Note that this is already done by non-compound assignments in
9895     // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
9896     // <1 x T> -> T. The result is also a vector type.
9897     } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
9898                (OtherType->isScalarType() && VT->getNumElements() == 1)) {
9899       ExprResult *RHSExpr = &RHS;
9900       *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
9901       return VecType;
9902     }
9903   }
9904 
9905   // Okay, the expression is invalid.
9906 
9907   // If there's a non-vector, non-real operand, diagnose that.
9908   if ((!RHSVecType && !RHSType->isRealType()) ||
9909       (!LHSVecType && !LHSType->isRealType())) {
9910     Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
9911       << LHSType << RHSType
9912       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9913     return QualType();
9914   }
9915 
9916   // OpenCL V1.1 6.2.6.p1:
9917   // If the operands are of more than one vector type, then an error shall
9918   // occur. Implicit conversions between vector types are not permitted, per
9919   // section 6.2.1.
9920   if (getLangOpts().OpenCL &&
9921       RHSVecType && isa<ExtVectorType>(RHSVecType) &&
9922       LHSVecType && isa<ExtVectorType>(LHSVecType)) {
9923     Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
9924                                                            << RHSType;
9925     return QualType();
9926   }
9927 
9928 
9929   // If there is a vector type that is not a ExtVector and a scalar, we reach
9930   // this point if scalar could not be converted to the vector's element type
9931   // without truncation.
9932   if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
9933       (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
9934     QualType Scalar = LHSVecType ? RHSType : LHSType;
9935     QualType Vector = LHSVecType ? LHSType : RHSType;
9936     unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
9937     Diag(Loc,
9938          diag::err_typecheck_vector_not_convertable_implict_truncation)
9939         << ScalarOrVector << Scalar << Vector;
9940 
9941     return QualType();
9942   }
9943 
9944   // Otherwise, use the generic diagnostic.
9945   Diag(Loc, DiagID)
9946     << LHSType << RHSType
9947     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9948   return QualType();
9949 }
9950 
9951 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
9952 // expression.  These are mainly cases where the null pointer is used as an
9953 // integer instead of a pointer.
9954 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
9955                                 SourceLocation Loc, bool IsCompare) {
9956   // The canonical way to check for a GNU null is with isNullPointerConstant,
9957   // but we use a bit of a hack here for speed; this is a relatively
9958   // hot path, and isNullPointerConstant is slow.
9959   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
9960   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
9961 
9962   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
9963 
9964   // Avoid analyzing cases where the result will either be invalid (and
9965   // diagnosed as such) or entirely valid and not something to warn about.
9966   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
9967       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
9968     return;
9969 
9970   // Comparison operations would not make sense with a null pointer no matter
9971   // what the other expression is.
9972   if (!IsCompare) {
9973     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
9974         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
9975         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
9976     return;
9977   }
9978 
9979   // The rest of the operations only make sense with a null pointer
9980   // if the other expression is a pointer.
9981   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
9982       NonNullType->canDecayToPointerType())
9983     return;
9984 
9985   S.Diag(Loc, diag::warn_null_in_comparison_operation)
9986       << LHSNull /* LHS is NULL */ << NonNullType
9987       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9988 }
9989 
9990 static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS,
9991                                           SourceLocation Loc) {
9992   const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS);
9993   const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS);
9994   if (!LUE || !RUE)
9995     return;
9996   if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
9997       RUE->getKind() != UETT_SizeOf)
9998     return;
9999 
10000   const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens();
10001   QualType LHSTy = LHSArg->getType();
10002   QualType RHSTy;
10003 
10004   if (RUE->isArgumentType())
10005     RHSTy = RUE->getArgumentType();
10006   else
10007     RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
10008 
10009   if (LHSTy->isPointerType() && !RHSTy->isPointerType()) {
10010     if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy))
10011       return;
10012 
10013     S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
10014     if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
10015       if (const ValueDecl *LHSArgDecl = DRE->getDecl())
10016         S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here)
10017             << LHSArgDecl;
10018     }
10019   } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) {
10020     QualType ArrayElemTy = ArrayTy->getElementType();
10021     if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) ||
10022         ArrayElemTy->isDependentType() || RHSTy->isDependentType() ||
10023         ArrayElemTy->isCharType() ||
10024         S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy))
10025       return;
10026     S.Diag(Loc, diag::warn_division_sizeof_array)
10027         << LHSArg->getSourceRange() << ArrayElemTy << RHSTy;
10028     if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
10029       if (const ValueDecl *LHSArgDecl = DRE->getDecl())
10030         S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here)
10031             << LHSArgDecl;
10032     }
10033 
10034     S.Diag(Loc, diag::note_precedence_silence) << RHS;
10035   }
10036 }
10037 
10038 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
10039                                                ExprResult &RHS,
10040                                                SourceLocation Loc, bool IsDiv) {
10041   // Check for division/remainder by zero.
10042   Expr::EvalResult RHSValue;
10043   if (!RHS.get()->isValueDependent() &&
10044       RHS.get()->EvaluateAsInt(RHSValue, S.Context) &&
10045       RHSValue.Val.getInt() == 0)
10046     S.DiagRuntimeBehavior(Loc, RHS.get(),
10047                           S.PDiag(diag::warn_remainder_division_by_zero)
10048                             << IsDiv << RHS.get()->getSourceRange());
10049 }
10050 
10051 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
10052                                            SourceLocation Loc,
10053                                            bool IsCompAssign, bool IsDiv) {
10054   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10055 
10056   if (LHS.get()->getType()->isVectorType() ||
10057       RHS.get()->getType()->isVectorType())
10058     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10059                                /*AllowBothBool*/getLangOpts().AltiVec,
10060                                /*AllowBoolConversions*/false);
10061 
10062   QualType compType = UsualArithmeticConversions(
10063       LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
10064   if (LHS.isInvalid() || RHS.isInvalid())
10065     return QualType();
10066 
10067 
10068   if (compType.isNull() || !compType->isArithmeticType())
10069     return InvalidOperands(Loc, LHS, RHS);
10070   if (IsDiv) {
10071     DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
10072     DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc);
10073   }
10074   return compType;
10075 }
10076 
10077 QualType Sema::CheckRemainderOperands(
10078   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
10079   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10080 
10081   if (LHS.get()->getType()->isVectorType() ||
10082       RHS.get()->getType()->isVectorType()) {
10083     if (LHS.get()->getType()->hasIntegerRepresentation() &&
10084         RHS.get()->getType()->hasIntegerRepresentation())
10085       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10086                                  /*AllowBothBool*/getLangOpts().AltiVec,
10087                                  /*AllowBoolConversions*/false);
10088     return InvalidOperands(Loc, LHS, RHS);
10089   }
10090 
10091   QualType compType = UsualArithmeticConversions(
10092       LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
10093   if (LHS.isInvalid() || RHS.isInvalid())
10094     return QualType();
10095 
10096   if (compType.isNull() || !compType->isIntegerType())
10097     return InvalidOperands(Loc, LHS, RHS);
10098   DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
10099   return compType;
10100 }
10101 
10102 /// Diagnose invalid arithmetic on two void pointers.
10103 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
10104                                                 Expr *LHSExpr, Expr *RHSExpr) {
10105   S.Diag(Loc, S.getLangOpts().CPlusPlus
10106                 ? diag::err_typecheck_pointer_arith_void_type
10107                 : diag::ext_gnu_void_ptr)
10108     << 1 /* two pointers */ << LHSExpr->getSourceRange()
10109                             << RHSExpr->getSourceRange();
10110 }
10111 
10112 /// Diagnose invalid arithmetic on a void pointer.
10113 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
10114                                             Expr *Pointer) {
10115   S.Diag(Loc, S.getLangOpts().CPlusPlus
10116                 ? diag::err_typecheck_pointer_arith_void_type
10117                 : diag::ext_gnu_void_ptr)
10118     << 0 /* one pointer */ << Pointer->getSourceRange();
10119 }
10120 
10121 /// Diagnose invalid arithmetic on a null pointer.
10122 ///
10123 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
10124 /// idiom, which we recognize as a GNU extension.
10125 ///
10126 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc,
10127                                             Expr *Pointer, bool IsGNUIdiom) {
10128   if (IsGNUIdiom)
10129     S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
10130       << Pointer->getSourceRange();
10131   else
10132     S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
10133       << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
10134 }
10135 
10136 /// Diagnose invalid arithmetic on two function pointers.
10137 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
10138                                                     Expr *LHS, Expr *RHS) {
10139   assert(LHS->getType()->isAnyPointerType());
10140   assert(RHS->getType()->isAnyPointerType());
10141   S.Diag(Loc, S.getLangOpts().CPlusPlus
10142                 ? diag::err_typecheck_pointer_arith_function_type
10143                 : diag::ext_gnu_ptr_func_arith)
10144     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
10145     // We only show the second type if it differs from the first.
10146     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
10147                                                    RHS->getType())
10148     << RHS->getType()->getPointeeType()
10149     << LHS->getSourceRange() << RHS->getSourceRange();
10150 }
10151 
10152 /// Diagnose invalid arithmetic on a function pointer.
10153 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
10154                                                 Expr *Pointer) {
10155   assert(Pointer->getType()->isAnyPointerType());
10156   S.Diag(Loc, S.getLangOpts().CPlusPlus
10157                 ? diag::err_typecheck_pointer_arith_function_type
10158                 : diag::ext_gnu_ptr_func_arith)
10159     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
10160     << 0 /* one pointer, so only one type */
10161     << Pointer->getSourceRange();
10162 }
10163 
10164 /// Emit error if Operand is incomplete pointer type
10165 ///
10166 /// \returns True if pointer has incomplete type
10167 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
10168                                                  Expr *Operand) {
10169   QualType ResType = Operand->getType();
10170   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10171     ResType = ResAtomicType->getValueType();
10172 
10173   assert(ResType->isAnyPointerType() && !ResType->isDependentType());
10174   QualType PointeeTy = ResType->getPointeeType();
10175   return S.RequireCompleteSizedType(
10176       Loc, PointeeTy,
10177       diag::err_typecheck_arithmetic_incomplete_or_sizeless_type,
10178       Operand->getSourceRange());
10179 }
10180 
10181 /// Check the validity of an arithmetic pointer operand.
10182 ///
10183 /// If the operand has pointer type, this code will check for pointer types
10184 /// which are invalid in arithmetic operations. These will be diagnosed
10185 /// appropriately, including whether or not the use is supported as an
10186 /// extension.
10187 ///
10188 /// \returns True when the operand is valid to use (even if as an extension).
10189 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
10190                                             Expr *Operand) {
10191   QualType ResType = Operand->getType();
10192   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10193     ResType = ResAtomicType->getValueType();
10194 
10195   if (!ResType->isAnyPointerType()) return true;
10196 
10197   QualType PointeeTy = ResType->getPointeeType();
10198   if (PointeeTy->isVoidType()) {
10199     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
10200     return !S.getLangOpts().CPlusPlus;
10201   }
10202   if (PointeeTy->isFunctionType()) {
10203     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
10204     return !S.getLangOpts().CPlusPlus;
10205   }
10206 
10207   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
10208 
10209   return true;
10210 }
10211 
10212 /// Check the validity of a binary arithmetic operation w.r.t. pointer
10213 /// operands.
10214 ///
10215 /// This routine will diagnose any invalid arithmetic on pointer operands much
10216 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
10217 /// for emitting a single diagnostic even for operations where both LHS and RHS
10218 /// are (potentially problematic) pointers.
10219 ///
10220 /// \returns True when the operand is valid to use (even if as an extension).
10221 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
10222                                                 Expr *LHSExpr, Expr *RHSExpr) {
10223   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
10224   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
10225   if (!isLHSPointer && !isRHSPointer) return true;
10226 
10227   QualType LHSPointeeTy, RHSPointeeTy;
10228   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
10229   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
10230 
10231   // if both are pointers check if operation is valid wrt address spaces
10232   if (isLHSPointer && isRHSPointer) {
10233     if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy)) {
10234       S.Diag(Loc,
10235              diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
10236           << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
10237           << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
10238       return false;
10239     }
10240   }
10241 
10242   // Check for arithmetic on pointers to incomplete types.
10243   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
10244   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
10245   if (isLHSVoidPtr || isRHSVoidPtr) {
10246     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
10247     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
10248     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
10249 
10250     return !S.getLangOpts().CPlusPlus;
10251   }
10252 
10253   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
10254   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
10255   if (isLHSFuncPtr || isRHSFuncPtr) {
10256     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
10257     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
10258                                                                 RHSExpr);
10259     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
10260 
10261     return !S.getLangOpts().CPlusPlus;
10262   }
10263 
10264   if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
10265     return false;
10266   if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
10267     return false;
10268 
10269   return true;
10270 }
10271 
10272 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
10273 /// literal.
10274 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
10275                                   Expr *LHSExpr, Expr *RHSExpr) {
10276   StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
10277   Expr* IndexExpr = RHSExpr;
10278   if (!StrExpr) {
10279     StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
10280     IndexExpr = LHSExpr;
10281   }
10282 
10283   bool IsStringPlusInt = StrExpr &&
10284       IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
10285   if (!IsStringPlusInt || IndexExpr->isValueDependent())
10286     return;
10287 
10288   SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
10289   Self.Diag(OpLoc, diag::warn_string_plus_int)
10290       << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
10291 
10292   // Only print a fixit for "str" + int, not for int + "str".
10293   if (IndexExpr == RHSExpr) {
10294     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
10295     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
10296         << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
10297         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
10298         << FixItHint::CreateInsertion(EndLoc, "]");
10299   } else
10300     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
10301 }
10302 
10303 /// Emit a warning when adding a char literal to a string.
10304 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
10305                                    Expr *LHSExpr, Expr *RHSExpr) {
10306   const Expr *StringRefExpr = LHSExpr;
10307   const CharacterLiteral *CharExpr =
10308       dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
10309 
10310   if (!CharExpr) {
10311     CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
10312     StringRefExpr = RHSExpr;
10313   }
10314 
10315   if (!CharExpr || !StringRefExpr)
10316     return;
10317 
10318   const QualType StringType = StringRefExpr->getType();
10319 
10320   // Return if not a PointerType.
10321   if (!StringType->isAnyPointerType())
10322     return;
10323 
10324   // Return if not a CharacterType.
10325   if (!StringType->getPointeeType()->isAnyCharacterType())
10326     return;
10327 
10328   ASTContext &Ctx = Self.getASTContext();
10329   SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
10330 
10331   const QualType CharType = CharExpr->getType();
10332   if (!CharType->isAnyCharacterType() &&
10333       CharType->isIntegerType() &&
10334       llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
10335     Self.Diag(OpLoc, diag::warn_string_plus_char)
10336         << DiagRange << Ctx.CharTy;
10337   } else {
10338     Self.Diag(OpLoc, diag::warn_string_plus_char)
10339         << DiagRange << CharExpr->getType();
10340   }
10341 
10342   // Only print a fixit for str + char, not for char + str.
10343   if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
10344     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
10345     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
10346         << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
10347         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
10348         << FixItHint::CreateInsertion(EndLoc, "]");
10349   } else {
10350     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
10351   }
10352 }
10353 
10354 /// Emit error when two pointers are incompatible.
10355 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
10356                                            Expr *LHSExpr, Expr *RHSExpr) {
10357   assert(LHSExpr->getType()->isAnyPointerType());
10358   assert(RHSExpr->getType()->isAnyPointerType());
10359   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
10360     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
10361     << RHSExpr->getSourceRange();
10362 }
10363 
10364 // C99 6.5.6
10365 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
10366                                      SourceLocation Loc, BinaryOperatorKind Opc,
10367                                      QualType* CompLHSTy) {
10368   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10369 
10370   if (LHS.get()->getType()->isVectorType() ||
10371       RHS.get()->getType()->isVectorType()) {
10372     QualType compType = CheckVectorOperands(
10373         LHS, RHS, Loc, CompLHSTy,
10374         /*AllowBothBool*/getLangOpts().AltiVec,
10375         /*AllowBoolConversions*/getLangOpts().ZVector);
10376     if (CompLHSTy) *CompLHSTy = compType;
10377     return compType;
10378   }
10379 
10380   if (LHS.get()->getType()->isConstantMatrixType() ||
10381       RHS.get()->getType()->isConstantMatrixType()) {
10382     return CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
10383   }
10384 
10385   QualType compType = UsualArithmeticConversions(
10386       LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
10387   if (LHS.isInvalid() || RHS.isInvalid())
10388     return QualType();
10389 
10390   // Diagnose "string literal" '+' int and string '+' "char literal".
10391   if (Opc == BO_Add) {
10392     diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
10393     diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
10394   }
10395 
10396   // handle the common case first (both operands are arithmetic).
10397   if (!compType.isNull() && compType->isArithmeticType()) {
10398     if (CompLHSTy) *CompLHSTy = compType;
10399     return compType;
10400   }
10401 
10402   // Type-checking.  Ultimately the pointer's going to be in PExp;
10403   // note that we bias towards the LHS being the pointer.
10404   Expr *PExp = LHS.get(), *IExp = RHS.get();
10405 
10406   bool isObjCPointer;
10407   if (PExp->getType()->isPointerType()) {
10408     isObjCPointer = false;
10409   } else if (PExp->getType()->isObjCObjectPointerType()) {
10410     isObjCPointer = true;
10411   } else {
10412     std::swap(PExp, IExp);
10413     if (PExp->getType()->isPointerType()) {
10414       isObjCPointer = false;
10415     } else if (PExp->getType()->isObjCObjectPointerType()) {
10416       isObjCPointer = true;
10417     } else {
10418       return InvalidOperands(Loc, LHS, RHS);
10419     }
10420   }
10421   assert(PExp->getType()->isAnyPointerType());
10422 
10423   if (!IExp->getType()->isIntegerType())
10424     return InvalidOperands(Loc, LHS, RHS);
10425 
10426   // Adding to a null pointer results in undefined behavior.
10427   if (PExp->IgnoreParenCasts()->isNullPointerConstant(
10428           Context, Expr::NPC_ValueDependentIsNotNull)) {
10429     // In C++ adding zero to a null pointer is defined.
10430     Expr::EvalResult KnownVal;
10431     if (!getLangOpts().CPlusPlus ||
10432         (!IExp->isValueDependent() &&
10433          (!IExp->EvaluateAsInt(KnownVal, Context) ||
10434           KnownVal.Val.getInt() != 0))) {
10435       // Check the conditions to see if this is the 'p = nullptr + n' idiom.
10436       bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension(
10437           Context, BO_Add, PExp, IExp);
10438       diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
10439     }
10440   }
10441 
10442   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
10443     return QualType();
10444 
10445   if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
10446     return QualType();
10447 
10448   // Check array bounds for pointer arithemtic
10449   CheckArrayAccess(PExp, IExp);
10450 
10451   if (CompLHSTy) {
10452     QualType LHSTy = Context.isPromotableBitField(LHS.get());
10453     if (LHSTy.isNull()) {
10454       LHSTy = LHS.get()->getType();
10455       if (LHSTy->isPromotableIntegerType())
10456         LHSTy = Context.getPromotedIntegerType(LHSTy);
10457     }
10458     *CompLHSTy = LHSTy;
10459   }
10460 
10461   return PExp->getType();
10462 }
10463 
10464 // C99 6.5.6
10465 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
10466                                         SourceLocation Loc,
10467                                         QualType* CompLHSTy) {
10468   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10469 
10470   if (LHS.get()->getType()->isVectorType() ||
10471       RHS.get()->getType()->isVectorType()) {
10472     QualType compType = CheckVectorOperands(
10473         LHS, RHS, Loc, CompLHSTy,
10474         /*AllowBothBool*/getLangOpts().AltiVec,
10475         /*AllowBoolConversions*/getLangOpts().ZVector);
10476     if (CompLHSTy) *CompLHSTy = compType;
10477     return compType;
10478   }
10479 
10480   if (LHS.get()->getType()->isConstantMatrixType() ||
10481       RHS.get()->getType()->isConstantMatrixType()) {
10482     return CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
10483   }
10484 
10485   QualType compType = UsualArithmeticConversions(
10486       LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
10487   if (LHS.isInvalid() || RHS.isInvalid())
10488     return QualType();
10489 
10490   // Enforce type constraints: C99 6.5.6p3.
10491 
10492   // Handle the common case first (both operands are arithmetic).
10493   if (!compType.isNull() && compType->isArithmeticType()) {
10494     if (CompLHSTy) *CompLHSTy = compType;
10495     return compType;
10496   }
10497 
10498   // Either ptr - int   or   ptr - ptr.
10499   if (LHS.get()->getType()->isAnyPointerType()) {
10500     QualType lpointee = LHS.get()->getType()->getPointeeType();
10501 
10502     // Diagnose bad cases where we step over interface counts.
10503     if (LHS.get()->getType()->isObjCObjectPointerType() &&
10504         checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
10505       return QualType();
10506 
10507     // The result type of a pointer-int computation is the pointer type.
10508     if (RHS.get()->getType()->isIntegerType()) {
10509       // Subtracting from a null pointer should produce a warning.
10510       // The last argument to the diagnose call says this doesn't match the
10511       // GNU int-to-pointer idiom.
10512       if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context,
10513                                            Expr::NPC_ValueDependentIsNotNull)) {
10514         // In C++ adding zero to a null pointer is defined.
10515         Expr::EvalResult KnownVal;
10516         if (!getLangOpts().CPlusPlus ||
10517             (!RHS.get()->isValueDependent() &&
10518              (!RHS.get()->EvaluateAsInt(KnownVal, Context) ||
10519               KnownVal.Val.getInt() != 0))) {
10520           diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
10521         }
10522       }
10523 
10524       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
10525         return QualType();
10526 
10527       // Check array bounds for pointer arithemtic
10528       CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
10529                        /*AllowOnePastEnd*/true, /*IndexNegated*/true);
10530 
10531       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
10532       return LHS.get()->getType();
10533     }
10534 
10535     // Handle pointer-pointer subtractions.
10536     if (const PointerType *RHSPTy
10537           = RHS.get()->getType()->getAs<PointerType>()) {
10538       QualType rpointee = RHSPTy->getPointeeType();
10539 
10540       if (getLangOpts().CPlusPlus) {
10541         // Pointee types must be the same: C++ [expr.add]
10542         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
10543           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
10544         }
10545       } else {
10546         // Pointee types must be compatible C99 6.5.6p3
10547         if (!Context.typesAreCompatible(
10548                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
10549                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
10550           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
10551           return QualType();
10552         }
10553       }
10554 
10555       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
10556                                                LHS.get(), RHS.get()))
10557         return QualType();
10558 
10559       // FIXME: Add warnings for nullptr - ptr.
10560 
10561       // The pointee type may have zero size.  As an extension, a structure or
10562       // union may have zero size or an array may have zero length.  In this
10563       // case subtraction does not make sense.
10564       if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
10565         CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
10566         if (ElementSize.isZero()) {
10567           Diag(Loc,diag::warn_sub_ptr_zero_size_types)
10568             << rpointee.getUnqualifiedType()
10569             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10570         }
10571       }
10572 
10573       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
10574       return Context.getPointerDiffType();
10575     }
10576   }
10577 
10578   return InvalidOperands(Loc, LHS, RHS);
10579 }
10580 
10581 static bool isScopedEnumerationType(QualType T) {
10582   if (const EnumType *ET = T->getAs<EnumType>())
10583     return ET->getDecl()->isScoped();
10584   return false;
10585 }
10586 
10587 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
10588                                    SourceLocation Loc, BinaryOperatorKind Opc,
10589                                    QualType LHSType) {
10590   // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
10591   // so skip remaining warnings as we don't want to modify values within Sema.
10592   if (S.getLangOpts().OpenCL)
10593     return;
10594 
10595   // Check right/shifter operand
10596   Expr::EvalResult RHSResult;
10597   if (RHS.get()->isValueDependent() ||
10598       !RHS.get()->EvaluateAsInt(RHSResult, S.Context))
10599     return;
10600   llvm::APSInt Right = RHSResult.Val.getInt();
10601 
10602   if (Right.isNegative()) {
10603     S.DiagRuntimeBehavior(Loc, RHS.get(),
10604                           S.PDiag(diag::warn_shift_negative)
10605                             << RHS.get()->getSourceRange());
10606     return;
10607   }
10608 
10609   QualType LHSExprType = LHS.get()->getType();
10610   uint64_t LeftSize = LHSExprType->isExtIntType()
10611                           ? S.Context.getIntWidth(LHSExprType)
10612                           : S.Context.getTypeSize(LHSExprType);
10613   llvm::APInt LeftBits(Right.getBitWidth(), LeftSize);
10614   if (Right.uge(LeftBits)) {
10615     S.DiagRuntimeBehavior(Loc, RHS.get(),
10616                           S.PDiag(diag::warn_shift_gt_typewidth)
10617                             << RHS.get()->getSourceRange());
10618     return;
10619   }
10620 
10621   if (Opc != BO_Shl)
10622     return;
10623 
10624   // When left shifting an ICE which is signed, we can check for overflow which
10625   // according to C++ standards prior to C++2a has undefined behavior
10626   // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one
10627   // more than the maximum value representable in the result type, so never
10628   // warn for those. (FIXME: Unsigned left-shift overflow in a constant
10629   // expression is still probably a bug.)
10630   Expr::EvalResult LHSResult;
10631   if (LHS.get()->isValueDependent() ||
10632       LHSType->hasUnsignedIntegerRepresentation() ||
10633       !LHS.get()->EvaluateAsInt(LHSResult, S.Context))
10634     return;
10635   llvm::APSInt Left = LHSResult.Val.getInt();
10636 
10637   // If LHS does not have a signed type and non-negative value
10638   // then, the behavior is undefined before C++2a. Warn about it.
10639   if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined() &&
10640       !S.getLangOpts().CPlusPlus20) {
10641     S.DiagRuntimeBehavior(Loc, LHS.get(),
10642                           S.PDiag(diag::warn_shift_lhs_negative)
10643                             << LHS.get()->getSourceRange());
10644     return;
10645   }
10646 
10647   llvm::APInt ResultBits =
10648       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
10649   if (LeftBits.uge(ResultBits))
10650     return;
10651   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
10652   Result = Result.shl(Right);
10653 
10654   // Print the bit representation of the signed integer as an unsigned
10655   // hexadecimal number.
10656   SmallString<40> HexResult;
10657   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
10658 
10659   // If we are only missing a sign bit, this is less likely to result in actual
10660   // bugs -- if the result is cast back to an unsigned type, it will have the
10661   // expected value. Thus we place this behind a different warning that can be
10662   // turned off separately if needed.
10663   if (LeftBits == ResultBits - 1) {
10664     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
10665         << HexResult << LHSType
10666         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10667     return;
10668   }
10669 
10670   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
10671     << HexResult.str() << Result.getMinSignedBits() << LHSType
10672     << Left.getBitWidth() << LHS.get()->getSourceRange()
10673     << RHS.get()->getSourceRange();
10674 }
10675 
10676 /// Return the resulting type when a vector is shifted
10677 ///        by a scalar or vector shift amount.
10678 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
10679                                  SourceLocation Loc, bool IsCompAssign) {
10680   // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
10681   if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
10682       !LHS.get()->getType()->isVectorType()) {
10683     S.Diag(Loc, diag::err_shift_rhs_only_vector)
10684       << RHS.get()->getType() << LHS.get()->getType()
10685       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10686     return QualType();
10687   }
10688 
10689   if (!IsCompAssign) {
10690     LHS = S.UsualUnaryConversions(LHS.get());
10691     if (LHS.isInvalid()) return QualType();
10692   }
10693 
10694   RHS = S.UsualUnaryConversions(RHS.get());
10695   if (RHS.isInvalid()) return QualType();
10696 
10697   QualType LHSType = LHS.get()->getType();
10698   // Note that LHS might be a scalar because the routine calls not only in
10699   // OpenCL case.
10700   const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
10701   QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
10702 
10703   // Note that RHS might not be a vector.
10704   QualType RHSType = RHS.get()->getType();
10705   const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
10706   QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
10707 
10708   // The operands need to be integers.
10709   if (!LHSEleType->isIntegerType()) {
10710     S.Diag(Loc, diag::err_typecheck_expect_int)
10711       << LHS.get()->getType() << LHS.get()->getSourceRange();
10712     return QualType();
10713   }
10714 
10715   if (!RHSEleType->isIntegerType()) {
10716     S.Diag(Loc, diag::err_typecheck_expect_int)
10717       << RHS.get()->getType() << RHS.get()->getSourceRange();
10718     return QualType();
10719   }
10720 
10721   if (!LHSVecTy) {
10722     assert(RHSVecTy);
10723     if (IsCompAssign)
10724       return RHSType;
10725     if (LHSEleType != RHSEleType) {
10726       LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
10727       LHSEleType = RHSEleType;
10728     }
10729     QualType VecTy =
10730         S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
10731     LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
10732     LHSType = VecTy;
10733   } else if (RHSVecTy) {
10734     // OpenCL v1.1 s6.3.j says that for vector types, the operators
10735     // are applied component-wise. So if RHS is a vector, then ensure
10736     // that the number of elements is the same as LHS...
10737     if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
10738       S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
10739         << LHS.get()->getType() << RHS.get()->getType()
10740         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10741       return QualType();
10742     }
10743     if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
10744       const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
10745       const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
10746       if (LHSBT != RHSBT &&
10747           S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
10748         S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
10749             << LHS.get()->getType() << RHS.get()->getType()
10750             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10751       }
10752     }
10753   } else {
10754     // ...else expand RHS to match the number of elements in LHS.
10755     QualType VecTy =
10756       S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
10757     RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
10758   }
10759 
10760   return LHSType;
10761 }
10762 
10763 // C99 6.5.7
10764 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
10765                                   SourceLocation Loc, BinaryOperatorKind Opc,
10766                                   bool IsCompAssign) {
10767   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10768 
10769   // Vector shifts promote their scalar inputs to vector type.
10770   if (LHS.get()->getType()->isVectorType() ||
10771       RHS.get()->getType()->isVectorType()) {
10772     if (LangOpts.ZVector) {
10773       // The shift operators for the z vector extensions work basically
10774       // like general shifts, except that neither the LHS nor the RHS is
10775       // allowed to be a "vector bool".
10776       if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
10777         if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
10778           return InvalidOperands(Loc, LHS, RHS);
10779       if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
10780         if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
10781           return InvalidOperands(Loc, LHS, RHS);
10782     }
10783     return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
10784   }
10785 
10786   // Shifts don't perform usual arithmetic conversions, they just do integer
10787   // promotions on each operand. C99 6.5.7p3
10788 
10789   // For the LHS, do usual unary conversions, but then reset them away
10790   // if this is a compound assignment.
10791   ExprResult OldLHS = LHS;
10792   LHS = UsualUnaryConversions(LHS.get());
10793   if (LHS.isInvalid())
10794     return QualType();
10795   QualType LHSType = LHS.get()->getType();
10796   if (IsCompAssign) LHS = OldLHS;
10797 
10798   // The RHS is simpler.
10799   RHS = UsualUnaryConversions(RHS.get());
10800   if (RHS.isInvalid())
10801     return QualType();
10802   QualType RHSType = RHS.get()->getType();
10803 
10804   // C99 6.5.7p2: Each of the operands shall have integer type.
10805   if (!LHSType->hasIntegerRepresentation() ||
10806       !RHSType->hasIntegerRepresentation())
10807     return InvalidOperands(Loc, LHS, RHS);
10808 
10809   // C++0x: Don't allow scoped enums. FIXME: Use something better than
10810   // hasIntegerRepresentation() above instead of this.
10811   if (isScopedEnumerationType(LHSType) ||
10812       isScopedEnumerationType(RHSType)) {
10813     return InvalidOperands(Loc, LHS, RHS);
10814   }
10815   // Sanity-check shift operands
10816   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
10817 
10818   // "The type of the result is that of the promoted left operand."
10819   return LHSType;
10820 }
10821 
10822 /// Diagnose bad pointer comparisons.
10823 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
10824                                               ExprResult &LHS, ExprResult &RHS,
10825                                               bool IsError) {
10826   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
10827                       : diag::ext_typecheck_comparison_of_distinct_pointers)
10828     << LHS.get()->getType() << RHS.get()->getType()
10829     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10830 }
10831 
10832 /// Returns false if the pointers are converted to a composite type,
10833 /// true otherwise.
10834 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
10835                                            ExprResult &LHS, ExprResult &RHS) {
10836   // C++ [expr.rel]p2:
10837   //   [...] Pointer conversions (4.10) and qualification
10838   //   conversions (4.4) are performed on pointer operands (or on
10839   //   a pointer operand and a null pointer constant) to bring
10840   //   them to their composite pointer type. [...]
10841   //
10842   // C++ [expr.eq]p1 uses the same notion for (in)equality
10843   // comparisons of pointers.
10844 
10845   QualType LHSType = LHS.get()->getType();
10846   QualType RHSType = RHS.get()->getType();
10847   assert(LHSType->isPointerType() || RHSType->isPointerType() ||
10848          LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
10849 
10850   QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
10851   if (T.isNull()) {
10852     if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) &&
10853         (RHSType->isAnyPointerType() || RHSType->isMemberPointerType()))
10854       diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
10855     else
10856       S.InvalidOperands(Loc, LHS, RHS);
10857     return true;
10858   }
10859 
10860   return false;
10861 }
10862 
10863 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
10864                                                     ExprResult &LHS,
10865                                                     ExprResult &RHS,
10866                                                     bool IsError) {
10867   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
10868                       : diag::ext_typecheck_comparison_of_fptr_to_void)
10869     << LHS.get()->getType() << RHS.get()->getType()
10870     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10871 }
10872 
10873 static bool isObjCObjectLiteral(ExprResult &E) {
10874   switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
10875   case Stmt::ObjCArrayLiteralClass:
10876   case Stmt::ObjCDictionaryLiteralClass:
10877   case Stmt::ObjCStringLiteralClass:
10878   case Stmt::ObjCBoxedExprClass:
10879     return true;
10880   default:
10881     // Note that ObjCBoolLiteral is NOT an object literal!
10882     return false;
10883   }
10884 }
10885 
10886 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
10887   const ObjCObjectPointerType *Type =
10888     LHS->getType()->getAs<ObjCObjectPointerType>();
10889 
10890   // If this is not actually an Objective-C object, bail out.
10891   if (!Type)
10892     return false;
10893 
10894   // Get the LHS object's interface type.
10895   QualType InterfaceType = Type->getPointeeType();
10896 
10897   // If the RHS isn't an Objective-C object, bail out.
10898   if (!RHS->getType()->isObjCObjectPointerType())
10899     return false;
10900 
10901   // Try to find the -isEqual: method.
10902   Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
10903   ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
10904                                                       InterfaceType,
10905                                                       /*IsInstance=*/true);
10906   if (!Method) {
10907     if (Type->isObjCIdType()) {
10908       // For 'id', just check the global pool.
10909       Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
10910                                                   /*receiverId=*/true);
10911     } else {
10912       // Check protocols.
10913       Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
10914                                              /*IsInstance=*/true);
10915     }
10916   }
10917 
10918   if (!Method)
10919     return false;
10920 
10921   QualType T = Method->parameters()[0]->getType();
10922   if (!T->isObjCObjectPointerType())
10923     return false;
10924 
10925   QualType R = Method->getReturnType();
10926   if (!R->isScalarType())
10927     return false;
10928 
10929   return true;
10930 }
10931 
10932 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
10933   FromE = FromE->IgnoreParenImpCasts();
10934   switch (FromE->getStmtClass()) {
10935     default:
10936       break;
10937     case Stmt::ObjCStringLiteralClass:
10938       // "string literal"
10939       return LK_String;
10940     case Stmt::ObjCArrayLiteralClass:
10941       // "array literal"
10942       return LK_Array;
10943     case Stmt::ObjCDictionaryLiteralClass:
10944       // "dictionary literal"
10945       return LK_Dictionary;
10946     case Stmt::BlockExprClass:
10947       return LK_Block;
10948     case Stmt::ObjCBoxedExprClass: {
10949       Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
10950       switch (Inner->getStmtClass()) {
10951         case Stmt::IntegerLiteralClass:
10952         case Stmt::FloatingLiteralClass:
10953         case Stmt::CharacterLiteralClass:
10954         case Stmt::ObjCBoolLiteralExprClass:
10955         case Stmt::CXXBoolLiteralExprClass:
10956           // "numeric literal"
10957           return LK_Numeric;
10958         case Stmt::ImplicitCastExprClass: {
10959           CastKind CK = cast<CastExpr>(Inner)->getCastKind();
10960           // Boolean literals can be represented by implicit casts.
10961           if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
10962             return LK_Numeric;
10963           break;
10964         }
10965         default:
10966           break;
10967       }
10968       return LK_Boxed;
10969     }
10970   }
10971   return LK_None;
10972 }
10973 
10974 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
10975                                           ExprResult &LHS, ExprResult &RHS,
10976                                           BinaryOperator::Opcode Opc){
10977   Expr *Literal;
10978   Expr *Other;
10979   if (isObjCObjectLiteral(LHS)) {
10980     Literal = LHS.get();
10981     Other = RHS.get();
10982   } else {
10983     Literal = RHS.get();
10984     Other = LHS.get();
10985   }
10986 
10987   // Don't warn on comparisons against nil.
10988   Other = Other->IgnoreParenCasts();
10989   if (Other->isNullPointerConstant(S.getASTContext(),
10990                                    Expr::NPC_ValueDependentIsNotNull))
10991     return;
10992 
10993   // This should be kept in sync with warn_objc_literal_comparison.
10994   // LK_String should always be after the other literals, since it has its own
10995   // warning flag.
10996   Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
10997   assert(LiteralKind != Sema::LK_Block);
10998   if (LiteralKind == Sema::LK_None) {
10999     llvm_unreachable("Unknown Objective-C object literal kind");
11000   }
11001 
11002   if (LiteralKind == Sema::LK_String)
11003     S.Diag(Loc, diag::warn_objc_string_literal_comparison)
11004       << Literal->getSourceRange();
11005   else
11006     S.Diag(Loc, diag::warn_objc_literal_comparison)
11007       << LiteralKind << Literal->getSourceRange();
11008 
11009   if (BinaryOperator::isEqualityOp(Opc) &&
11010       hasIsEqualMethod(S, LHS.get(), RHS.get())) {
11011     SourceLocation Start = LHS.get()->getBeginLoc();
11012     SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc());
11013     CharSourceRange OpRange =
11014       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
11015 
11016     S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
11017       << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
11018       << FixItHint::CreateReplacement(OpRange, " isEqual:")
11019       << FixItHint::CreateInsertion(End, "]");
11020   }
11021 }
11022 
11023 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
11024 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
11025                                            ExprResult &RHS, SourceLocation Loc,
11026                                            BinaryOperatorKind Opc) {
11027   // Check that left hand side is !something.
11028   UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
11029   if (!UO || UO->getOpcode() != UO_LNot) return;
11030 
11031   // Only check if the right hand side is non-bool arithmetic type.
11032   if (RHS.get()->isKnownToHaveBooleanValue()) return;
11033 
11034   // Make sure that the something in !something is not bool.
11035   Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
11036   if (SubExpr->isKnownToHaveBooleanValue()) return;
11037 
11038   // Emit warning.
11039   bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
11040   S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
11041       << Loc << IsBitwiseOp;
11042 
11043   // First note suggest !(x < y)
11044   SourceLocation FirstOpen = SubExpr->getBeginLoc();
11045   SourceLocation FirstClose = RHS.get()->getEndLoc();
11046   FirstClose = S.getLocForEndOfToken(FirstClose);
11047   if (FirstClose.isInvalid())
11048     FirstOpen = SourceLocation();
11049   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
11050       << IsBitwiseOp
11051       << FixItHint::CreateInsertion(FirstOpen, "(")
11052       << FixItHint::CreateInsertion(FirstClose, ")");
11053 
11054   // Second note suggests (!x) < y
11055   SourceLocation SecondOpen = LHS.get()->getBeginLoc();
11056   SourceLocation SecondClose = LHS.get()->getEndLoc();
11057   SecondClose = S.getLocForEndOfToken(SecondClose);
11058   if (SecondClose.isInvalid())
11059     SecondOpen = SourceLocation();
11060   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
11061       << FixItHint::CreateInsertion(SecondOpen, "(")
11062       << FixItHint::CreateInsertion(SecondClose, ")");
11063 }
11064 
11065 // Returns true if E refers to a non-weak array.
11066 static bool checkForArray(const Expr *E) {
11067   const ValueDecl *D = nullptr;
11068   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
11069     D = DR->getDecl();
11070   } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
11071     if (Mem->isImplicitAccess())
11072       D = Mem->getMemberDecl();
11073   }
11074   if (!D)
11075     return false;
11076   return D->getType()->isArrayType() && !D->isWeak();
11077 }
11078 
11079 /// Diagnose some forms of syntactically-obvious tautological comparison.
11080 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc,
11081                                            Expr *LHS, Expr *RHS,
11082                                            BinaryOperatorKind Opc) {
11083   Expr *LHSStripped = LHS->IgnoreParenImpCasts();
11084   Expr *RHSStripped = RHS->IgnoreParenImpCasts();
11085 
11086   QualType LHSType = LHS->getType();
11087   QualType RHSType = RHS->getType();
11088   if (LHSType->hasFloatingRepresentation() ||
11089       (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
11090       S.inTemplateInstantiation())
11091     return;
11092 
11093   // Comparisons between two array types are ill-formed for operator<=>, so
11094   // we shouldn't emit any additional warnings about it.
11095   if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
11096     return;
11097 
11098   // For non-floating point types, check for self-comparisons of the form
11099   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
11100   // often indicate logic errors in the program.
11101   //
11102   // NOTE: Don't warn about comparison expressions resulting from macro
11103   // expansion. Also don't warn about comparisons which are only self
11104   // comparisons within a template instantiation. The warnings should catch
11105   // obvious cases in the definition of the template anyways. The idea is to
11106   // warn when the typed comparison operator will always evaluate to the same
11107   // result.
11108 
11109   // Used for indexing into %select in warn_comparison_always
11110   enum {
11111     AlwaysConstant,
11112     AlwaysTrue,
11113     AlwaysFalse,
11114     AlwaysEqual, // std::strong_ordering::equal from operator<=>
11115   };
11116 
11117   // C++2a [depr.array.comp]:
11118   //   Equality and relational comparisons ([expr.eq], [expr.rel]) between two
11119   //   operands of array type are deprecated.
11120   if (S.getLangOpts().CPlusPlus20 && LHSStripped->getType()->isArrayType() &&
11121       RHSStripped->getType()->isArrayType()) {
11122     S.Diag(Loc, diag::warn_depr_array_comparison)
11123         << LHS->getSourceRange() << RHS->getSourceRange()
11124         << LHSStripped->getType() << RHSStripped->getType();
11125     // Carry on to produce the tautological comparison warning, if this
11126     // expression is potentially-evaluated, we can resolve the array to a
11127     // non-weak declaration, and so on.
11128   }
11129 
11130   if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) {
11131     if (Expr::isSameComparisonOperand(LHS, RHS)) {
11132       unsigned Result;
11133       switch (Opc) {
11134       case BO_EQ:
11135       case BO_LE:
11136       case BO_GE:
11137         Result = AlwaysTrue;
11138         break;
11139       case BO_NE:
11140       case BO_LT:
11141       case BO_GT:
11142         Result = AlwaysFalse;
11143         break;
11144       case BO_Cmp:
11145         Result = AlwaysEqual;
11146         break;
11147       default:
11148         Result = AlwaysConstant;
11149         break;
11150       }
11151       S.DiagRuntimeBehavior(Loc, nullptr,
11152                             S.PDiag(diag::warn_comparison_always)
11153                                 << 0 /*self-comparison*/
11154                                 << Result);
11155     } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) {
11156       // What is it always going to evaluate to?
11157       unsigned Result;
11158       switch (Opc) {
11159       case BO_EQ: // e.g. array1 == array2
11160         Result = AlwaysFalse;
11161         break;
11162       case BO_NE: // e.g. array1 != array2
11163         Result = AlwaysTrue;
11164         break;
11165       default: // e.g. array1 <= array2
11166         // The best we can say is 'a constant'
11167         Result = AlwaysConstant;
11168         break;
11169       }
11170       S.DiagRuntimeBehavior(Loc, nullptr,
11171                             S.PDiag(diag::warn_comparison_always)
11172                                 << 1 /*array comparison*/
11173                                 << Result);
11174     }
11175   }
11176 
11177   if (isa<CastExpr>(LHSStripped))
11178     LHSStripped = LHSStripped->IgnoreParenCasts();
11179   if (isa<CastExpr>(RHSStripped))
11180     RHSStripped = RHSStripped->IgnoreParenCasts();
11181 
11182   // Warn about comparisons against a string constant (unless the other
11183   // operand is null); the user probably wants string comparison function.
11184   Expr *LiteralString = nullptr;
11185   Expr *LiteralStringStripped = nullptr;
11186   if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
11187       !RHSStripped->isNullPointerConstant(S.Context,
11188                                           Expr::NPC_ValueDependentIsNull)) {
11189     LiteralString = LHS;
11190     LiteralStringStripped = LHSStripped;
11191   } else if ((isa<StringLiteral>(RHSStripped) ||
11192               isa<ObjCEncodeExpr>(RHSStripped)) &&
11193              !LHSStripped->isNullPointerConstant(S.Context,
11194                                           Expr::NPC_ValueDependentIsNull)) {
11195     LiteralString = RHS;
11196     LiteralStringStripped = RHSStripped;
11197   }
11198 
11199   if (LiteralString) {
11200     S.DiagRuntimeBehavior(Loc, nullptr,
11201                           S.PDiag(diag::warn_stringcompare)
11202                               << isa<ObjCEncodeExpr>(LiteralStringStripped)
11203                               << LiteralString->getSourceRange());
11204   }
11205 }
11206 
11207 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) {
11208   switch (CK) {
11209   default: {
11210 #ifndef NDEBUG
11211     llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
11212                  << "\n";
11213 #endif
11214     llvm_unreachable("unhandled cast kind");
11215   }
11216   case CK_UserDefinedConversion:
11217     return ICK_Identity;
11218   case CK_LValueToRValue:
11219     return ICK_Lvalue_To_Rvalue;
11220   case CK_ArrayToPointerDecay:
11221     return ICK_Array_To_Pointer;
11222   case CK_FunctionToPointerDecay:
11223     return ICK_Function_To_Pointer;
11224   case CK_IntegralCast:
11225     return ICK_Integral_Conversion;
11226   case CK_FloatingCast:
11227     return ICK_Floating_Conversion;
11228   case CK_IntegralToFloating:
11229   case CK_FloatingToIntegral:
11230     return ICK_Floating_Integral;
11231   case CK_IntegralComplexCast:
11232   case CK_FloatingComplexCast:
11233   case CK_FloatingComplexToIntegralComplex:
11234   case CK_IntegralComplexToFloatingComplex:
11235     return ICK_Complex_Conversion;
11236   case CK_FloatingComplexToReal:
11237   case CK_FloatingRealToComplex:
11238   case CK_IntegralComplexToReal:
11239   case CK_IntegralRealToComplex:
11240     return ICK_Complex_Real;
11241   }
11242 }
11243 
11244 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E,
11245                                              QualType FromType,
11246                                              SourceLocation Loc) {
11247   // Check for a narrowing implicit conversion.
11248   StandardConversionSequence SCS;
11249   SCS.setAsIdentityConversion();
11250   SCS.setToType(0, FromType);
11251   SCS.setToType(1, ToType);
11252   if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
11253     SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
11254 
11255   APValue PreNarrowingValue;
11256   QualType PreNarrowingType;
11257   switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
11258                                PreNarrowingType,
11259                                /*IgnoreFloatToIntegralConversion*/ true)) {
11260   case NK_Dependent_Narrowing:
11261     // Implicit conversion to a narrower type, but the expression is
11262     // value-dependent so we can't tell whether it's actually narrowing.
11263   case NK_Not_Narrowing:
11264     return false;
11265 
11266   case NK_Constant_Narrowing:
11267     // Implicit conversion to a narrower type, and the value is not a constant
11268     // expression.
11269     S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
11270         << /*Constant*/ 1
11271         << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
11272     return true;
11273 
11274   case NK_Variable_Narrowing:
11275     // Implicit conversion to a narrower type, and the value is not a constant
11276     // expression.
11277   case NK_Type_Narrowing:
11278     S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
11279         << /*Constant*/ 0 << FromType << ToType;
11280     // TODO: It's not a constant expression, but what if the user intended it
11281     // to be? Can we produce notes to help them figure out why it isn't?
11282     return true;
11283   }
11284   llvm_unreachable("unhandled case in switch");
11285 }
11286 
11287 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S,
11288                                                          ExprResult &LHS,
11289                                                          ExprResult &RHS,
11290                                                          SourceLocation Loc) {
11291   QualType LHSType = LHS.get()->getType();
11292   QualType RHSType = RHS.get()->getType();
11293   // Dig out the original argument type and expression before implicit casts
11294   // were applied. These are the types/expressions we need to check the
11295   // [expr.spaceship] requirements against.
11296   ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
11297   ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
11298   QualType LHSStrippedType = LHSStripped.get()->getType();
11299   QualType RHSStrippedType = RHSStripped.get()->getType();
11300 
11301   // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
11302   // other is not, the program is ill-formed.
11303   if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
11304     S.InvalidOperands(Loc, LHSStripped, RHSStripped);
11305     return QualType();
11306   }
11307 
11308   // FIXME: Consider combining this with checkEnumArithmeticConversions.
11309   int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
11310                     RHSStrippedType->isEnumeralType();
11311   if (NumEnumArgs == 1) {
11312     bool LHSIsEnum = LHSStrippedType->isEnumeralType();
11313     QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
11314     if (OtherTy->hasFloatingRepresentation()) {
11315       S.InvalidOperands(Loc, LHSStripped, RHSStripped);
11316       return QualType();
11317     }
11318   }
11319   if (NumEnumArgs == 2) {
11320     // C++2a [expr.spaceship]p5: If both operands have the same enumeration
11321     // type E, the operator yields the result of converting the operands
11322     // to the underlying type of E and applying <=> to the converted operands.
11323     if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
11324       S.InvalidOperands(Loc, LHS, RHS);
11325       return QualType();
11326     }
11327     QualType IntType =
11328         LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType();
11329     assert(IntType->isArithmeticType());
11330 
11331     // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
11332     // promote the boolean type, and all other promotable integer types, to
11333     // avoid this.
11334     if (IntType->isPromotableIntegerType())
11335       IntType = S.Context.getPromotedIntegerType(IntType);
11336 
11337     LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
11338     RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
11339     LHSType = RHSType = IntType;
11340   }
11341 
11342   // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
11343   // usual arithmetic conversions are applied to the operands.
11344   QualType Type =
11345       S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison);
11346   if (LHS.isInvalid() || RHS.isInvalid())
11347     return QualType();
11348   if (Type.isNull())
11349     return S.InvalidOperands(Loc, LHS, RHS);
11350 
11351   Optional<ComparisonCategoryType> CCT =
11352       getComparisonCategoryForBuiltinCmp(Type);
11353   if (!CCT)
11354     return S.InvalidOperands(Loc, LHS, RHS);
11355 
11356   bool HasNarrowing = checkThreeWayNarrowingConversion(
11357       S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc());
11358   HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType,
11359                                                    RHS.get()->getBeginLoc());
11360   if (HasNarrowing)
11361     return QualType();
11362 
11363   assert(!Type.isNull() && "composite type for <=> has not been set");
11364 
11365   return S.CheckComparisonCategoryType(
11366       *CCT, Loc, Sema::ComparisonCategoryUsage::OperatorInExpression);
11367 }
11368 
11369 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS,
11370                                                  ExprResult &RHS,
11371                                                  SourceLocation Loc,
11372                                                  BinaryOperatorKind Opc) {
11373   if (Opc == BO_Cmp)
11374     return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
11375 
11376   // C99 6.5.8p3 / C99 6.5.9p4
11377   QualType Type =
11378       S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison);
11379   if (LHS.isInvalid() || RHS.isInvalid())
11380     return QualType();
11381   if (Type.isNull())
11382     return S.InvalidOperands(Loc, LHS, RHS);
11383   assert(Type->isArithmeticType() || Type->isEnumeralType());
11384 
11385   if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc))
11386     return S.InvalidOperands(Loc, LHS, RHS);
11387 
11388   // Check for comparisons of floating point operands using != and ==.
11389   if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc))
11390     S.CheckFloatComparison(Loc, LHS.get(), RHS.get());
11391 
11392   // The result of comparisons is 'bool' in C++, 'int' in C.
11393   return S.Context.getLogicalOperationType();
11394 }
11395 
11396 void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) {
11397   if (!NullE.get()->getType()->isAnyPointerType())
11398     return;
11399   int NullValue = PP.isMacroDefined("NULL") ? 0 : 1;
11400   if (!E.get()->getType()->isAnyPointerType() &&
11401       E.get()->isNullPointerConstant(Context,
11402                                      Expr::NPC_ValueDependentIsNotNull) ==
11403         Expr::NPCK_ZeroExpression) {
11404     if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) {
11405       if (CL->getValue() == 0)
11406         Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
11407             << NullValue
11408             << FixItHint::CreateReplacement(E.get()->getExprLoc(),
11409                                             NullValue ? "NULL" : "(void *)0");
11410     } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) {
11411         TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
11412         QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType();
11413         if (T == Context.CharTy)
11414           Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
11415               << NullValue
11416               << FixItHint::CreateReplacement(E.get()->getExprLoc(),
11417                                               NullValue ? "NULL" : "(void *)0");
11418       }
11419   }
11420 }
11421 
11422 // C99 6.5.8, C++ [expr.rel]
11423 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
11424                                     SourceLocation Loc,
11425                                     BinaryOperatorKind Opc) {
11426   bool IsRelational = BinaryOperator::isRelationalOp(Opc);
11427   bool IsThreeWay = Opc == BO_Cmp;
11428   bool IsOrdered = IsRelational || IsThreeWay;
11429   auto IsAnyPointerType = [](ExprResult E) {
11430     QualType Ty = E.get()->getType();
11431     return Ty->isPointerType() || Ty->isMemberPointerType();
11432   };
11433 
11434   // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
11435   // type, array-to-pointer, ..., conversions are performed on both operands to
11436   // bring them to their composite type.
11437   // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
11438   // any type-related checks.
11439   if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
11440     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
11441     if (LHS.isInvalid())
11442       return QualType();
11443     RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
11444     if (RHS.isInvalid())
11445       return QualType();
11446   } else {
11447     LHS = DefaultLvalueConversion(LHS.get());
11448     if (LHS.isInvalid())
11449       return QualType();
11450     RHS = DefaultLvalueConversion(RHS.get());
11451     if (RHS.isInvalid())
11452       return QualType();
11453   }
11454 
11455   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true);
11456   if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) {
11457     CheckPtrComparisonWithNullChar(LHS, RHS);
11458     CheckPtrComparisonWithNullChar(RHS, LHS);
11459   }
11460 
11461   // Handle vector comparisons separately.
11462   if (LHS.get()->getType()->isVectorType() ||
11463       RHS.get()->getType()->isVectorType())
11464     return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
11465 
11466   diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
11467   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
11468 
11469   QualType LHSType = LHS.get()->getType();
11470   QualType RHSType = RHS.get()->getType();
11471   if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
11472       (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
11473     return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
11474 
11475   const Expr::NullPointerConstantKind LHSNullKind =
11476       LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
11477   const Expr::NullPointerConstantKind RHSNullKind =
11478       RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
11479   bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
11480   bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
11481 
11482   auto computeResultTy = [&]() {
11483     if (Opc != BO_Cmp)
11484       return Context.getLogicalOperationType();
11485     assert(getLangOpts().CPlusPlus);
11486     assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
11487 
11488     QualType CompositeTy = LHS.get()->getType();
11489     assert(!CompositeTy->isReferenceType());
11490 
11491     Optional<ComparisonCategoryType> CCT =
11492         getComparisonCategoryForBuiltinCmp(CompositeTy);
11493     if (!CCT)
11494       return InvalidOperands(Loc, LHS, RHS);
11495 
11496     if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) {
11497       // P0946R0: Comparisons between a null pointer constant and an object
11498       // pointer result in std::strong_equality, which is ill-formed under
11499       // P1959R0.
11500       Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero)
11501           << (LHSIsNull ? LHS.get()->getSourceRange()
11502                         : RHS.get()->getSourceRange());
11503       return QualType();
11504     }
11505 
11506     return CheckComparisonCategoryType(
11507         *CCT, Loc, ComparisonCategoryUsage::OperatorInExpression);
11508   };
11509 
11510   if (!IsOrdered && LHSIsNull != RHSIsNull) {
11511     bool IsEquality = Opc == BO_EQ;
11512     if (RHSIsNull)
11513       DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
11514                                    RHS.get()->getSourceRange());
11515     else
11516       DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
11517                                    LHS.get()->getSourceRange());
11518   }
11519 
11520   if ((LHSType->isIntegerType() && !LHSIsNull) ||
11521       (RHSType->isIntegerType() && !RHSIsNull)) {
11522     // Skip normal pointer conversion checks in this case; we have better
11523     // diagnostics for this below.
11524   } else if (getLangOpts().CPlusPlus) {
11525     // Equality comparison of a function pointer to a void pointer is invalid,
11526     // but we allow it as an extension.
11527     // FIXME: If we really want to allow this, should it be part of composite
11528     // pointer type computation so it works in conditionals too?
11529     if (!IsOrdered &&
11530         ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
11531          (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
11532       // This is a gcc extension compatibility comparison.
11533       // In a SFINAE context, we treat this as a hard error to maintain
11534       // conformance with the C++ standard.
11535       diagnoseFunctionPointerToVoidComparison(
11536           *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
11537 
11538       if (isSFINAEContext())
11539         return QualType();
11540 
11541       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
11542       return computeResultTy();
11543     }
11544 
11545     // C++ [expr.eq]p2:
11546     //   If at least one operand is a pointer [...] bring them to their
11547     //   composite pointer type.
11548     // C++ [expr.spaceship]p6
11549     //  If at least one of the operands is of pointer type, [...] bring them
11550     //  to their composite pointer type.
11551     // C++ [expr.rel]p2:
11552     //   If both operands are pointers, [...] bring them to their composite
11553     //   pointer type.
11554     // For <=>, the only valid non-pointer types are arrays and functions, and
11555     // we already decayed those, so this is really the same as the relational
11556     // comparison rule.
11557     if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
11558             (IsOrdered ? 2 : 1) &&
11559         (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
11560                                          RHSType->isObjCObjectPointerType()))) {
11561       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
11562         return QualType();
11563       return computeResultTy();
11564     }
11565   } else if (LHSType->isPointerType() &&
11566              RHSType->isPointerType()) { // C99 6.5.8p2
11567     // All of the following pointer-related warnings are GCC extensions, except
11568     // when handling null pointer constants.
11569     QualType LCanPointeeTy =
11570       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
11571     QualType RCanPointeeTy =
11572       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
11573 
11574     // C99 6.5.9p2 and C99 6.5.8p2
11575     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
11576                                    RCanPointeeTy.getUnqualifiedType())) {
11577       // Valid unless a relational comparison of function pointers
11578       if (IsRelational && LCanPointeeTy->isFunctionType()) {
11579         Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
11580           << LHSType << RHSType << LHS.get()->getSourceRange()
11581           << RHS.get()->getSourceRange();
11582       }
11583     } else if (!IsRelational &&
11584                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
11585       // Valid unless comparison between non-null pointer and function pointer
11586       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
11587           && !LHSIsNull && !RHSIsNull)
11588         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
11589                                                 /*isError*/false);
11590     } else {
11591       // Invalid
11592       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
11593     }
11594     if (LCanPointeeTy != RCanPointeeTy) {
11595       // Treat NULL constant as a special case in OpenCL.
11596       if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
11597         if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy)) {
11598           Diag(Loc,
11599                diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
11600               << LHSType << RHSType << 0 /* comparison */
11601               << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11602         }
11603       }
11604       LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
11605       LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
11606       CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
11607                                                : CK_BitCast;
11608       if (LHSIsNull && !RHSIsNull)
11609         LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
11610       else
11611         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
11612     }
11613     return computeResultTy();
11614   }
11615 
11616   if (getLangOpts().CPlusPlus) {
11617     // C++ [expr.eq]p4:
11618     //   Two operands of type std::nullptr_t or one operand of type
11619     //   std::nullptr_t and the other a null pointer constant compare equal.
11620     if (!IsOrdered && LHSIsNull && RHSIsNull) {
11621       if (LHSType->isNullPtrType()) {
11622         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11623         return computeResultTy();
11624       }
11625       if (RHSType->isNullPtrType()) {
11626         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11627         return computeResultTy();
11628       }
11629     }
11630 
11631     // Comparison of Objective-C pointers and block pointers against nullptr_t.
11632     // These aren't covered by the composite pointer type rules.
11633     if (!IsOrdered && RHSType->isNullPtrType() &&
11634         (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
11635       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11636       return computeResultTy();
11637     }
11638     if (!IsOrdered && LHSType->isNullPtrType() &&
11639         (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
11640       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11641       return computeResultTy();
11642     }
11643 
11644     if (IsRelational &&
11645         ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
11646          (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
11647       // HACK: Relational comparison of nullptr_t against a pointer type is
11648       // invalid per DR583, but we allow it within std::less<> and friends,
11649       // since otherwise common uses of it break.
11650       // FIXME: Consider removing this hack once LWG fixes std::less<> and
11651       // friends to have std::nullptr_t overload candidates.
11652       DeclContext *DC = CurContext;
11653       if (isa<FunctionDecl>(DC))
11654         DC = DC->getParent();
11655       if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
11656         if (CTSD->isInStdNamespace() &&
11657             llvm::StringSwitch<bool>(CTSD->getName())
11658                 .Cases("less", "less_equal", "greater", "greater_equal", true)
11659                 .Default(false)) {
11660           if (RHSType->isNullPtrType())
11661             RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11662           else
11663             LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11664           return computeResultTy();
11665         }
11666       }
11667     }
11668 
11669     // C++ [expr.eq]p2:
11670     //   If at least one operand is a pointer to member, [...] bring them to
11671     //   their composite pointer type.
11672     if (!IsOrdered &&
11673         (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
11674       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
11675         return QualType();
11676       else
11677         return computeResultTy();
11678     }
11679   }
11680 
11681   // Handle block pointer types.
11682   if (!IsOrdered && LHSType->isBlockPointerType() &&
11683       RHSType->isBlockPointerType()) {
11684     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
11685     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
11686 
11687     if (!LHSIsNull && !RHSIsNull &&
11688         !Context.typesAreCompatible(lpointee, rpointee)) {
11689       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
11690         << LHSType << RHSType << LHS.get()->getSourceRange()
11691         << RHS.get()->getSourceRange();
11692     }
11693     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
11694     return computeResultTy();
11695   }
11696 
11697   // Allow block pointers to be compared with null pointer constants.
11698   if (!IsOrdered
11699       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
11700           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
11701     if (!LHSIsNull && !RHSIsNull) {
11702       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
11703              ->getPointeeType()->isVoidType())
11704             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
11705                 ->getPointeeType()->isVoidType())))
11706         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
11707           << LHSType << RHSType << LHS.get()->getSourceRange()
11708           << RHS.get()->getSourceRange();
11709     }
11710     if (LHSIsNull && !RHSIsNull)
11711       LHS = ImpCastExprToType(LHS.get(), RHSType,
11712                               RHSType->isPointerType() ? CK_BitCast
11713                                 : CK_AnyPointerToBlockPointerCast);
11714     else
11715       RHS = ImpCastExprToType(RHS.get(), LHSType,
11716                               LHSType->isPointerType() ? CK_BitCast
11717                                 : CK_AnyPointerToBlockPointerCast);
11718     return computeResultTy();
11719   }
11720 
11721   if (LHSType->isObjCObjectPointerType() ||
11722       RHSType->isObjCObjectPointerType()) {
11723     const PointerType *LPT = LHSType->getAs<PointerType>();
11724     const PointerType *RPT = RHSType->getAs<PointerType>();
11725     if (LPT || RPT) {
11726       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
11727       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
11728 
11729       if (!LPtrToVoid && !RPtrToVoid &&
11730           !Context.typesAreCompatible(LHSType, RHSType)) {
11731         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
11732                                           /*isError*/false);
11733       }
11734       // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than
11735       // the RHS, but we have test coverage for this behavior.
11736       // FIXME: Consider using convertPointersToCompositeType in C++.
11737       if (LHSIsNull && !RHSIsNull) {
11738         Expr *E = LHS.get();
11739         if (getLangOpts().ObjCAutoRefCount)
11740           CheckObjCConversion(SourceRange(), RHSType, E,
11741                               CCK_ImplicitConversion);
11742         LHS = ImpCastExprToType(E, RHSType,
11743                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
11744       }
11745       else {
11746         Expr *E = RHS.get();
11747         if (getLangOpts().ObjCAutoRefCount)
11748           CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion,
11749                               /*Diagnose=*/true,
11750                               /*DiagnoseCFAudited=*/false, Opc);
11751         RHS = ImpCastExprToType(E, LHSType,
11752                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
11753       }
11754       return computeResultTy();
11755     }
11756     if (LHSType->isObjCObjectPointerType() &&
11757         RHSType->isObjCObjectPointerType()) {
11758       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
11759         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
11760                                           /*isError*/false);
11761       if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
11762         diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
11763 
11764       if (LHSIsNull && !RHSIsNull)
11765         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
11766       else
11767         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
11768       return computeResultTy();
11769     }
11770 
11771     if (!IsOrdered && LHSType->isBlockPointerType() &&
11772         RHSType->isBlockCompatibleObjCPointerType(Context)) {
11773       LHS = ImpCastExprToType(LHS.get(), RHSType,
11774                               CK_BlockPointerToObjCPointerCast);
11775       return computeResultTy();
11776     } else if (!IsOrdered &&
11777                LHSType->isBlockCompatibleObjCPointerType(Context) &&
11778                RHSType->isBlockPointerType()) {
11779       RHS = ImpCastExprToType(RHS.get(), LHSType,
11780                               CK_BlockPointerToObjCPointerCast);
11781       return computeResultTy();
11782     }
11783   }
11784   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
11785       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
11786     unsigned DiagID = 0;
11787     bool isError = false;
11788     if (LangOpts.DebuggerSupport) {
11789       // Under a debugger, allow the comparison of pointers to integers,
11790       // since users tend to want to compare addresses.
11791     } else if ((LHSIsNull && LHSType->isIntegerType()) ||
11792                (RHSIsNull && RHSType->isIntegerType())) {
11793       if (IsOrdered) {
11794         isError = getLangOpts().CPlusPlus;
11795         DiagID =
11796           isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
11797                   : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
11798       }
11799     } else if (getLangOpts().CPlusPlus) {
11800       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
11801       isError = true;
11802     } else if (IsOrdered)
11803       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
11804     else
11805       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
11806 
11807     if (DiagID) {
11808       Diag(Loc, DiagID)
11809         << LHSType << RHSType << LHS.get()->getSourceRange()
11810         << RHS.get()->getSourceRange();
11811       if (isError)
11812         return QualType();
11813     }
11814 
11815     if (LHSType->isIntegerType())
11816       LHS = ImpCastExprToType(LHS.get(), RHSType,
11817                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
11818     else
11819       RHS = ImpCastExprToType(RHS.get(), LHSType,
11820                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
11821     return computeResultTy();
11822   }
11823 
11824   // Handle block pointers.
11825   if (!IsOrdered && RHSIsNull
11826       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
11827     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11828     return computeResultTy();
11829   }
11830   if (!IsOrdered && LHSIsNull
11831       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
11832     LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11833     return computeResultTy();
11834   }
11835 
11836   if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) {
11837     if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
11838       return computeResultTy();
11839     }
11840 
11841     if (LHSType->isQueueT() && RHSType->isQueueT()) {
11842       return computeResultTy();
11843     }
11844 
11845     if (LHSIsNull && RHSType->isQueueT()) {
11846       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11847       return computeResultTy();
11848     }
11849 
11850     if (LHSType->isQueueT() && RHSIsNull) {
11851       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11852       return computeResultTy();
11853     }
11854   }
11855 
11856   return InvalidOperands(Loc, LHS, RHS);
11857 }
11858 
11859 // Return a signed ext_vector_type that is of identical size and number of
11860 // elements. For floating point vectors, return an integer type of identical
11861 // size and number of elements. In the non ext_vector_type case, search from
11862 // the largest type to the smallest type to avoid cases where long long == long,
11863 // where long gets picked over long long.
11864 QualType Sema::GetSignedVectorType(QualType V) {
11865   const VectorType *VTy = V->castAs<VectorType>();
11866   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
11867 
11868   if (isa<ExtVectorType>(VTy)) {
11869     if (TypeSize == Context.getTypeSize(Context.CharTy))
11870       return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
11871     else if (TypeSize == Context.getTypeSize(Context.ShortTy))
11872       return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
11873     else if (TypeSize == Context.getTypeSize(Context.IntTy))
11874       return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
11875     else if (TypeSize == Context.getTypeSize(Context.LongTy))
11876       return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
11877     assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
11878            "Unhandled vector element size in vector compare");
11879     return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
11880   }
11881 
11882   if (TypeSize == Context.getTypeSize(Context.LongLongTy))
11883     return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
11884                                  VectorType::GenericVector);
11885   else if (TypeSize == Context.getTypeSize(Context.LongTy))
11886     return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
11887                                  VectorType::GenericVector);
11888   else if (TypeSize == Context.getTypeSize(Context.IntTy))
11889     return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
11890                                  VectorType::GenericVector);
11891   else if (TypeSize == Context.getTypeSize(Context.ShortTy))
11892     return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
11893                                  VectorType::GenericVector);
11894   assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
11895          "Unhandled vector element size in vector compare");
11896   return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
11897                                VectorType::GenericVector);
11898 }
11899 
11900 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
11901 /// operates on extended vector types.  Instead of producing an IntTy result,
11902 /// like a scalar comparison, a vector comparison produces a vector of integer
11903 /// types.
11904 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
11905                                           SourceLocation Loc,
11906                                           BinaryOperatorKind Opc) {
11907   if (Opc == BO_Cmp) {
11908     Diag(Loc, diag::err_three_way_vector_comparison);
11909     return QualType();
11910   }
11911 
11912   // Check to make sure we're operating on vectors of the same type and width,
11913   // Allowing one side to be a scalar of element type.
11914   QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
11915                               /*AllowBothBool*/true,
11916                               /*AllowBoolConversions*/getLangOpts().ZVector);
11917   if (vType.isNull())
11918     return vType;
11919 
11920   QualType LHSType = LHS.get()->getType();
11921 
11922   // If AltiVec, the comparison results in a numeric type, i.e.
11923   // bool for C++, int for C
11924   if (getLangOpts().AltiVec &&
11925       vType->castAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
11926     return Context.getLogicalOperationType();
11927 
11928   // For non-floating point types, check for self-comparisons of the form
11929   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
11930   // often indicate logic errors in the program.
11931   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
11932 
11933   // Check for comparisons of floating point operands using != and ==.
11934   if (BinaryOperator::isEqualityOp(Opc) &&
11935       LHSType->hasFloatingRepresentation()) {
11936     assert(RHS.get()->getType()->hasFloatingRepresentation());
11937     CheckFloatComparison(Loc, LHS.get(), RHS.get());
11938   }
11939 
11940   // Return a signed type for the vector.
11941   return GetSignedVectorType(vType);
11942 }
11943 
11944 static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS,
11945                                     const ExprResult &XorRHS,
11946                                     const SourceLocation Loc) {
11947   // Do not diagnose macros.
11948   if (Loc.isMacroID())
11949     return;
11950 
11951   bool Negative = false;
11952   bool ExplicitPlus = false;
11953   const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get());
11954   const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get());
11955 
11956   if (!LHSInt)
11957     return;
11958   if (!RHSInt) {
11959     // Check negative literals.
11960     if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) {
11961       UnaryOperatorKind Opc = UO->getOpcode();
11962       if (Opc != UO_Minus && Opc != UO_Plus)
11963         return;
11964       RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr());
11965       if (!RHSInt)
11966         return;
11967       Negative = (Opc == UO_Minus);
11968       ExplicitPlus = !Negative;
11969     } else {
11970       return;
11971     }
11972   }
11973 
11974   const llvm::APInt &LeftSideValue = LHSInt->getValue();
11975   llvm::APInt RightSideValue = RHSInt->getValue();
11976   if (LeftSideValue != 2 && LeftSideValue != 10)
11977     return;
11978 
11979   if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth())
11980     return;
11981 
11982   CharSourceRange ExprRange = CharSourceRange::getCharRange(
11983       LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation()));
11984   llvm::StringRef ExprStr =
11985       Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts());
11986 
11987   CharSourceRange XorRange =
11988       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
11989   llvm::StringRef XorStr =
11990       Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts());
11991   // Do not diagnose if xor keyword/macro is used.
11992   if (XorStr == "xor")
11993     return;
11994 
11995   std::string LHSStr = std::string(Lexer::getSourceText(
11996       CharSourceRange::getTokenRange(LHSInt->getSourceRange()),
11997       S.getSourceManager(), S.getLangOpts()));
11998   std::string RHSStr = std::string(Lexer::getSourceText(
11999       CharSourceRange::getTokenRange(RHSInt->getSourceRange()),
12000       S.getSourceManager(), S.getLangOpts()));
12001 
12002   if (Negative) {
12003     RightSideValue = -RightSideValue;
12004     RHSStr = "-" + RHSStr;
12005   } else if (ExplicitPlus) {
12006     RHSStr = "+" + RHSStr;
12007   }
12008 
12009   StringRef LHSStrRef = LHSStr;
12010   StringRef RHSStrRef = RHSStr;
12011   // Do not diagnose literals with digit separators, binary, hexadecimal, octal
12012   // literals.
12013   if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") ||
12014       RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") ||
12015       LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") ||
12016       RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") ||
12017       (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) ||
12018       (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) ||
12019       LHSStrRef.find('\'') != StringRef::npos ||
12020       RHSStrRef.find('\'') != StringRef::npos)
12021     return;
12022 
12023   bool SuggestXor = S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor");
12024   const llvm::APInt XorValue = LeftSideValue ^ RightSideValue;
12025   int64_t RightSideIntValue = RightSideValue.getSExtValue();
12026   if (LeftSideValue == 2 && RightSideIntValue >= 0) {
12027     std::string SuggestedExpr = "1 << " + RHSStr;
12028     bool Overflow = false;
12029     llvm::APInt One = (LeftSideValue - 1);
12030     llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow);
12031     if (Overflow) {
12032       if (RightSideIntValue < 64)
12033         S.Diag(Loc, diag::warn_xor_used_as_pow_base)
12034             << ExprStr << XorValue.toString(10, true) << ("1LL << " + RHSStr)
12035             << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr);
12036       else if (RightSideIntValue == 64)
12037         S.Diag(Loc, diag::warn_xor_used_as_pow) << ExprStr << XorValue.toString(10, true);
12038       else
12039         return;
12040     } else {
12041       S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra)
12042           << ExprStr << XorValue.toString(10, true) << SuggestedExpr
12043           << PowValue.toString(10, true)
12044           << FixItHint::CreateReplacement(
12045                  ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr);
12046     }
12047 
12048     S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0x2 ^ " + RHSStr) << SuggestXor;
12049   } else if (LeftSideValue == 10) {
12050     std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue);
12051     S.Diag(Loc, diag::warn_xor_used_as_pow_base)
12052         << ExprStr << XorValue.toString(10, true) << SuggestedValue
12053         << FixItHint::CreateReplacement(ExprRange, SuggestedValue);
12054     S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0xA ^ " + RHSStr) << SuggestXor;
12055   }
12056 }
12057 
12058 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
12059                                           SourceLocation Loc) {
12060   // Ensure that either both operands are of the same vector type, or
12061   // one operand is of a vector type and the other is of its element type.
12062   QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
12063                                        /*AllowBothBool*/true,
12064                                        /*AllowBoolConversions*/false);
12065   if (vType.isNull())
12066     return InvalidOperands(Loc, LHS, RHS);
12067   if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
12068       !getLangOpts().OpenCLCPlusPlus && vType->hasFloatingRepresentation())
12069     return InvalidOperands(Loc, LHS, RHS);
12070   // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
12071   //        usage of the logical operators && and || with vectors in C. This
12072   //        check could be notionally dropped.
12073   if (!getLangOpts().CPlusPlus &&
12074       !(isa<ExtVectorType>(vType->getAs<VectorType>())))
12075     return InvalidLogicalVectorOperands(Loc, LHS, RHS);
12076 
12077   return GetSignedVectorType(LHS.get()->getType());
12078 }
12079 
12080 QualType Sema::CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS,
12081                                               SourceLocation Loc,
12082                                               bool IsCompAssign) {
12083   if (!IsCompAssign) {
12084     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
12085     if (LHS.isInvalid())
12086       return QualType();
12087   }
12088   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
12089   if (RHS.isInvalid())
12090     return QualType();
12091 
12092   // For conversion purposes, we ignore any qualifiers.
12093   // For example, "const float" and "float" are equivalent.
12094   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
12095   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
12096 
12097   const MatrixType *LHSMatType = LHSType->getAs<MatrixType>();
12098   const MatrixType *RHSMatType = RHSType->getAs<MatrixType>();
12099   assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
12100 
12101   if (Context.hasSameType(LHSType, RHSType))
12102     return LHSType;
12103 
12104   // Type conversion may change LHS/RHS. Keep copies to the original results, in
12105   // case we have to return InvalidOperands.
12106   ExprResult OriginalLHS = LHS;
12107   ExprResult OriginalRHS = RHS;
12108   if (LHSMatType && !RHSMatType) {
12109     if (tryConvertToTy(*this, LHSMatType->getElementType(), &RHS))
12110       return LHSType;
12111     return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
12112   }
12113 
12114   if (!LHSMatType && RHSMatType) {
12115     if (tryConvertToTy(*this, RHSMatType->getElementType(), &LHS))
12116       return RHSType;
12117     return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
12118   }
12119 
12120   return InvalidOperands(Loc, LHS, RHS);
12121 }
12122 
12123 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
12124                                            SourceLocation Loc,
12125                                            BinaryOperatorKind Opc) {
12126   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
12127 
12128   bool IsCompAssign =
12129       Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
12130 
12131   if (LHS.get()->getType()->isVectorType() ||
12132       RHS.get()->getType()->isVectorType()) {
12133     if (LHS.get()->getType()->hasIntegerRepresentation() &&
12134         RHS.get()->getType()->hasIntegerRepresentation())
12135       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
12136                         /*AllowBothBool*/true,
12137                         /*AllowBoolConversions*/getLangOpts().ZVector);
12138     return InvalidOperands(Loc, LHS, RHS);
12139   }
12140 
12141   if (Opc == BO_And)
12142     diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
12143 
12144   if (LHS.get()->getType()->hasFloatingRepresentation() ||
12145       RHS.get()->getType()->hasFloatingRepresentation())
12146     return InvalidOperands(Loc, LHS, RHS);
12147 
12148   ExprResult LHSResult = LHS, RHSResult = RHS;
12149   QualType compType = UsualArithmeticConversions(
12150       LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp);
12151   if (LHSResult.isInvalid() || RHSResult.isInvalid())
12152     return QualType();
12153   LHS = LHSResult.get();
12154   RHS = RHSResult.get();
12155 
12156   if (Opc == BO_Xor)
12157     diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc);
12158 
12159   if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
12160     return compType;
12161   return InvalidOperands(Loc, LHS, RHS);
12162 }
12163 
12164 // C99 6.5.[13,14]
12165 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
12166                                            SourceLocation Loc,
12167                                            BinaryOperatorKind Opc) {
12168   // Check vector operands differently.
12169   if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
12170     return CheckVectorLogicalOperands(LHS, RHS, Loc);
12171 
12172   bool EnumConstantInBoolContext = false;
12173   for (const ExprResult &HS : {LHS, RHS}) {
12174     if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) {
12175       const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl());
12176       if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1)
12177         EnumConstantInBoolContext = true;
12178     }
12179   }
12180 
12181   if (EnumConstantInBoolContext)
12182     Diag(Loc, diag::warn_enum_constant_in_bool_context);
12183 
12184   // Diagnose cases where the user write a logical and/or but probably meant a
12185   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
12186   // is a constant.
12187   if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() &&
12188       !LHS.get()->getType()->isBooleanType() &&
12189       RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
12190       // Don't warn in macros or template instantiations.
12191       !Loc.isMacroID() && !inTemplateInstantiation()) {
12192     // If the RHS can be constant folded, and if it constant folds to something
12193     // that isn't 0 or 1 (which indicate a potential logical operation that
12194     // happened to fold to true/false) then warn.
12195     // Parens on the RHS are ignored.
12196     Expr::EvalResult EVResult;
12197     if (RHS.get()->EvaluateAsInt(EVResult, Context)) {
12198       llvm::APSInt Result = EVResult.Val.getInt();
12199       if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
12200            !RHS.get()->getExprLoc().isMacroID()) ||
12201           (Result != 0 && Result != 1)) {
12202         Diag(Loc, diag::warn_logical_instead_of_bitwise)
12203           << RHS.get()->getSourceRange()
12204           << (Opc == BO_LAnd ? "&&" : "||");
12205         // Suggest replacing the logical operator with the bitwise version
12206         Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
12207             << (Opc == BO_LAnd ? "&" : "|")
12208             << FixItHint::CreateReplacement(SourceRange(
12209                                                  Loc, getLocForEndOfToken(Loc)),
12210                                             Opc == BO_LAnd ? "&" : "|");
12211         if (Opc == BO_LAnd)
12212           // Suggest replacing "Foo() && kNonZero" with "Foo()"
12213           Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
12214               << FixItHint::CreateRemoval(
12215                      SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()),
12216                                  RHS.get()->getEndLoc()));
12217       }
12218     }
12219   }
12220 
12221   if (!Context.getLangOpts().CPlusPlus) {
12222     // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
12223     // not operate on the built-in scalar and vector float types.
12224     if (Context.getLangOpts().OpenCL &&
12225         Context.getLangOpts().OpenCLVersion < 120) {
12226       if (LHS.get()->getType()->isFloatingType() ||
12227           RHS.get()->getType()->isFloatingType())
12228         return InvalidOperands(Loc, LHS, RHS);
12229     }
12230 
12231     LHS = UsualUnaryConversions(LHS.get());
12232     if (LHS.isInvalid())
12233       return QualType();
12234 
12235     RHS = UsualUnaryConversions(RHS.get());
12236     if (RHS.isInvalid())
12237       return QualType();
12238 
12239     if (!LHS.get()->getType()->isScalarType() ||
12240         !RHS.get()->getType()->isScalarType())
12241       return InvalidOperands(Loc, LHS, RHS);
12242 
12243     return Context.IntTy;
12244   }
12245 
12246   // The following is safe because we only use this method for
12247   // non-overloadable operands.
12248 
12249   // C++ [expr.log.and]p1
12250   // C++ [expr.log.or]p1
12251   // The operands are both contextually converted to type bool.
12252   ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
12253   if (LHSRes.isInvalid())
12254     return InvalidOperands(Loc, LHS, RHS);
12255   LHS = LHSRes;
12256 
12257   ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
12258   if (RHSRes.isInvalid())
12259     return InvalidOperands(Loc, LHS, RHS);
12260   RHS = RHSRes;
12261 
12262   // C++ [expr.log.and]p2
12263   // C++ [expr.log.or]p2
12264   // The result is a bool.
12265   return Context.BoolTy;
12266 }
12267 
12268 static bool IsReadonlyMessage(Expr *E, Sema &S) {
12269   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
12270   if (!ME) return false;
12271   if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
12272   ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
12273       ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
12274   if (!Base) return false;
12275   return Base->getMethodDecl() != nullptr;
12276 }
12277 
12278 /// Is the given expression (which must be 'const') a reference to a
12279 /// variable which was originally non-const, but which has become
12280 /// 'const' due to being captured within a block?
12281 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
12282 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
12283   assert(E->isLValue() && E->getType().isConstQualified());
12284   E = E->IgnoreParens();
12285 
12286   // Must be a reference to a declaration from an enclosing scope.
12287   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
12288   if (!DRE) return NCCK_None;
12289   if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
12290 
12291   // The declaration must be a variable which is not declared 'const'.
12292   VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
12293   if (!var) return NCCK_None;
12294   if (var->getType().isConstQualified()) return NCCK_None;
12295   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
12296 
12297   // Decide whether the first capture was for a block or a lambda.
12298   DeclContext *DC = S.CurContext, *Prev = nullptr;
12299   // Decide whether the first capture was for a block or a lambda.
12300   while (DC) {
12301     // For init-capture, it is possible that the variable belongs to the
12302     // template pattern of the current context.
12303     if (auto *FD = dyn_cast<FunctionDecl>(DC))
12304       if (var->isInitCapture() &&
12305           FD->getTemplateInstantiationPattern() == var->getDeclContext())
12306         break;
12307     if (DC == var->getDeclContext())
12308       break;
12309     Prev = DC;
12310     DC = DC->getParent();
12311   }
12312   // Unless we have an init-capture, we've gone one step too far.
12313   if (!var->isInitCapture())
12314     DC = Prev;
12315   return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
12316 }
12317 
12318 static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
12319   Ty = Ty.getNonReferenceType();
12320   if (IsDereference && Ty->isPointerType())
12321     Ty = Ty->getPointeeType();
12322   return !Ty.isConstQualified();
12323 }
12324 
12325 // Update err_typecheck_assign_const and note_typecheck_assign_const
12326 // when this enum is changed.
12327 enum {
12328   ConstFunction,
12329   ConstVariable,
12330   ConstMember,
12331   ConstMethod,
12332   NestedConstMember,
12333   ConstUnknown,  // Keep as last element
12334 };
12335 
12336 /// Emit the "read-only variable not assignable" error and print notes to give
12337 /// more information about why the variable is not assignable, such as pointing
12338 /// to the declaration of a const variable, showing that a method is const, or
12339 /// that the function is returning a const reference.
12340 static void DiagnoseConstAssignment(Sema &S, const Expr *E,
12341                                     SourceLocation Loc) {
12342   SourceRange ExprRange = E->getSourceRange();
12343 
12344   // Only emit one error on the first const found.  All other consts will emit
12345   // a note to the error.
12346   bool DiagnosticEmitted = false;
12347 
12348   // Track if the current expression is the result of a dereference, and if the
12349   // next checked expression is the result of a dereference.
12350   bool IsDereference = false;
12351   bool NextIsDereference = false;
12352 
12353   // Loop to process MemberExpr chains.
12354   while (true) {
12355     IsDereference = NextIsDereference;
12356 
12357     E = E->IgnoreImplicit()->IgnoreParenImpCasts();
12358     if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
12359       NextIsDereference = ME->isArrow();
12360       const ValueDecl *VD = ME->getMemberDecl();
12361       if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
12362         // Mutable fields can be modified even if the class is const.
12363         if (Field->isMutable()) {
12364           assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
12365           break;
12366         }
12367 
12368         if (!IsTypeModifiable(Field->getType(), IsDereference)) {
12369           if (!DiagnosticEmitted) {
12370             S.Diag(Loc, diag::err_typecheck_assign_const)
12371                 << ExprRange << ConstMember << false /*static*/ << Field
12372                 << Field->getType();
12373             DiagnosticEmitted = true;
12374           }
12375           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
12376               << ConstMember << false /*static*/ << Field << Field->getType()
12377               << Field->getSourceRange();
12378         }
12379         E = ME->getBase();
12380         continue;
12381       } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
12382         if (VDecl->getType().isConstQualified()) {
12383           if (!DiagnosticEmitted) {
12384             S.Diag(Loc, diag::err_typecheck_assign_const)
12385                 << ExprRange << ConstMember << true /*static*/ << VDecl
12386                 << VDecl->getType();
12387             DiagnosticEmitted = true;
12388           }
12389           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
12390               << ConstMember << true /*static*/ << VDecl << VDecl->getType()
12391               << VDecl->getSourceRange();
12392         }
12393         // Static fields do not inherit constness from parents.
12394         break;
12395       }
12396       break; // End MemberExpr
12397     } else if (const ArraySubscriptExpr *ASE =
12398                    dyn_cast<ArraySubscriptExpr>(E)) {
12399       E = ASE->getBase()->IgnoreParenImpCasts();
12400       continue;
12401     } else if (const ExtVectorElementExpr *EVE =
12402                    dyn_cast<ExtVectorElementExpr>(E)) {
12403       E = EVE->getBase()->IgnoreParenImpCasts();
12404       continue;
12405     }
12406     break;
12407   }
12408 
12409   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
12410     // Function calls
12411     const FunctionDecl *FD = CE->getDirectCallee();
12412     if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
12413       if (!DiagnosticEmitted) {
12414         S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
12415                                                       << ConstFunction << FD;
12416         DiagnosticEmitted = true;
12417       }
12418       S.Diag(FD->getReturnTypeSourceRange().getBegin(),
12419              diag::note_typecheck_assign_const)
12420           << ConstFunction << FD << FD->getReturnType()
12421           << FD->getReturnTypeSourceRange();
12422     }
12423   } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
12424     // Point to variable declaration.
12425     if (const ValueDecl *VD = DRE->getDecl()) {
12426       if (!IsTypeModifiable(VD->getType(), IsDereference)) {
12427         if (!DiagnosticEmitted) {
12428           S.Diag(Loc, diag::err_typecheck_assign_const)
12429               << ExprRange << ConstVariable << VD << VD->getType();
12430           DiagnosticEmitted = true;
12431         }
12432         S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
12433             << ConstVariable << VD << VD->getType() << VD->getSourceRange();
12434       }
12435     }
12436   } else if (isa<CXXThisExpr>(E)) {
12437     if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
12438       if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
12439         if (MD->isConst()) {
12440           if (!DiagnosticEmitted) {
12441             S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
12442                                                           << ConstMethod << MD;
12443             DiagnosticEmitted = true;
12444           }
12445           S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
12446               << ConstMethod << MD << MD->getSourceRange();
12447         }
12448       }
12449     }
12450   }
12451 
12452   if (DiagnosticEmitted)
12453     return;
12454 
12455   // Can't determine a more specific message, so display the generic error.
12456   S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
12457 }
12458 
12459 enum OriginalExprKind {
12460   OEK_Variable,
12461   OEK_Member,
12462   OEK_LValue
12463 };
12464 
12465 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD,
12466                                          const RecordType *Ty,
12467                                          SourceLocation Loc, SourceRange Range,
12468                                          OriginalExprKind OEK,
12469                                          bool &DiagnosticEmitted) {
12470   std::vector<const RecordType *> RecordTypeList;
12471   RecordTypeList.push_back(Ty);
12472   unsigned NextToCheckIndex = 0;
12473   // We walk the record hierarchy breadth-first to ensure that we print
12474   // diagnostics in field nesting order.
12475   while (RecordTypeList.size() > NextToCheckIndex) {
12476     bool IsNested = NextToCheckIndex > 0;
12477     for (const FieldDecl *Field :
12478          RecordTypeList[NextToCheckIndex]->getDecl()->fields()) {
12479       // First, check every field for constness.
12480       QualType FieldTy = Field->getType();
12481       if (FieldTy.isConstQualified()) {
12482         if (!DiagnosticEmitted) {
12483           S.Diag(Loc, diag::err_typecheck_assign_const)
12484               << Range << NestedConstMember << OEK << VD
12485               << IsNested << Field;
12486           DiagnosticEmitted = true;
12487         }
12488         S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
12489             << NestedConstMember << IsNested << Field
12490             << FieldTy << Field->getSourceRange();
12491       }
12492 
12493       // Then we append it to the list to check next in order.
12494       FieldTy = FieldTy.getCanonicalType();
12495       if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) {
12496         if (llvm::find(RecordTypeList, FieldRecTy) == RecordTypeList.end())
12497           RecordTypeList.push_back(FieldRecTy);
12498       }
12499     }
12500     ++NextToCheckIndex;
12501   }
12502 }
12503 
12504 /// Emit an error for the case where a record we are trying to assign to has a
12505 /// const-qualified field somewhere in its hierarchy.
12506 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
12507                                          SourceLocation Loc) {
12508   QualType Ty = E->getType();
12509   assert(Ty->isRecordType() && "lvalue was not record?");
12510   SourceRange Range = E->getSourceRange();
12511   const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>();
12512   bool DiagEmitted = false;
12513 
12514   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
12515     DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
12516             Range, OEK_Member, DiagEmitted);
12517   else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
12518     DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
12519             Range, OEK_Variable, DiagEmitted);
12520   else
12521     DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
12522             Range, OEK_LValue, DiagEmitted);
12523   if (!DiagEmitted)
12524     DiagnoseConstAssignment(S, E, Loc);
12525 }
12526 
12527 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
12528 /// emit an error and return true.  If so, return false.
12529 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
12530   assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
12531 
12532   S.CheckShadowingDeclModification(E, Loc);
12533 
12534   SourceLocation OrigLoc = Loc;
12535   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
12536                                                               &Loc);
12537   if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
12538     IsLV = Expr::MLV_InvalidMessageExpression;
12539   if (IsLV == Expr::MLV_Valid)
12540     return false;
12541 
12542   unsigned DiagID = 0;
12543   bool NeedType = false;
12544   switch (IsLV) { // C99 6.5.16p2
12545   case Expr::MLV_ConstQualified:
12546     // Use a specialized diagnostic when we're assigning to an object
12547     // from an enclosing function or block.
12548     if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
12549       if (NCCK == NCCK_Block)
12550         DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
12551       else
12552         DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
12553       break;
12554     }
12555 
12556     // In ARC, use some specialized diagnostics for occasions where we
12557     // infer 'const'.  These are always pseudo-strong variables.
12558     if (S.getLangOpts().ObjCAutoRefCount) {
12559       DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
12560       if (declRef && isa<VarDecl>(declRef->getDecl())) {
12561         VarDecl *var = cast<VarDecl>(declRef->getDecl());
12562 
12563         // Use the normal diagnostic if it's pseudo-__strong but the
12564         // user actually wrote 'const'.
12565         if (var->isARCPseudoStrong() &&
12566             (!var->getTypeSourceInfo() ||
12567              !var->getTypeSourceInfo()->getType().isConstQualified())) {
12568           // There are three pseudo-strong cases:
12569           //  - self
12570           ObjCMethodDecl *method = S.getCurMethodDecl();
12571           if (method && var == method->getSelfDecl()) {
12572             DiagID = method->isClassMethod()
12573               ? diag::err_typecheck_arc_assign_self_class_method
12574               : diag::err_typecheck_arc_assign_self;
12575 
12576           //  - Objective-C externally_retained attribute.
12577           } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
12578                      isa<ParmVarDecl>(var)) {
12579             DiagID = diag::err_typecheck_arc_assign_externally_retained;
12580 
12581           //  - fast enumeration variables
12582           } else {
12583             DiagID = diag::err_typecheck_arr_assign_enumeration;
12584           }
12585 
12586           SourceRange Assign;
12587           if (Loc != OrigLoc)
12588             Assign = SourceRange(OrigLoc, OrigLoc);
12589           S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
12590           // We need to preserve the AST regardless, so migration tool
12591           // can do its job.
12592           return false;
12593         }
12594       }
12595     }
12596 
12597     // If none of the special cases above are triggered, then this is a
12598     // simple const assignment.
12599     if (DiagID == 0) {
12600       DiagnoseConstAssignment(S, E, Loc);
12601       return true;
12602     }
12603 
12604     break;
12605   case Expr::MLV_ConstAddrSpace:
12606     DiagnoseConstAssignment(S, E, Loc);
12607     return true;
12608   case Expr::MLV_ConstQualifiedField:
12609     DiagnoseRecursiveConstFields(S, E, Loc);
12610     return true;
12611   case Expr::MLV_ArrayType:
12612   case Expr::MLV_ArrayTemporary:
12613     DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
12614     NeedType = true;
12615     break;
12616   case Expr::MLV_NotObjectType:
12617     DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
12618     NeedType = true;
12619     break;
12620   case Expr::MLV_LValueCast:
12621     DiagID = diag::err_typecheck_lvalue_casts_not_supported;
12622     break;
12623   case Expr::MLV_Valid:
12624     llvm_unreachable("did not take early return for MLV_Valid");
12625   case Expr::MLV_InvalidExpression:
12626   case Expr::MLV_MemberFunction:
12627   case Expr::MLV_ClassTemporary:
12628     DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
12629     break;
12630   case Expr::MLV_IncompleteType:
12631   case Expr::MLV_IncompleteVoidType:
12632     return S.RequireCompleteType(Loc, E->getType(),
12633              diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
12634   case Expr::MLV_DuplicateVectorComponents:
12635     DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
12636     break;
12637   case Expr::MLV_NoSetterProperty:
12638     llvm_unreachable("readonly properties should be processed differently");
12639   case Expr::MLV_InvalidMessageExpression:
12640     DiagID = diag::err_readonly_message_assignment;
12641     break;
12642   case Expr::MLV_SubObjCPropertySetting:
12643     DiagID = diag::err_no_subobject_property_setting;
12644     break;
12645   }
12646 
12647   SourceRange Assign;
12648   if (Loc != OrigLoc)
12649     Assign = SourceRange(OrigLoc, OrigLoc);
12650   if (NeedType)
12651     S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
12652   else
12653     S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
12654   return true;
12655 }
12656 
12657 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
12658                                          SourceLocation Loc,
12659                                          Sema &Sema) {
12660   if (Sema.inTemplateInstantiation())
12661     return;
12662   if (Sema.isUnevaluatedContext())
12663     return;
12664   if (Loc.isInvalid() || Loc.isMacroID())
12665     return;
12666   if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
12667     return;
12668 
12669   // C / C++ fields
12670   MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
12671   MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
12672   if (ML && MR) {
12673     if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
12674       return;
12675     const ValueDecl *LHSDecl =
12676         cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl());
12677     const ValueDecl *RHSDecl =
12678         cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl());
12679     if (LHSDecl != RHSDecl)
12680       return;
12681     if (LHSDecl->getType().isVolatileQualified())
12682       return;
12683     if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
12684       if (RefTy->getPointeeType().isVolatileQualified())
12685         return;
12686 
12687     Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
12688   }
12689 
12690   // Objective-C instance variables
12691   ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
12692   ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
12693   if (OL && OR && OL->getDecl() == OR->getDecl()) {
12694     DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
12695     DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
12696     if (RL && RR && RL->getDecl() == RR->getDecl())
12697       Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
12698   }
12699 }
12700 
12701 // C99 6.5.16.1
12702 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
12703                                        SourceLocation Loc,
12704                                        QualType CompoundType) {
12705   assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
12706 
12707   // Verify that LHS is a modifiable lvalue, and emit error if not.
12708   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
12709     return QualType();
12710 
12711   QualType LHSType = LHSExpr->getType();
12712   QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
12713                                              CompoundType;
12714   // OpenCL v1.2 s6.1.1.1 p2:
12715   // The half data type can only be used to declare a pointer to a buffer that
12716   // contains half values
12717   if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
12718     LHSType->isHalfType()) {
12719     Diag(Loc, diag::err_opencl_half_load_store) << 1
12720         << LHSType.getUnqualifiedType();
12721     return QualType();
12722   }
12723 
12724   AssignConvertType ConvTy;
12725   if (CompoundType.isNull()) {
12726     Expr *RHSCheck = RHS.get();
12727 
12728     CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
12729 
12730     QualType LHSTy(LHSType);
12731     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
12732     if (RHS.isInvalid())
12733       return QualType();
12734     // Special case of NSObject attributes on c-style pointer types.
12735     if (ConvTy == IncompatiblePointer &&
12736         ((Context.isObjCNSObjectType(LHSType) &&
12737           RHSType->isObjCObjectPointerType()) ||
12738          (Context.isObjCNSObjectType(RHSType) &&
12739           LHSType->isObjCObjectPointerType())))
12740       ConvTy = Compatible;
12741 
12742     if (ConvTy == Compatible &&
12743         LHSType->isObjCObjectType())
12744         Diag(Loc, diag::err_objc_object_assignment)
12745           << LHSType;
12746 
12747     // If the RHS is a unary plus or minus, check to see if they = and + are
12748     // right next to each other.  If so, the user may have typo'd "x =+ 4"
12749     // instead of "x += 4".
12750     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
12751       RHSCheck = ICE->getSubExpr();
12752     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
12753       if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
12754           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
12755           // Only if the two operators are exactly adjacent.
12756           Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
12757           // And there is a space or other character before the subexpr of the
12758           // unary +/-.  We don't want to warn on "x=-1".
12759           Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() &&
12760           UO->getSubExpr()->getBeginLoc().isFileID()) {
12761         Diag(Loc, diag::warn_not_compound_assign)
12762           << (UO->getOpcode() == UO_Plus ? "+" : "-")
12763           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
12764       }
12765     }
12766 
12767     if (ConvTy == Compatible) {
12768       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
12769         // Warn about retain cycles where a block captures the LHS, but
12770         // not if the LHS is a simple variable into which the block is
12771         // being stored...unless that variable can be captured by reference!
12772         const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
12773         const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
12774         if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
12775           checkRetainCycles(LHSExpr, RHS.get());
12776       }
12777 
12778       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
12779           LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
12780         // It is safe to assign a weak reference into a strong variable.
12781         // Although this code can still have problems:
12782         //   id x = self.weakProp;
12783         //   id y = self.weakProp;
12784         // we do not warn to warn spuriously when 'x' and 'y' are on separate
12785         // paths through the function. This should be revisited if
12786         // -Wrepeated-use-of-weak is made flow-sensitive.
12787         // For ObjCWeak only, we do not warn if the assign is to a non-weak
12788         // variable, which will be valid for the current autorelease scope.
12789         if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
12790                              RHS.get()->getBeginLoc()))
12791           getCurFunction()->markSafeWeakUse(RHS.get());
12792 
12793       } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
12794         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
12795       }
12796     }
12797   } else {
12798     // Compound assignment "x += y"
12799     ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
12800   }
12801 
12802   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
12803                                RHS.get(), AA_Assigning))
12804     return QualType();
12805 
12806   CheckForNullPointerDereference(*this, LHSExpr);
12807 
12808   if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) {
12809     if (CompoundType.isNull()) {
12810       // C++2a [expr.ass]p5:
12811       //   A simple-assignment whose left operand is of a volatile-qualified
12812       //   type is deprecated unless the assignment is either a discarded-value
12813       //   expression or an unevaluated operand
12814       ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr);
12815     } else {
12816       // C++2a [expr.ass]p6:
12817       //   [Compound-assignment] expressions are deprecated if E1 has
12818       //   volatile-qualified type
12819       Diag(Loc, diag::warn_deprecated_compound_assign_volatile) << LHSType;
12820     }
12821   }
12822 
12823   // C99 6.5.16p3: The type of an assignment expression is the type of the
12824   // left operand unless the left operand has qualified type, in which case
12825   // it is the unqualified version of the type of the left operand.
12826   // C99 6.5.16.1p2: In simple assignment, the value of the right operand
12827   // is converted to the type of the assignment expression (above).
12828   // C++ 5.17p1: the type of the assignment expression is that of its left
12829   // operand.
12830   return (getLangOpts().CPlusPlus
12831           ? LHSType : LHSType.getUnqualifiedType());
12832 }
12833 
12834 // Only ignore explicit casts to void.
12835 static bool IgnoreCommaOperand(const Expr *E) {
12836   E = E->IgnoreParens();
12837 
12838   if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
12839     if (CE->getCastKind() == CK_ToVoid) {
12840       return true;
12841     }
12842 
12843     // static_cast<void> on a dependent type will not show up as CK_ToVoid.
12844     if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
12845         CE->getSubExpr()->getType()->isDependentType()) {
12846       return true;
12847     }
12848   }
12849 
12850   return false;
12851 }
12852 
12853 // Look for instances where it is likely the comma operator is confused with
12854 // another operator.  There is a whitelist of acceptable expressions for the
12855 // left hand side of the comma operator, otherwise emit a warning.
12856 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
12857   // No warnings in macros
12858   if (Loc.isMacroID())
12859     return;
12860 
12861   // Don't warn in template instantiations.
12862   if (inTemplateInstantiation())
12863     return;
12864 
12865   // Scope isn't fine-grained enough to whitelist the specific cases, so
12866   // instead, skip more than needed, then call back into here with the
12867   // CommaVisitor in SemaStmt.cpp.
12868   // The whitelisted locations are the initialization and increment portions
12869   // of a for loop.  The additional checks are on the condition of
12870   // if statements, do/while loops, and for loops.
12871   // Differences in scope flags for C89 mode requires the extra logic.
12872   const unsigned ForIncrementFlags =
12873       getLangOpts().C99 || getLangOpts().CPlusPlus
12874           ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope
12875           : Scope::ContinueScope | Scope::BreakScope;
12876   const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
12877   const unsigned ScopeFlags = getCurScope()->getFlags();
12878   if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
12879       (ScopeFlags & ForInitFlags) == ForInitFlags)
12880     return;
12881 
12882   // If there are multiple comma operators used together, get the RHS of the
12883   // of the comma operator as the LHS.
12884   while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
12885     if (BO->getOpcode() != BO_Comma)
12886       break;
12887     LHS = BO->getRHS();
12888   }
12889 
12890   // Only allow some expressions on LHS to not warn.
12891   if (IgnoreCommaOperand(LHS))
12892     return;
12893 
12894   Diag(Loc, diag::warn_comma_operator);
12895   Diag(LHS->getBeginLoc(), diag::note_cast_to_void)
12896       << LHS->getSourceRange()
12897       << FixItHint::CreateInsertion(LHS->getBeginLoc(),
12898                                     LangOpts.CPlusPlus ? "static_cast<void>("
12899                                                        : "(void)(")
12900       << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()),
12901                                     ")");
12902 }
12903 
12904 // C99 6.5.17
12905 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
12906                                    SourceLocation Loc) {
12907   LHS = S.CheckPlaceholderExpr(LHS.get());
12908   RHS = S.CheckPlaceholderExpr(RHS.get());
12909   if (LHS.isInvalid() || RHS.isInvalid())
12910     return QualType();
12911 
12912   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
12913   // operands, but not unary promotions.
12914   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
12915 
12916   // So we treat the LHS as a ignored value, and in C++ we allow the
12917   // containing site to determine what should be done with the RHS.
12918   LHS = S.IgnoredValueConversions(LHS.get());
12919   if (LHS.isInvalid())
12920     return QualType();
12921 
12922   S.DiagnoseUnusedExprResult(LHS.get());
12923 
12924   if (!S.getLangOpts().CPlusPlus) {
12925     RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
12926     if (RHS.isInvalid())
12927       return QualType();
12928     if (!RHS.get()->getType()->isVoidType())
12929       S.RequireCompleteType(Loc, RHS.get()->getType(),
12930                             diag::err_incomplete_type);
12931   }
12932 
12933   if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
12934     S.DiagnoseCommaOperator(LHS.get(), Loc);
12935 
12936   return RHS.get()->getType();
12937 }
12938 
12939 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
12940 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
12941 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
12942                                                ExprValueKind &VK,
12943                                                ExprObjectKind &OK,
12944                                                SourceLocation OpLoc,
12945                                                bool IsInc, bool IsPrefix) {
12946   if (Op->isTypeDependent())
12947     return S.Context.DependentTy;
12948 
12949   QualType ResType = Op->getType();
12950   // Atomic types can be used for increment / decrement where the non-atomic
12951   // versions can, so ignore the _Atomic() specifier for the purpose of
12952   // checking.
12953   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
12954     ResType = ResAtomicType->getValueType();
12955 
12956   assert(!ResType.isNull() && "no type for increment/decrement expression");
12957 
12958   if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
12959     // Decrement of bool is not allowed.
12960     if (!IsInc) {
12961       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
12962       return QualType();
12963     }
12964     // Increment of bool sets it to true, but is deprecated.
12965     S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
12966                                               : diag::warn_increment_bool)
12967       << Op->getSourceRange();
12968   } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
12969     // Error on enum increments and decrements in C++ mode
12970     S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
12971     return QualType();
12972   } else if (ResType->isRealType()) {
12973     // OK!
12974   } else if (ResType->isPointerType()) {
12975     // C99 6.5.2.4p2, 6.5.6p2
12976     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
12977       return QualType();
12978   } else if (ResType->isObjCObjectPointerType()) {
12979     // On modern runtimes, ObjC pointer arithmetic is forbidden.
12980     // Otherwise, we just need a complete type.
12981     if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
12982         checkArithmeticOnObjCPointer(S, OpLoc, Op))
12983       return QualType();
12984   } else if (ResType->isAnyComplexType()) {
12985     // C99 does not support ++/-- on complex types, we allow as an extension.
12986     S.Diag(OpLoc, diag::ext_integer_increment_complex)
12987       << ResType << Op->getSourceRange();
12988   } else if (ResType->isPlaceholderType()) {
12989     ExprResult PR = S.CheckPlaceholderExpr(Op);
12990     if (PR.isInvalid()) return QualType();
12991     return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
12992                                           IsInc, IsPrefix);
12993   } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
12994     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
12995   } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
12996              (ResType->castAs<VectorType>()->getVectorKind() !=
12997               VectorType::AltiVecBool)) {
12998     // The z vector extensions allow ++ and -- for non-bool vectors.
12999   } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
13000             ResType->castAs<VectorType>()->getElementType()->isIntegerType()) {
13001     // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
13002   } else {
13003     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
13004       << ResType << int(IsInc) << Op->getSourceRange();
13005     return QualType();
13006   }
13007   // At this point, we know we have a real, complex or pointer type.
13008   // Now make sure the operand is a modifiable lvalue.
13009   if (CheckForModifiableLvalue(Op, OpLoc, S))
13010     return QualType();
13011   if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) {
13012     // C++2a [expr.pre.inc]p1, [expr.post.inc]p1:
13013     //   An operand with volatile-qualified type is deprecated
13014     S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile)
13015         << IsInc << ResType;
13016   }
13017   // In C++, a prefix increment is the same type as the operand. Otherwise
13018   // (in C or with postfix), the increment is the unqualified type of the
13019   // operand.
13020   if (IsPrefix && S.getLangOpts().CPlusPlus) {
13021     VK = VK_LValue;
13022     OK = Op->getObjectKind();
13023     return ResType;
13024   } else {
13025     VK = VK_RValue;
13026     return ResType.getUnqualifiedType();
13027   }
13028 }
13029 
13030 
13031 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
13032 /// This routine allows us to typecheck complex/recursive expressions
13033 /// where the declaration is needed for type checking. We only need to
13034 /// handle cases when the expression references a function designator
13035 /// or is an lvalue. Here are some examples:
13036 ///  - &(x) => x
13037 ///  - &*****f => f for f a function designator.
13038 ///  - &s.xx => s
13039 ///  - &s.zz[1].yy -> s, if zz is an array
13040 ///  - *(x + 1) -> x, if x is an array
13041 ///  - &"123"[2] -> 0
13042 ///  - & __real__ x -> x
13043 ///
13044 /// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to
13045 /// members.
13046 static ValueDecl *getPrimaryDecl(Expr *E) {
13047   switch (E->getStmtClass()) {
13048   case Stmt::DeclRefExprClass:
13049     return cast<DeclRefExpr>(E)->getDecl();
13050   case Stmt::MemberExprClass:
13051     // If this is an arrow operator, the address is an offset from
13052     // the base's value, so the object the base refers to is
13053     // irrelevant.
13054     if (cast<MemberExpr>(E)->isArrow())
13055       return nullptr;
13056     // Otherwise, the expression refers to a part of the base
13057     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
13058   case Stmt::ArraySubscriptExprClass: {
13059     // FIXME: This code shouldn't be necessary!  We should catch the implicit
13060     // promotion of register arrays earlier.
13061     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
13062     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
13063       if (ICE->getSubExpr()->getType()->isArrayType())
13064         return getPrimaryDecl(ICE->getSubExpr());
13065     }
13066     return nullptr;
13067   }
13068   case Stmt::UnaryOperatorClass: {
13069     UnaryOperator *UO = cast<UnaryOperator>(E);
13070 
13071     switch(UO->getOpcode()) {
13072     case UO_Real:
13073     case UO_Imag:
13074     case UO_Extension:
13075       return getPrimaryDecl(UO->getSubExpr());
13076     default:
13077       return nullptr;
13078     }
13079   }
13080   case Stmt::ParenExprClass:
13081     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
13082   case Stmt::ImplicitCastExprClass:
13083     // If the result of an implicit cast is an l-value, we care about
13084     // the sub-expression; otherwise, the result here doesn't matter.
13085     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
13086   case Stmt::CXXUuidofExprClass:
13087     return cast<CXXUuidofExpr>(E)->getGuidDecl();
13088   default:
13089     return nullptr;
13090   }
13091 }
13092 
13093 namespace {
13094 enum {
13095   AO_Bit_Field = 0,
13096   AO_Vector_Element = 1,
13097   AO_Property_Expansion = 2,
13098   AO_Register_Variable = 3,
13099   AO_Matrix_Element = 4,
13100   AO_No_Error = 5
13101 };
13102 }
13103 /// Diagnose invalid operand for address of operations.
13104 ///
13105 /// \param Type The type of operand which cannot have its address taken.
13106 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
13107                                          Expr *E, unsigned Type) {
13108   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
13109 }
13110 
13111 /// CheckAddressOfOperand - The operand of & must be either a function
13112 /// designator or an lvalue designating an object. If it is an lvalue, the
13113 /// object cannot be declared with storage class register or be a bit field.
13114 /// Note: The usual conversions are *not* applied to the operand of the &
13115 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
13116 /// In C++, the operand might be an overloaded function name, in which case
13117 /// we allow the '&' but retain the overloaded-function type.
13118 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
13119   if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
13120     if (PTy->getKind() == BuiltinType::Overload) {
13121       Expr *E = OrigOp.get()->IgnoreParens();
13122       if (!isa<OverloadExpr>(E)) {
13123         assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
13124         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
13125           << OrigOp.get()->getSourceRange();
13126         return QualType();
13127       }
13128 
13129       OverloadExpr *Ovl = cast<OverloadExpr>(E);
13130       if (isa<UnresolvedMemberExpr>(Ovl))
13131         if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
13132           Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
13133             << OrigOp.get()->getSourceRange();
13134           return QualType();
13135         }
13136 
13137       return Context.OverloadTy;
13138     }
13139 
13140     if (PTy->getKind() == BuiltinType::UnknownAny)
13141       return Context.UnknownAnyTy;
13142 
13143     if (PTy->getKind() == BuiltinType::BoundMember) {
13144       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
13145         << OrigOp.get()->getSourceRange();
13146       return QualType();
13147     }
13148 
13149     OrigOp = CheckPlaceholderExpr(OrigOp.get());
13150     if (OrigOp.isInvalid()) return QualType();
13151   }
13152 
13153   if (OrigOp.get()->isTypeDependent())
13154     return Context.DependentTy;
13155 
13156   assert(!OrigOp.get()->getType()->isPlaceholderType());
13157 
13158   // Make sure to ignore parentheses in subsequent checks
13159   Expr *op = OrigOp.get()->IgnoreParens();
13160 
13161   // In OpenCL captures for blocks called as lambda functions
13162   // are located in the private address space. Blocks used in
13163   // enqueue_kernel can be located in a different address space
13164   // depending on a vendor implementation. Thus preventing
13165   // taking an address of the capture to avoid invalid AS casts.
13166   if (LangOpts.OpenCL) {
13167     auto* VarRef = dyn_cast<DeclRefExpr>(op);
13168     if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
13169       Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
13170       return QualType();
13171     }
13172   }
13173 
13174   if (getLangOpts().C99) {
13175     // Implement C99-only parts of addressof rules.
13176     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
13177       if (uOp->getOpcode() == UO_Deref)
13178         // Per C99 6.5.3.2, the address of a deref always returns a valid result
13179         // (assuming the deref expression is valid).
13180         return uOp->getSubExpr()->getType();
13181     }
13182     // Technically, there should be a check for array subscript
13183     // expressions here, but the result of one is always an lvalue anyway.
13184   }
13185   ValueDecl *dcl = getPrimaryDecl(op);
13186 
13187   if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
13188     if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
13189                                            op->getBeginLoc()))
13190       return QualType();
13191 
13192   Expr::LValueClassification lval = op->ClassifyLValue(Context);
13193   unsigned AddressOfError = AO_No_Error;
13194 
13195   if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
13196     bool sfinae = (bool)isSFINAEContext();
13197     Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
13198                                   : diag::ext_typecheck_addrof_temporary)
13199       << op->getType() << op->getSourceRange();
13200     if (sfinae)
13201       return QualType();
13202     // Materialize the temporary as an lvalue so that we can take its address.
13203     OrigOp = op =
13204         CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
13205   } else if (isa<ObjCSelectorExpr>(op)) {
13206     return Context.getPointerType(op->getType());
13207   } else if (lval == Expr::LV_MemberFunction) {
13208     // If it's an instance method, make a member pointer.
13209     // The expression must have exactly the form &A::foo.
13210 
13211     // If the underlying expression isn't a decl ref, give up.
13212     if (!isa<DeclRefExpr>(op)) {
13213       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
13214         << OrigOp.get()->getSourceRange();
13215       return QualType();
13216     }
13217     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
13218     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
13219 
13220     // The id-expression was parenthesized.
13221     if (OrigOp.get() != DRE) {
13222       Diag(OpLoc, diag::err_parens_pointer_member_function)
13223         << OrigOp.get()->getSourceRange();
13224 
13225     // The method was named without a qualifier.
13226     } else if (!DRE->getQualifier()) {
13227       if (MD->getParent()->getName().empty())
13228         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
13229           << op->getSourceRange();
13230       else {
13231         SmallString<32> Str;
13232         StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
13233         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
13234           << op->getSourceRange()
13235           << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
13236       }
13237     }
13238 
13239     // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
13240     if (isa<CXXDestructorDecl>(MD))
13241       Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
13242 
13243     QualType MPTy = Context.getMemberPointerType(
13244         op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
13245     // Under the MS ABI, lock down the inheritance model now.
13246     if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13247       (void)isCompleteType(OpLoc, MPTy);
13248     return MPTy;
13249   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
13250     // C99 6.5.3.2p1
13251     // The operand must be either an l-value or a function designator
13252     if (!op->getType()->isFunctionType()) {
13253       // Use a special diagnostic for loads from property references.
13254       if (isa<PseudoObjectExpr>(op)) {
13255         AddressOfError = AO_Property_Expansion;
13256       } else {
13257         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
13258           << op->getType() << op->getSourceRange();
13259         return QualType();
13260       }
13261     }
13262   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
13263     // The operand cannot be a bit-field
13264     AddressOfError = AO_Bit_Field;
13265   } else if (op->getObjectKind() == OK_VectorComponent) {
13266     // The operand cannot be an element of a vector
13267     AddressOfError = AO_Vector_Element;
13268   } else if (op->getObjectKind() == OK_MatrixComponent) {
13269     // The operand cannot be an element of a matrix.
13270     AddressOfError = AO_Matrix_Element;
13271   } else if (dcl) { // C99 6.5.3.2p1
13272     // We have an lvalue with a decl. Make sure the decl is not declared
13273     // with the register storage-class specifier.
13274     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
13275       // in C++ it is not error to take address of a register
13276       // variable (c++03 7.1.1P3)
13277       if (vd->getStorageClass() == SC_Register &&
13278           !getLangOpts().CPlusPlus) {
13279         AddressOfError = AO_Register_Variable;
13280       }
13281     } else if (isa<MSPropertyDecl>(dcl)) {
13282       AddressOfError = AO_Property_Expansion;
13283     } else if (isa<FunctionTemplateDecl>(dcl)) {
13284       return Context.OverloadTy;
13285     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
13286       // Okay: we can take the address of a field.
13287       // Could be a pointer to member, though, if there is an explicit
13288       // scope qualifier for the class.
13289       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
13290         DeclContext *Ctx = dcl->getDeclContext();
13291         if (Ctx && Ctx->isRecord()) {
13292           if (dcl->getType()->isReferenceType()) {
13293             Diag(OpLoc,
13294                  diag::err_cannot_form_pointer_to_member_of_reference_type)
13295               << dcl->getDeclName() << dcl->getType();
13296             return QualType();
13297           }
13298 
13299           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
13300             Ctx = Ctx->getParent();
13301 
13302           QualType MPTy = Context.getMemberPointerType(
13303               op->getType(),
13304               Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
13305           // Under the MS ABI, lock down the inheritance model now.
13306           if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13307             (void)isCompleteType(OpLoc, MPTy);
13308           return MPTy;
13309         }
13310       }
13311     } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) &&
13312                !isa<BindingDecl>(dcl) && !isa<MSGuidDecl>(dcl))
13313       llvm_unreachable("Unknown/unexpected decl type");
13314   }
13315 
13316   if (AddressOfError != AO_No_Error) {
13317     diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
13318     return QualType();
13319   }
13320 
13321   if (lval == Expr::LV_IncompleteVoidType) {
13322     // Taking the address of a void variable is technically illegal, but we
13323     // allow it in cases which are otherwise valid.
13324     // Example: "extern void x; void* y = &x;".
13325     Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
13326   }
13327 
13328   // If the operand has type "type", the result has type "pointer to type".
13329   if (op->getType()->isObjCObjectType())
13330     return Context.getObjCObjectPointerType(op->getType());
13331 
13332   CheckAddressOfPackedMember(op);
13333 
13334   return Context.getPointerType(op->getType());
13335 }
13336 
13337 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
13338   const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
13339   if (!DRE)
13340     return;
13341   const Decl *D = DRE->getDecl();
13342   if (!D)
13343     return;
13344   const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
13345   if (!Param)
13346     return;
13347   if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
13348     if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
13349       return;
13350   if (FunctionScopeInfo *FD = S.getCurFunction())
13351     if (!FD->ModifiedNonNullParams.count(Param))
13352       FD->ModifiedNonNullParams.insert(Param);
13353 }
13354 
13355 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
13356 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
13357                                         SourceLocation OpLoc) {
13358   if (Op->isTypeDependent())
13359     return S.Context.DependentTy;
13360 
13361   ExprResult ConvResult = S.UsualUnaryConversions(Op);
13362   if (ConvResult.isInvalid())
13363     return QualType();
13364   Op = ConvResult.get();
13365   QualType OpTy = Op->getType();
13366   QualType Result;
13367 
13368   if (isa<CXXReinterpretCastExpr>(Op)) {
13369     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
13370     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
13371                                      Op->getSourceRange());
13372   }
13373 
13374   if (const PointerType *PT = OpTy->getAs<PointerType>())
13375   {
13376     Result = PT->getPointeeType();
13377   }
13378   else if (const ObjCObjectPointerType *OPT =
13379              OpTy->getAs<ObjCObjectPointerType>())
13380     Result = OPT->getPointeeType();
13381   else {
13382     ExprResult PR = S.CheckPlaceholderExpr(Op);
13383     if (PR.isInvalid()) return QualType();
13384     if (PR.get() != Op)
13385       return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
13386   }
13387 
13388   if (Result.isNull()) {
13389     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
13390       << OpTy << Op->getSourceRange();
13391     return QualType();
13392   }
13393 
13394   // Note that per both C89 and C99, indirection is always legal, even if Result
13395   // is an incomplete type or void.  It would be possible to warn about
13396   // dereferencing a void pointer, but it's completely well-defined, and such a
13397   // warning is unlikely to catch any mistakes. In C++, indirection is not valid
13398   // for pointers to 'void' but is fine for any other pointer type:
13399   //
13400   // C++ [expr.unary.op]p1:
13401   //   [...] the expression to which [the unary * operator] is applied shall
13402   //   be a pointer to an object type, or a pointer to a function type
13403   if (S.getLangOpts().CPlusPlus && Result->isVoidType())
13404     S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
13405       << OpTy << Op->getSourceRange();
13406 
13407   // Dereferences are usually l-values...
13408   VK = VK_LValue;
13409 
13410   // ...except that certain expressions are never l-values in C.
13411   if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
13412     VK = VK_RValue;
13413 
13414   return Result;
13415 }
13416 
13417 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
13418   BinaryOperatorKind Opc;
13419   switch (Kind) {
13420   default: llvm_unreachable("Unknown binop!");
13421   case tok::periodstar:           Opc = BO_PtrMemD; break;
13422   case tok::arrowstar:            Opc = BO_PtrMemI; break;
13423   case tok::star:                 Opc = BO_Mul; break;
13424   case tok::slash:                Opc = BO_Div; break;
13425   case tok::percent:              Opc = BO_Rem; break;
13426   case tok::plus:                 Opc = BO_Add; break;
13427   case tok::minus:                Opc = BO_Sub; break;
13428   case tok::lessless:             Opc = BO_Shl; break;
13429   case tok::greatergreater:       Opc = BO_Shr; break;
13430   case tok::lessequal:            Opc = BO_LE; break;
13431   case tok::less:                 Opc = BO_LT; break;
13432   case tok::greaterequal:         Opc = BO_GE; break;
13433   case tok::greater:              Opc = BO_GT; break;
13434   case tok::exclaimequal:         Opc = BO_NE; break;
13435   case tok::equalequal:           Opc = BO_EQ; break;
13436   case tok::spaceship:            Opc = BO_Cmp; break;
13437   case tok::amp:                  Opc = BO_And; break;
13438   case tok::caret:                Opc = BO_Xor; break;
13439   case tok::pipe:                 Opc = BO_Or; break;
13440   case tok::ampamp:               Opc = BO_LAnd; break;
13441   case tok::pipepipe:             Opc = BO_LOr; break;
13442   case tok::equal:                Opc = BO_Assign; break;
13443   case tok::starequal:            Opc = BO_MulAssign; break;
13444   case tok::slashequal:           Opc = BO_DivAssign; break;
13445   case tok::percentequal:         Opc = BO_RemAssign; break;
13446   case tok::plusequal:            Opc = BO_AddAssign; break;
13447   case tok::minusequal:           Opc = BO_SubAssign; break;
13448   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
13449   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
13450   case tok::ampequal:             Opc = BO_AndAssign; break;
13451   case tok::caretequal:           Opc = BO_XorAssign; break;
13452   case tok::pipeequal:            Opc = BO_OrAssign; break;
13453   case tok::comma:                Opc = BO_Comma; break;
13454   }
13455   return Opc;
13456 }
13457 
13458 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
13459   tok::TokenKind Kind) {
13460   UnaryOperatorKind Opc;
13461   switch (Kind) {
13462   default: llvm_unreachable("Unknown unary op!");
13463   case tok::plusplus:     Opc = UO_PreInc; break;
13464   case tok::minusminus:   Opc = UO_PreDec; break;
13465   case tok::amp:          Opc = UO_AddrOf; break;
13466   case tok::star:         Opc = UO_Deref; break;
13467   case tok::plus:         Opc = UO_Plus; break;
13468   case tok::minus:        Opc = UO_Minus; break;
13469   case tok::tilde:        Opc = UO_Not; break;
13470   case tok::exclaim:      Opc = UO_LNot; break;
13471   case tok::kw___real:    Opc = UO_Real; break;
13472   case tok::kw___imag:    Opc = UO_Imag; break;
13473   case tok::kw___extension__: Opc = UO_Extension; break;
13474   }
13475   return Opc;
13476 }
13477 
13478 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
13479 /// This warning suppressed in the event of macro expansions.
13480 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
13481                                    SourceLocation OpLoc, bool IsBuiltin) {
13482   if (S.inTemplateInstantiation())
13483     return;
13484   if (S.isUnevaluatedContext())
13485     return;
13486   if (OpLoc.isInvalid() || OpLoc.isMacroID())
13487     return;
13488   LHSExpr = LHSExpr->IgnoreParenImpCasts();
13489   RHSExpr = RHSExpr->IgnoreParenImpCasts();
13490   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
13491   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
13492   if (!LHSDeclRef || !RHSDeclRef ||
13493       LHSDeclRef->getLocation().isMacroID() ||
13494       RHSDeclRef->getLocation().isMacroID())
13495     return;
13496   const ValueDecl *LHSDecl =
13497     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
13498   const ValueDecl *RHSDecl =
13499     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
13500   if (LHSDecl != RHSDecl)
13501     return;
13502   if (LHSDecl->getType().isVolatileQualified())
13503     return;
13504   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
13505     if (RefTy->getPointeeType().isVolatileQualified())
13506       return;
13507 
13508   S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
13509                           : diag::warn_self_assignment_overloaded)
13510       << LHSDeclRef->getType() << LHSExpr->getSourceRange()
13511       << RHSExpr->getSourceRange();
13512 }
13513 
13514 /// Check if a bitwise-& is performed on an Objective-C pointer.  This
13515 /// is usually indicative of introspection within the Objective-C pointer.
13516 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
13517                                           SourceLocation OpLoc) {
13518   if (!S.getLangOpts().ObjC)
13519     return;
13520 
13521   const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
13522   const Expr *LHS = L.get();
13523   const Expr *RHS = R.get();
13524 
13525   if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
13526     ObjCPointerExpr = LHS;
13527     OtherExpr = RHS;
13528   }
13529   else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
13530     ObjCPointerExpr = RHS;
13531     OtherExpr = LHS;
13532   }
13533 
13534   // This warning is deliberately made very specific to reduce false
13535   // positives with logic that uses '&' for hashing.  This logic mainly
13536   // looks for code trying to introspect into tagged pointers, which
13537   // code should generally never do.
13538   if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
13539     unsigned Diag = diag::warn_objc_pointer_masking;
13540     // Determine if we are introspecting the result of performSelectorXXX.
13541     const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
13542     // Special case messages to -performSelector and friends, which
13543     // can return non-pointer values boxed in a pointer value.
13544     // Some clients may wish to silence warnings in this subcase.
13545     if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
13546       Selector S = ME->getSelector();
13547       StringRef SelArg0 = S.getNameForSlot(0);
13548       if (SelArg0.startswith("performSelector"))
13549         Diag = diag::warn_objc_pointer_masking_performSelector;
13550     }
13551 
13552     S.Diag(OpLoc, Diag)
13553       << ObjCPointerExpr->getSourceRange();
13554   }
13555 }
13556 
13557 static NamedDecl *getDeclFromExpr(Expr *E) {
13558   if (!E)
13559     return nullptr;
13560   if (auto *DRE = dyn_cast<DeclRefExpr>(E))
13561     return DRE->getDecl();
13562   if (auto *ME = dyn_cast<MemberExpr>(E))
13563     return ME->getMemberDecl();
13564   if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
13565     return IRE->getDecl();
13566   return nullptr;
13567 }
13568 
13569 // This helper function promotes a binary operator's operands (which are of a
13570 // half vector type) to a vector of floats and then truncates the result to
13571 // a vector of either half or short.
13572 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS,
13573                                       BinaryOperatorKind Opc, QualType ResultTy,
13574                                       ExprValueKind VK, ExprObjectKind OK,
13575                                       bool IsCompAssign, SourceLocation OpLoc,
13576                                       FPOptions FPFeatures) {
13577   auto &Context = S.getASTContext();
13578   assert((isVector(ResultTy, Context.HalfTy) ||
13579           isVector(ResultTy, Context.ShortTy)) &&
13580          "Result must be a vector of half or short");
13581   assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
13582          isVector(RHS.get()->getType(), Context.HalfTy) &&
13583          "both operands expected to be a half vector");
13584 
13585   RHS = convertVector(RHS.get(), Context.FloatTy, S);
13586   QualType BinOpResTy = RHS.get()->getType();
13587 
13588   // If Opc is a comparison, ResultType is a vector of shorts. In that case,
13589   // change BinOpResTy to a vector of ints.
13590   if (isVector(ResultTy, Context.ShortTy))
13591     BinOpResTy = S.GetSignedVectorType(BinOpResTy);
13592 
13593   if (IsCompAssign)
13594     return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc,
13595                                           ResultTy, VK, OK, OpLoc, FPFeatures,
13596                                           BinOpResTy, BinOpResTy);
13597 
13598   LHS = convertVector(LHS.get(), Context.FloatTy, S);
13599   auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc,
13600                                     BinOpResTy, VK, OK, OpLoc, FPFeatures);
13601   return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S);
13602 }
13603 
13604 static std::pair<ExprResult, ExprResult>
13605 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr,
13606                            Expr *RHSExpr) {
13607   ExprResult LHS = LHSExpr, RHS = RHSExpr;
13608   if (!S.getLangOpts().CPlusPlus) {
13609     // C cannot handle TypoExpr nodes on either side of a binop because it
13610     // doesn't handle dependent types properly, so make sure any TypoExprs have
13611     // been dealt with before checking the operands.
13612     LHS = S.CorrectDelayedTyposInExpr(LHS);
13613     RHS = S.CorrectDelayedTyposInExpr(RHS, [Opc, LHS](Expr *E) {
13614       if (Opc != BO_Assign)
13615         return ExprResult(E);
13616       // Avoid correcting the RHS to the same Expr as the LHS.
13617       Decl *D = getDeclFromExpr(E);
13618       return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
13619     });
13620   }
13621   return std::make_pair(LHS, RHS);
13622 }
13623 
13624 /// Returns true if conversion between vectors of halfs and vectors of floats
13625 /// is needed.
13626 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
13627                                      Expr *E0, Expr *E1 = nullptr) {
13628   if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType ||
13629       Ctx.getTargetInfo().useFP16ConversionIntrinsics())
13630     return false;
13631 
13632   auto HasVectorOfHalfType = [&Ctx](Expr *E) {
13633     QualType Ty = E->IgnoreImplicit()->getType();
13634 
13635     // Don't promote half precision neon vectors like float16x4_t in arm_neon.h
13636     // to vectors of floats. Although the element type of the vectors is __fp16,
13637     // the vectors shouldn't be treated as storage-only types. See the
13638     // discussion here: https://reviews.llvm.org/rG825235c140e7
13639     if (const VectorType *VT = Ty->getAs<VectorType>()) {
13640       if (VT->getVectorKind() == VectorType::NeonVector)
13641         return false;
13642       return VT->getElementType().getCanonicalType() == Ctx.HalfTy;
13643     }
13644     return false;
13645   };
13646 
13647   return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1));
13648 }
13649 
13650 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
13651 /// operator @p Opc at location @c TokLoc. This routine only supports
13652 /// built-in operations; ActOnBinOp handles overloaded operators.
13653 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
13654                                     BinaryOperatorKind Opc,
13655                                     Expr *LHSExpr, Expr *RHSExpr) {
13656   if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
13657     // The syntax only allows initializer lists on the RHS of assignment,
13658     // so we don't need to worry about accepting invalid code for
13659     // non-assignment operators.
13660     // C++11 5.17p9:
13661     //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
13662     //   of x = {} is x = T().
13663     InitializationKind Kind = InitializationKind::CreateDirectList(
13664         RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
13665     InitializedEntity Entity =
13666         InitializedEntity::InitializeTemporary(LHSExpr->getType());
13667     InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
13668     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
13669     if (Init.isInvalid())
13670       return Init;
13671     RHSExpr = Init.get();
13672   }
13673 
13674   ExprResult LHS = LHSExpr, RHS = RHSExpr;
13675   QualType ResultTy;     // Result type of the binary operator.
13676   // The following two variables are used for compound assignment operators
13677   QualType CompLHSTy;    // Type of LHS after promotions for computation
13678   QualType CompResultTy; // Type of computation result
13679   ExprValueKind VK = VK_RValue;
13680   ExprObjectKind OK = OK_Ordinary;
13681   bool ConvertHalfVec = false;
13682 
13683   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
13684   if (!LHS.isUsable() || !RHS.isUsable())
13685     return ExprError();
13686 
13687   if (getLangOpts().OpenCL) {
13688     QualType LHSTy = LHSExpr->getType();
13689     QualType RHSTy = RHSExpr->getType();
13690     // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
13691     // the ATOMIC_VAR_INIT macro.
13692     if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
13693       SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
13694       if (BO_Assign == Opc)
13695         Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
13696       else
13697         ResultTy = InvalidOperands(OpLoc, LHS, RHS);
13698       return ExprError();
13699     }
13700 
13701     // OpenCL special types - image, sampler, pipe, and blocks are to be used
13702     // only with a builtin functions and therefore should be disallowed here.
13703     if (LHSTy->isImageType() || RHSTy->isImageType() ||
13704         LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
13705         LHSTy->isPipeType() || RHSTy->isPipeType() ||
13706         LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
13707       ResultTy = InvalidOperands(OpLoc, LHS, RHS);
13708       return ExprError();
13709     }
13710   }
13711 
13712   switch (Opc) {
13713   case BO_Assign:
13714     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
13715     if (getLangOpts().CPlusPlus &&
13716         LHS.get()->getObjectKind() != OK_ObjCProperty) {
13717       VK = LHS.get()->getValueKind();
13718       OK = LHS.get()->getObjectKind();
13719     }
13720     if (!ResultTy.isNull()) {
13721       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
13722       DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
13723 
13724       // Avoid copying a block to the heap if the block is assigned to a local
13725       // auto variable that is declared in the same scope as the block. This
13726       // optimization is unsafe if the local variable is declared in an outer
13727       // scope. For example:
13728       //
13729       // BlockTy b;
13730       // {
13731       //   b = ^{...};
13732       // }
13733       // // It is unsafe to invoke the block here if it wasn't copied to the
13734       // // heap.
13735       // b();
13736 
13737       if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens()))
13738         if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
13739           if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
13740             if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD))
13741               BE->getBlockDecl()->setCanAvoidCopyToHeap();
13742 
13743       if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion())
13744         checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(),
13745                               NTCUC_Assignment, NTCUK_Copy);
13746     }
13747     RecordModifiableNonNullParam(*this, LHS.get());
13748     break;
13749   case BO_PtrMemD:
13750   case BO_PtrMemI:
13751     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
13752                                             Opc == BO_PtrMemI);
13753     break;
13754   case BO_Mul:
13755   case BO_Div:
13756     ConvertHalfVec = true;
13757     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
13758                                            Opc == BO_Div);
13759     break;
13760   case BO_Rem:
13761     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
13762     break;
13763   case BO_Add:
13764     ConvertHalfVec = true;
13765     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
13766     break;
13767   case BO_Sub:
13768     ConvertHalfVec = true;
13769     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
13770     break;
13771   case BO_Shl:
13772   case BO_Shr:
13773     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
13774     break;
13775   case BO_LE:
13776   case BO_LT:
13777   case BO_GE:
13778   case BO_GT:
13779     ConvertHalfVec = true;
13780     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
13781     break;
13782   case BO_EQ:
13783   case BO_NE:
13784     ConvertHalfVec = true;
13785     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
13786     break;
13787   case BO_Cmp:
13788     ConvertHalfVec = true;
13789     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
13790     assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
13791     break;
13792   case BO_And:
13793     checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
13794     LLVM_FALLTHROUGH;
13795   case BO_Xor:
13796   case BO_Or:
13797     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
13798     break;
13799   case BO_LAnd:
13800   case BO_LOr:
13801     ConvertHalfVec = true;
13802     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
13803     break;
13804   case BO_MulAssign:
13805   case BO_DivAssign:
13806     ConvertHalfVec = true;
13807     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
13808                                                Opc == BO_DivAssign);
13809     CompLHSTy = CompResultTy;
13810     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13811       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13812     break;
13813   case BO_RemAssign:
13814     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
13815     CompLHSTy = CompResultTy;
13816     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13817       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13818     break;
13819   case BO_AddAssign:
13820     ConvertHalfVec = true;
13821     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
13822     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13823       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13824     break;
13825   case BO_SubAssign:
13826     ConvertHalfVec = true;
13827     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
13828     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13829       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13830     break;
13831   case BO_ShlAssign:
13832   case BO_ShrAssign:
13833     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
13834     CompLHSTy = CompResultTy;
13835     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13836       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13837     break;
13838   case BO_AndAssign:
13839   case BO_OrAssign: // fallthrough
13840     DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
13841     LLVM_FALLTHROUGH;
13842   case BO_XorAssign:
13843     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
13844     CompLHSTy = CompResultTy;
13845     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13846       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13847     break;
13848   case BO_Comma:
13849     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
13850     if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
13851       VK = RHS.get()->getValueKind();
13852       OK = RHS.get()->getObjectKind();
13853     }
13854     break;
13855   }
13856   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
13857     return ExprError();
13858 
13859   // Some of the binary operations require promoting operands of half vector to
13860   // float vectors and truncating the result back to half vector. For now, we do
13861   // this only when HalfArgsAndReturn is set (that is, when the target is arm or
13862   // arm64).
13863   assert(isVector(RHS.get()->getType(), Context.HalfTy) ==
13864          isVector(LHS.get()->getType(), Context.HalfTy) &&
13865          "both sides are half vectors or neither sides are");
13866   ConvertHalfVec =
13867       needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get());
13868 
13869   // Check for array bounds violations for both sides of the BinaryOperator
13870   CheckArrayAccess(LHS.get());
13871   CheckArrayAccess(RHS.get());
13872 
13873   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
13874     NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
13875                                                  &Context.Idents.get("object_setClass"),
13876                                                  SourceLocation(), LookupOrdinaryName);
13877     if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
13878       SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc());
13879       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign)
13880           << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(),
13881                                         "object_setClass(")
13882           << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc),
13883                                           ",")
13884           << FixItHint::CreateInsertion(RHSLocEnd, ")");
13885     }
13886     else
13887       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
13888   }
13889   else if (const ObjCIvarRefExpr *OIRE =
13890            dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
13891     DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
13892 
13893   // Opc is not a compound assignment if CompResultTy is null.
13894   if (CompResultTy.isNull()) {
13895     if (ConvertHalfVec)
13896       return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
13897                                  OpLoc, CurFPFeatures);
13898     return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy,
13899                                   VK, OK, OpLoc, CurFPFeatures);
13900   }
13901 
13902   // Handle compound assignments.
13903   if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
13904       OK_ObjCProperty) {
13905     VK = VK_LValue;
13906     OK = LHS.get()->getObjectKind();
13907   }
13908 
13909   // The LHS is not converted to the result type for fixed-point compound
13910   // assignment as the common type is computed on demand. Reset the CompLHSTy
13911   // to the LHS type we would have gotten after unary conversions.
13912   if (CompResultTy->isFixedPointType())
13913     CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType();
13914 
13915   if (ConvertHalfVec)
13916     return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
13917                                OpLoc, CurFPFeatures);
13918 
13919   return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc,
13920                                         ResultTy, VK, OK, OpLoc, CurFPFeatures,
13921                                         CompLHSTy, CompResultTy);
13922 }
13923 
13924 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
13925 /// operators are mixed in a way that suggests that the programmer forgot that
13926 /// comparison operators have higher precedence. The most typical example of
13927 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
13928 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
13929                                       SourceLocation OpLoc, Expr *LHSExpr,
13930                                       Expr *RHSExpr) {
13931   BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
13932   BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
13933 
13934   // Check that one of the sides is a comparison operator and the other isn't.
13935   bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
13936   bool isRightComp = RHSBO && RHSBO->isComparisonOp();
13937   if (isLeftComp == isRightComp)
13938     return;
13939 
13940   // Bitwise operations are sometimes used as eager logical ops.
13941   // Don't diagnose this.
13942   bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
13943   bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
13944   if (isLeftBitwise || isRightBitwise)
13945     return;
13946 
13947   SourceRange DiagRange = isLeftComp
13948                               ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
13949                               : SourceRange(OpLoc, RHSExpr->getEndLoc());
13950   StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
13951   SourceRange ParensRange =
13952       isLeftComp
13953           ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
13954           : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
13955 
13956   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
13957     << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
13958   SuggestParentheses(Self, OpLoc,
13959     Self.PDiag(diag::note_precedence_silence) << OpStr,
13960     (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
13961   SuggestParentheses(Self, OpLoc,
13962     Self.PDiag(diag::note_precedence_bitwise_first)
13963       << BinaryOperator::getOpcodeStr(Opc),
13964     ParensRange);
13965 }
13966 
13967 /// It accepts a '&&' expr that is inside a '||' one.
13968 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
13969 /// in parentheses.
13970 static void
13971 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
13972                                        BinaryOperator *Bop) {
13973   assert(Bop->getOpcode() == BO_LAnd);
13974   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
13975       << Bop->getSourceRange() << OpLoc;
13976   SuggestParentheses(Self, Bop->getOperatorLoc(),
13977     Self.PDiag(diag::note_precedence_silence)
13978       << Bop->getOpcodeStr(),
13979     Bop->getSourceRange());
13980 }
13981 
13982 /// Returns true if the given expression can be evaluated as a constant
13983 /// 'true'.
13984 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
13985   bool Res;
13986   return !E->isValueDependent() &&
13987          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
13988 }
13989 
13990 /// Returns true if the given expression can be evaluated as a constant
13991 /// 'false'.
13992 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
13993   bool Res;
13994   return !E->isValueDependent() &&
13995          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
13996 }
13997 
13998 /// Look for '&&' in the left hand of a '||' expr.
13999 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
14000                                              Expr *LHSExpr, Expr *RHSExpr) {
14001   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
14002     if (Bop->getOpcode() == BO_LAnd) {
14003       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
14004       if (EvaluatesAsFalse(S, RHSExpr))
14005         return;
14006       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
14007       if (!EvaluatesAsTrue(S, Bop->getLHS()))
14008         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
14009     } else if (Bop->getOpcode() == BO_LOr) {
14010       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
14011         // If it's "a || b && 1 || c" we didn't warn earlier for
14012         // "a || b && 1", but warn now.
14013         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
14014           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
14015       }
14016     }
14017   }
14018 }
14019 
14020 /// Look for '&&' in the right hand of a '||' expr.
14021 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
14022                                              Expr *LHSExpr, Expr *RHSExpr) {
14023   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
14024     if (Bop->getOpcode() == BO_LAnd) {
14025       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
14026       if (EvaluatesAsFalse(S, LHSExpr))
14027         return;
14028       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
14029       if (!EvaluatesAsTrue(S, Bop->getRHS()))
14030         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
14031     }
14032   }
14033 }
14034 
14035 /// Look for bitwise op in the left or right hand of a bitwise op with
14036 /// lower precedence and emit a diagnostic together with a fixit hint that wraps
14037 /// the '&' expression in parentheses.
14038 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
14039                                          SourceLocation OpLoc, Expr *SubExpr) {
14040   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
14041     if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
14042       S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
14043         << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
14044         << Bop->getSourceRange() << OpLoc;
14045       SuggestParentheses(S, Bop->getOperatorLoc(),
14046         S.PDiag(diag::note_precedence_silence)
14047           << Bop->getOpcodeStr(),
14048         Bop->getSourceRange());
14049     }
14050   }
14051 }
14052 
14053 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
14054                                     Expr *SubExpr, StringRef Shift) {
14055   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
14056     if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
14057       StringRef Op = Bop->getOpcodeStr();
14058       S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
14059           << Bop->getSourceRange() << OpLoc << Shift << Op;
14060       SuggestParentheses(S, Bop->getOperatorLoc(),
14061           S.PDiag(diag::note_precedence_silence) << Op,
14062           Bop->getSourceRange());
14063     }
14064   }
14065 }
14066 
14067 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
14068                                  Expr *LHSExpr, Expr *RHSExpr) {
14069   CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
14070   if (!OCE)
14071     return;
14072 
14073   FunctionDecl *FD = OCE->getDirectCallee();
14074   if (!FD || !FD->isOverloadedOperator())
14075     return;
14076 
14077   OverloadedOperatorKind Kind = FD->getOverloadedOperator();
14078   if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
14079     return;
14080 
14081   S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
14082       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
14083       << (Kind == OO_LessLess);
14084   SuggestParentheses(S, OCE->getOperatorLoc(),
14085                      S.PDiag(diag::note_precedence_silence)
14086                          << (Kind == OO_LessLess ? "<<" : ">>"),
14087                      OCE->getSourceRange());
14088   SuggestParentheses(
14089       S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first),
14090       SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc()));
14091 }
14092 
14093 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
14094 /// precedence.
14095 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
14096                                     SourceLocation OpLoc, Expr *LHSExpr,
14097                                     Expr *RHSExpr){
14098   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
14099   if (BinaryOperator::isBitwiseOp(Opc))
14100     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
14101 
14102   // Diagnose "arg1 & arg2 | arg3"
14103   if ((Opc == BO_Or || Opc == BO_Xor) &&
14104       !OpLoc.isMacroID()/* Don't warn in macros. */) {
14105     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
14106     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
14107   }
14108 
14109   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
14110   // We don't warn for 'assert(a || b && "bad")' since this is safe.
14111   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
14112     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
14113     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
14114   }
14115 
14116   if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
14117       || Opc == BO_Shr) {
14118     StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
14119     DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
14120     DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
14121   }
14122 
14123   // Warn on overloaded shift operators and comparisons, such as:
14124   // cout << 5 == 4;
14125   if (BinaryOperator::isComparisonOp(Opc))
14126     DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
14127 }
14128 
14129 // Binary Operators.  'Tok' is the token for the operator.
14130 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
14131                             tok::TokenKind Kind,
14132                             Expr *LHSExpr, Expr *RHSExpr) {
14133   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
14134   assert(LHSExpr && "ActOnBinOp(): missing left expression");
14135   assert(RHSExpr && "ActOnBinOp(): missing right expression");
14136 
14137   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
14138   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
14139 
14140   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
14141 }
14142 
14143 /// Build an overloaded binary operator expression in the given scope.
14144 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
14145                                        BinaryOperatorKind Opc,
14146                                        Expr *LHS, Expr *RHS) {
14147   switch (Opc) {
14148   case BO_Assign:
14149   case BO_DivAssign:
14150   case BO_RemAssign:
14151   case BO_SubAssign:
14152   case BO_AndAssign:
14153   case BO_OrAssign:
14154   case BO_XorAssign:
14155     DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
14156     CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
14157     break;
14158   default:
14159     break;
14160   }
14161 
14162   // Find all of the overloaded operators visible from this
14163   // point. We perform both an operator-name lookup from the local
14164   // scope and an argument-dependent lookup based on the types of
14165   // the arguments.
14166   UnresolvedSet<16> Functions;
14167   OverloadedOperatorKind OverOp
14168     = BinaryOperator::getOverloadedOperator(Opc);
14169   if (Sc && OverOp != OO_None && OverOp != OO_Equal)
14170     S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
14171                                    RHS->getType(), Functions);
14172 
14173   // In C++20 onwards, we may have a second operator to look up.
14174   if (S.getLangOpts().CPlusPlus20) {
14175     if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp))
14176       S.LookupOverloadedOperatorName(ExtraOp, Sc, LHS->getType(),
14177                                      RHS->getType(), Functions);
14178   }
14179 
14180   // Build the (potentially-overloaded, potentially-dependent)
14181   // binary operation.
14182   return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
14183 }
14184 
14185 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
14186                             BinaryOperatorKind Opc,
14187                             Expr *LHSExpr, Expr *RHSExpr) {
14188   ExprResult LHS, RHS;
14189   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
14190   if (!LHS.isUsable() || !RHS.isUsable())
14191     return ExprError();
14192   LHSExpr = LHS.get();
14193   RHSExpr = RHS.get();
14194 
14195   // We want to end up calling one of checkPseudoObjectAssignment
14196   // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
14197   // both expressions are overloadable or either is type-dependent),
14198   // or CreateBuiltinBinOp (in any other case).  We also want to get
14199   // any placeholder types out of the way.
14200 
14201   // Handle pseudo-objects in the LHS.
14202   if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
14203     // Assignments with a pseudo-object l-value need special analysis.
14204     if (pty->getKind() == BuiltinType::PseudoObject &&
14205         BinaryOperator::isAssignmentOp(Opc))
14206       return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
14207 
14208     // Don't resolve overloads if the other type is overloadable.
14209     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
14210       // We can't actually test that if we still have a placeholder,
14211       // though.  Fortunately, none of the exceptions we see in that
14212       // code below are valid when the LHS is an overload set.  Note
14213       // that an overload set can be dependently-typed, but it never
14214       // instantiates to having an overloadable type.
14215       ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
14216       if (resolvedRHS.isInvalid()) return ExprError();
14217       RHSExpr = resolvedRHS.get();
14218 
14219       if (RHSExpr->isTypeDependent() ||
14220           RHSExpr->getType()->isOverloadableType())
14221         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14222     }
14223 
14224     // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
14225     // template, diagnose the missing 'template' keyword instead of diagnosing
14226     // an invalid use of a bound member function.
14227     //
14228     // Note that "A::x < b" might be valid if 'b' has an overloadable type due
14229     // to C++1z [over.over]/1.4, but we already checked for that case above.
14230     if (Opc == BO_LT && inTemplateInstantiation() &&
14231         (pty->getKind() == BuiltinType::BoundMember ||
14232          pty->getKind() == BuiltinType::Overload)) {
14233       auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
14234       if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
14235           std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) {
14236             return isa<FunctionTemplateDecl>(ND);
14237           })) {
14238         Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
14239                                 : OE->getNameLoc(),
14240              diag::err_template_kw_missing)
14241           << OE->getName().getAsString() << "";
14242         return ExprError();
14243       }
14244     }
14245 
14246     ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
14247     if (LHS.isInvalid()) return ExprError();
14248     LHSExpr = LHS.get();
14249   }
14250 
14251   // Handle pseudo-objects in the RHS.
14252   if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
14253     // An overload in the RHS can potentially be resolved by the type
14254     // being assigned to.
14255     if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
14256       if (getLangOpts().CPlusPlus &&
14257           (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
14258            LHSExpr->getType()->isOverloadableType()))
14259         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14260 
14261       return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
14262     }
14263 
14264     // Don't resolve overloads if the other type is overloadable.
14265     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
14266         LHSExpr->getType()->isOverloadableType())
14267       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14268 
14269     ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
14270     if (!resolvedRHS.isUsable()) return ExprError();
14271     RHSExpr = resolvedRHS.get();
14272   }
14273 
14274   if (getLangOpts().CPlusPlus) {
14275     // If either expression is type-dependent, always build an
14276     // overloaded op.
14277     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
14278       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14279 
14280     // Otherwise, build an overloaded op if either expression has an
14281     // overloadable type.
14282     if (LHSExpr->getType()->isOverloadableType() ||
14283         RHSExpr->getType()->isOverloadableType())
14284       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14285   }
14286 
14287   // Build a built-in binary operation.
14288   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
14289 }
14290 
14291 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
14292   if (T.isNull() || T->isDependentType())
14293     return false;
14294 
14295   if (!T->isPromotableIntegerType())
14296     return true;
14297 
14298   return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
14299 }
14300 
14301 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
14302                                       UnaryOperatorKind Opc,
14303                                       Expr *InputExpr) {
14304   ExprResult Input = InputExpr;
14305   ExprValueKind VK = VK_RValue;
14306   ExprObjectKind OK = OK_Ordinary;
14307   QualType resultType;
14308   bool CanOverflow = false;
14309 
14310   bool ConvertHalfVec = false;
14311   if (getLangOpts().OpenCL) {
14312     QualType Ty = InputExpr->getType();
14313     // The only legal unary operation for atomics is '&'.
14314     if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
14315     // OpenCL special types - image, sampler, pipe, and blocks are to be used
14316     // only with a builtin functions and therefore should be disallowed here.
14317         (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
14318         || Ty->isBlockPointerType())) {
14319       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14320                        << InputExpr->getType()
14321                        << Input.get()->getSourceRange());
14322     }
14323   }
14324 
14325   switch (Opc) {
14326   case UO_PreInc:
14327   case UO_PreDec:
14328   case UO_PostInc:
14329   case UO_PostDec:
14330     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
14331                                                 OpLoc,
14332                                                 Opc == UO_PreInc ||
14333                                                 Opc == UO_PostInc,
14334                                                 Opc == UO_PreInc ||
14335                                                 Opc == UO_PreDec);
14336     CanOverflow = isOverflowingIntegerType(Context, resultType);
14337     break;
14338   case UO_AddrOf:
14339     resultType = CheckAddressOfOperand(Input, OpLoc);
14340     CheckAddressOfNoDeref(InputExpr);
14341     RecordModifiableNonNullParam(*this, InputExpr);
14342     break;
14343   case UO_Deref: {
14344     Input = DefaultFunctionArrayLvalueConversion(Input.get());
14345     if (Input.isInvalid()) return ExprError();
14346     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
14347     break;
14348   }
14349   case UO_Plus:
14350   case UO_Minus:
14351     CanOverflow = Opc == UO_Minus &&
14352                   isOverflowingIntegerType(Context, Input.get()->getType());
14353     Input = UsualUnaryConversions(Input.get());
14354     if (Input.isInvalid()) return ExprError();
14355     // Unary plus and minus require promoting an operand of half vector to a
14356     // float vector and truncating the result back to a half vector. For now, we
14357     // do this only when HalfArgsAndReturns is set (that is, when the target is
14358     // arm or arm64).
14359     ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get());
14360 
14361     // If the operand is a half vector, promote it to a float vector.
14362     if (ConvertHalfVec)
14363       Input = convertVector(Input.get(), Context.FloatTy, *this);
14364     resultType = Input.get()->getType();
14365     if (resultType->isDependentType())
14366       break;
14367     if (resultType->isArithmeticType()) // C99 6.5.3.3p1
14368       break;
14369     else if (resultType->isVectorType() &&
14370              // The z vector extensions don't allow + or - with bool vectors.
14371              (!Context.getLangOpts().ZVector ||
14372               resultType->castAs<VectorType>()->getVectorKind() !=
14373               VectorType::AltiVecBool))
14374       break;
14375     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
14376              Opc == UO_Plus &&
14377              resultType->isPointerType())
14378       break;
14379 
14380     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14381       << resultType << Input.get()->getSourceRange());
14382 
14383   case UO_Not: // bitwise complement
14384     Input = UsualUnaryConversions(Input.get());
14385     if (Input.isInvalid())
14386       return ExprError();
14387     resultType = Input.get()->getType();
14388     if (resultType->isDependentType())
14389       break;
14390     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
14391     if (resultType->isComplexType() || resultType->isComplexIntegerType())
14392       // C99 does not support '~' for complex conjugation.
14393       Diag(OpLoc, diag::ext_integer_complement_complex)
14394           << resultType << Input.get()->getSourceRange();
14395     else if (resultType->hasIntegerRepresentation())
14396       break;
14397     else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
14398       // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
14399       // on vector float types.
14400       QualType T = resultType->castAs<ExtVectorType>()->getElementType();
14401       if (!T->isIntegerType())
14402         return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14403                           << resultType << Input.get()->getSourceRange());
14404     } else {
14405       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14406                        << resultType << Input.get()->getSourceRange());
14407     }
14408     break;
14409 
14410   case UO_LNot: // logical negation
14411     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
14412     Input = DefaultFunctionArrayLvalueConversion(Input.get());
14413     if (Input.isInvalid()) return ExprError();
14414     resultType = Input.get()->getType();
14415 
14416     // Though we still have to promote half FP to float...
14417     if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
14418       Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
14419       resultType = Context.FloatTy;
14420     }
14421 
14422     if (resultType->isDependentType())
14423       break;
14424     if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
14425       // C99 6.5.3.3p1: ok, fallthrough;
14426       if (Context.getLangOpts().CPlusPlus) {
14427         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
14428         // operand contextually converted to bool.
14429         Input = ImpCastExprToType(Input.get(), Context.BoolTy,
14430                                   ScalarTypeToBooleanCastKind(resultType));
14431       } else if (Context.getLangOpts().OpenCL &&
14432                  Context.getLangOpts().OpenCLVersion < 120) {
14433         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
14434         // operate on scalar float types.
14435         if (!resultType->isIntegerType() && !resultType->isPointerType())
14436           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14437                            << resultType << Input.get()->getSourceRange());
14438       }
14439     } else if (resultType->isExtVectorType()) {
14440       if (Context.getLangOpts().OpenCL &&
14441           Context.getLangOpts().OpenCLVersion < 120 &&
14442           !Context.getLangOpts().OpenCLCPlusPlus) {
14443         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
14444         // operate on vector float types.
14445         QualType T = resultType->castAs<ExtVectorType>()->getElementType();
14446         if (!T->isIntegerType())
14447           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14448                            << resultType << Input.get()->getSourceRange());
14449       }
14450       // Vector logical not returns the signed variant of the operand type.
14451       resultType = GetSignedVectorType(resultType);
14452       break;
14453     } else {
14454       // FIXME: GCC's vector extension permits the usage of '!' with a vector
14455       //        type in C++. We should allow that here too.
14456       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14457         << resultType << Input.get()->getSourceRange());
14458     }
14459 
14460     // LNot always has type int. C99 6.5.3.3p5.
14461     // In C++, it's bool. C++ 5.3.1p8
14462     resultType = Context.getLogicalOperationType();
14463     break;
14464   case UO_Real:
14465   case UO_Imag:
14466     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
14467     // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
14468     // complex l-values to ordinary l-values and all other values to r-values.
14469     if (Input.isInvalid()) return ExprError();
14470     if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
14471       if (Input.get()->getValueKind() != VK_RValue &&
14472           Input.get()->getObjectKind() == OK_Ordinary)
14473         VK = Input.get()->getValueKind();
14474     } else if (!getLangOpts().CPlusPlus) {
14475       // In C, a volatile scalar is read by __imag. In C++, it is not.
14476       Input = DefaultLvalueConversion(Input.get());
14477     }
14478     break;
14479   case UO_Extension:
14480     resultType = Input.get()->getType();
14481     VK = Input.get()->getValueKind();
14482     OK = Input.get()->getObjectKind();
14483     break;
14484   case UO_Coawait:
14485     // It's unnecessary to represent the pass-through operator co_await in the
14486     // AST; just return the input expression instead.
14487     assert(!Input.get()->getType()->isDependentType() &&
14488                    "the co_await expression must be non-dependant before "
14489                    "building operator co_await");
14490     return Input;
14491   }
14492   if (resultType.isNull() || Input.isInvalid())
14493     return ExprError();
14494 
14495   // Check for array bounds violations in the operand of the UnaryOperator,
14496   // except for the '*' and '&' operators that have to be handled specially
14497   // by CheckArrayAccess (as there are special cases like &array[arraysize]
14498   // that are explicitly defined as valid by the standard).
14499   if (Opc != UO_AddrOf && Opc != UO_Deref)
14500     CheckArrayAccess(Input.get());
14501 
14502   auto *UO = UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK,
14503                                    OK, OpLoc, CanOverflow, CurFPFeatures);
14504 
14505   if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) &&
14506       !isa<ArrayType>(UO->getType().getDesugaredType(Context)))
14507     ExprEvalContexts.back().PossibleDerefs.insert(UO);
14508 
14509   // Convert the result back to a half vector.
14510   if (ConvertHalfVec)
14511     return convertVector(UO, Context.HalfTy, *this);
14512   return UO;
14513 }
14514 
14515 /// Determine whether the given expression is a qualified member
14516 /// access expression, of a form that could be turned into a pointer to member
14517 /// with the address-of operator.
14518 bool Sema::isQualifiedMemberAccess(Expr *E) {
14519   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
14520     if (!DRE->getQualifier())
14521       return false;
14522 
14523     ValueDecl *VD = DRE->getDecl();
14524     if (!VD->isCXXClassMember())
14525       return false;
14526 
14527     if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
14528       return true;
14529     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
14530       return Method->isInstance();
14531 
14532     return false;
14533   }
14534 
14535   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
14536     if (!ULE->getQualifier())
14537       return false;
14538 
14539     for (NamedDecl *D : ULE->decls()) {
14540       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
14541         if (Method->isInstance())
14542           return true;
14543       } else {
14544         // Overload set does not contain methods.
14545         break;
14546       }
14547     }
14548 
14549     return false;
14550   }
14551 
14552   return false;
14553 }
14554 
14555 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
14556                               UnaryOperatorKind Opc, Expr *Input) {
14557   // First things first: handle placeholders so that the
14558   // overloaded-operator check considers the right type.
14559   if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
14560     // Increment and decrement of pseudo-object references.
14561     if (pty->getKind() == BuiltinType::PseudoObject &&
14562         UnaryOperator::isIncrementDecrementOp(Opc))
14563       return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
14564 
14565     // extension is always a builtin operator.
14566     if (Opc == UO_Extension)
14567       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
14568 
14569     // & gets special logic for several kinds of placeholder.
14570     // The builtin code knows what to do.
14571     if (Opc == UO_AddrOf &&
14572         (pty->getKind() == BuiltinType::Overload ||
14573          pty->getKind() == BuiltinType::UnknownAny ||
14574          pty->getKind() == BuiltinType::BoundMember))
14575       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
14576 
14577     // Anything else needs to be handled now.
14578     ExprResult Result = CheckPlaceholderExpr(Input);
14579     if (Result.isInvalid()) return ExprError();
14580     Input = Result.get();
14581   }
14582 
14583   if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
14584       UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
14585       !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
14586     // Find all of the overloaded operators visible from this
14587     // point. We perform both an operator-name lookup from the local
14588     // scope and an argument-dependent lookup based on the types of
14589     // the arguments.
14590     UnresolvedSet<16> Functions;
14591     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
14592     if (S && OverOp != OO_None)
14593       LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
14594                                    Functions);
14595 
14596     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
14597   }
14598 
14599   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
14600 }
14601 
14602 // Unary Operators.  'Tok' is the token for the operator.
14603 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
14604                               tok::TokenKind Op, Expr *Input) {
14605   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
14606 }
14607 
14608 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
14609 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
14610                                 LabelDecl *TheDecl) {
14611   TheDecl->markUsed(Context);
14612   // Create the AST node.  The address of a label always has type 'void*'.
14613   return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
14614                                      Context.getPointerType(Context.VoidTy));
14615 }
14616 
14617 void Sema::ActOnStartStmtExpr() {
14618   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
14619 }
14620 
14621 void Sema::ActOnStmtExprError() {
14622   // Note that function is also called by TreeTransform when leaving a
14623   // StmtExpr scope without rebuilding anything.
14624 
14625   DiscardCleanupsInEvaluationContext();
14626   PopExpressionEvaluationContext();
14627 }
14628 
14629 ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt,
14630                                SourceLocation RPLoc) {
14631   return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S));
14632 }
14633 
14634 ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
14635                                SourceLocation RPLoc, unsigned TemplateDepth) {
14636   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
14637   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
14638 
14639   if (hasAnyUnrecoverableErrorsInThisFunction())
14640     DiscardCleanupsInEvaluationContext();
14641   assert(!Cleanup.exprNeedsCleanups() &&
14642          "cleanups within StmtExpr not correctly bound!");
14643   PopExpressionEvaluationContext();
14644 
14645   // FIXME: there are a variety of strange constraints to enforce here, for
14646   // example, it is not possible to goto into a stmt expression apparently.
14647   // More semantic analysis is needed.
14648 
14649   // If there are sub-stmts in the compound stmt, take the type of the last one
14650   // as the type of the stmtexpr.
14651   QualType Ty = Context.VoidTy;
14652   bool StmtExprMayBindToTemp = false;
14653   if (!Compound->body_empty()) {
14654     // For GCC compatibility we get the last Stmt excluding trailing NullStmts.
14655     if (const auto *LastStmt =
14656             dyn_cast<ValueStmt>(Compound->getStmtExprResult())) {
14657       if (const Expr *Value = LastStmt->getExprStmt()) {
14658         StmtExprMayBindToTemp = true;
14659         Ty = Value->getType();
14660       }
14661     }
14662   }
14663 
14664   // FIXME: Check that expression type is complete/non-abstract; statement
14665   // expressions are not lvalues.
14666   Expr *ResStmtExpr =
14667       new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth);
14668   if (StmtExprMayBindToTemp)
14669     return MaybeBindToTemporary(ResStmtExpr);
14670   return ResStmtExpr;
14671 }
14672 
14673 ExprResult Sema::ActOnStmtExprResult(ExprResult ER) {
14674   if (ER.isInvalid())
14675     return ExprError();
14676 
14677   // Do function/array conversion on the last expression, but not
14678   // lvalue-to-rvalue.  However, initialize an unqualified type.
14679   ER = DefaultFunctionArrayConversion(ER.get());
14680   if (ER.isInvalid())
14681     return ExprError();
14682   Expr *E = ER.get();
14683 
14684   if (E->isTypeDependent())
14685     return E;
14686 
14687   // In ARC, if the final expression ends in a consume, splice
14688   // the consume out and bind it later.  In the alternate case
14689   // (when dealing with a retainable type), the result
14690   // initialization will create a produce.  In both cases the
14691   // result will be +1, and we'll need to balance that out with
14692   // a bind.
14693   auto *Cast = dyn_cast<ImplicitCastExpr>(E);
14694   if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
14695     return Cast->getSubExpr();
14696 
14697   // FIXME: Provide a better location for the initialization.
14698   return PerformCopyInitialization(
14699       InitializedEntity::InitializeStmtExprResult(
14700           E->getBeginLoc(), E->getType().getUnqualifiedType()),
14701       SourceLocation(), E);
14702 }
14703 
14704 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
14705                                       TypeSourceInfo *TInfo,
14706                                       ArrayRef<OffsetOfComponent> Components,
14707                                       SourceLocation RParenLoc) {
14708   QualType ArgTy = TInfo->getType();
14709   bool Dependent = ArgTy->isDependentType();
14710   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
14711 
14712   // We must have at least one component that refers to the type, and the first
14713   // one is known to be a field designator.  Verify that the ArgTy represents
14714   // a struct/union/class.
14715   if (!Dependent && !ArgTy->isRecordType())
14716     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
14717                        << ArgTy << TypeRange);
14718 
14719   // Type must be complete per C99 7.17p3 because a declaring a variable
14720   // with an incomplete type would be ill-formed.
14721   if (!Dependent
14722       && RequireCompleteType(BuiltinLoc, ArgTy,
14723                              diag::err_offsetof_incomplete_type, TypeRange))
14724     return ExprError();
14725 
14726   bool DidWarnAboutNonPOD = false;
14727   QualType CurrentType = ArgTy;
14728   SmallVector<OffsetOfNode, 4> Comps;
14729   SmallVector<Expr*, 4> Exprs;
14730   for (const OffsetOfComponent &OC : Components) {
14731     if (OC.isBrackets) {
14732       // Offset of an array sub-field.  TODO: Should we allow vector elements?
14733       if (!CurrentType->isDependentType()) {
14734         const ArrayType *AT = Context.getAsArrayType(CurrentType);
14735         if(!AT)
14736           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
14737                            << CurrentType);
14738         CurrentType = AT->getElementType();
14739       } else
14740         CurrentType = Context.DependentTy;
14741 
14742       ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
14743       if (IdxRval.isInvalid())
14744         return ExprError();
14745       Expr *Idx = IdxRval.get();
14746 
14747       // The expression must be an integral expression.
14748       // FIXME: An integral constant expression?
14749       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
14750           !Idx->getType()->isIntegerType())
14751         return ExprError(
14752             Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer)
14753             << Idx->getSourceRange());
14754 
14755       // Record this array index.
14756       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
14757       Exprs.push_back(Idx);
14758       continue;
14759     }
14760 
14761     // Offset of a field.
14762     if (CurrentType->isDependentType()) {
14763       // We have the offset of a field, but we can't look into the dependent
14764       // type. Just record the identifier of the field.
14765       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
14766       CurrentType = Context.DependentTy;
14767       continue;
14768     }
14769 
14770     // We need to have a complete type to look into.
14771     if (RequireCompleteType(OC.LocStart, CurrentType,
14772                             diag::err_offsetof_incomplete_type))
14773       return ExprError();
14774 
14775     // Look for the designated field.
14776     const RecordType *RC = CurrentType->getAs<RecordType>();
14777     if (!RC)
14778       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
14779                        << CurrentType);
14780     RecordDecl *RD = RC->getDecl();
14781 
14782     // C++ [lib.support.types]p5:
14783     //   The macro offsetof accepts a restricted set of type arguments in this
14784     //   International Standard. type shall be a POD structure or a POD union
14785     //   (clause 9).
14786     // C++11 [support.types]p4:
14787     //   If type is not a standard-layout class (Clause 9), the results are
14788     //   undefined.
14789     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
14790       bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
14791       unsigned DiagID =
14792         LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
14793                             : diag::ext_offsetof_non_pod_type;
14794 
14795       if (!IsSafe && !DidWarnAboutNonPOD &&
14796           DiagRuntimeBehavior(BuiltinLoc, nullptr,
14797                               PDiag(DiagID)
14798                               << SourceRange(Components[0].LocStart, OC.LocEnd)
14799                               << CurrentType))
14800         DidWarnAboutNonPOD = true;
14801     }
14802 
14803     // Look for the field.
14804     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
14805     LookupQualifiedName(R, RD);
14806     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
14807     IndirectFieldDecl *IndirectMemberDecl = nullptr;
14808     if (!MemberDecl) {
14809       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
14810         MemberDecl = IndirectMemberDecl->getAnonField();
14811     }
14812 
14813     if (!MemberDecl)
14814       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
14815                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
14816                                                               OC.LocEnd));
14817 
14818     // C99 7.17p3:
14819     //   (If the specified member is a bit-field, the behavior is undefined.)
14820     //
14821     // We diagnose this as an error.
14822     if (MemberDecl->isBitField()) {
14823       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
14824         << MemberDecl->getDeclName()
14825         << SourceRange(BuiltinLoc, RParenLoc);
14826       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
14827       return ExprError();
14828     }
14829 
14830     RecordDecl *Parent = MemberDecl->getParent();
14831     if (IndirectMemberDecl)
14832       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
14833 
14834     // If the member was found in a base class, introduce OffsetOfNodes for
14835     // the base class indirections.
14836     CXXBasePaths Paths;
14837     if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
14838                       Paths)) {
14839       if (Paths.getDetectedVirtual()) {
14840         Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
14841           << MemberDecl->getDeclName()
14842           << SourceRange(BuiltinLoc, RParenLoc);
14843         return ExprError();
14844       }
14845 
14846       CXXBasePath &Path = Paths.front();
14847       for (const CXXBasePathElement &B : Path)
14848         Comps.push_back(OffsetOfNode(B.Base));
14849     }
14850 
14851     if (IndirectMemberDecl) {
14852       for (auto *FI : IndirectMemberDecl->chain()) {
14853         assert(isa<FieldDecl>(FI));
14854         Comps.push_back(OffsetOfNode(OC.LocStart,
14855                                      cast<FieldDecl>(FI), OC.LocEnd));
14856       }
14857     } else
14858       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
14859 
14860     CurrentType = MemberDecl->getType().getNonReferenceType();
14861   }
14862 
14863   return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
14864                               Comps, Exprs, RParenLoc);
14865 }
14866 
14867 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
14868                                       SourceLocation BuiltinLoc,
14869                                       SourceLocation TypeLoc,
14870                                       ParsedType ParsedArgTy,
14871                                       ArrayRef<OffsetOfComponent> Components,
14872                                       SourceLocation RParenLoc) {
14873 
14874   TypeSourceInfo *ArgTInfo;
14875   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
14876   if (ArgTy.isNull())
14877     return ExprError();
14878 
14879   if (!ArgTInfo)
14880     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
14881 
14882   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
14883 }
14884 
14885 
14886 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
14887                                  Expr *CondExpr,
14888                                  Expr *LHSExpr, Expr *RHSExpr,
14889                                  SourceLocation RPLoc) {
14890   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
14891 
14892   ExprValueKind VK = VK_RValue;
14893   ExprObjectKind OK = OK_Ordinary;
14894   QualType resType;
14895   bool CondIsTrue = false;
14896   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
14897     resType = Context.DependentTy;
14898   } else {
14899     // The conditional expression is required to be a constant expression.
14900     llvm::APSInt condEval(32);
14901     ExprResult CondICE
14902       = VerifyIntegerConstantExpression(CondExpr, &condEval,
14903           diag::err_typecheck_choose_expr_requires_constant, false);
14904     if (CondICE.isInvalid())
14905       return ExprError();
14906     CondExpr = CondICE.get();
14907     CondIsTrue = condEval.getZExtValue();
14908 
14909     // If the condition is > zero, then the AST type is the same as the LHSExpr.
14910     Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
14911 
14912     resType = ActiveExpr->getType();
14913     VK = ActiveExpr->getValueKind();
14914     OK = ActiveExpr->getObjectKind();
14915   }
14916 
14917   return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
14918                                   resType, VK, OK, RPLoc, CondIsTrue);
14919 }
14920 
14921 //===----------------------------------------------------------------------===//
14922 // Clang Extensions.
14923 //===----------------------------------------------------------------------===//
14924 
14925 /// ActOnBlockStart - This callback is invoked when a block literal is started.
14926 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
14927   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
14928 
14929   if (LangOpts.CPlusPlus) {
14930     MangleNumberingContext *MCtx;
14931     Decl *ManglingContextDecl;
14932     std::tie(MCtx, ManglingContextDecl) =
14933         getCurrentMangleNumberContext(Block->getDeclContext());
14934     if (MCtx) {
14935       unsigned ManglingNumber = MCtx->getManglingNumber(Block);
14936       Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
14937     }
14938   }
14939 
14940   PushBlockScope(CurScope, Block);
14941   CurContext->addDecl(Block);
14942   if (CurScope)
14943     PushDeclContext(CurScope, Block);
14944   else
14945     CurContext = Block;
14946 
14947   getCurBlock()->HasImplicitReturnType = true;
14948 
14949   // Enter a new evaluation context to insulate the block from any
14950   // cleanups from the enclosing full-expression.
14951   PushExpressionEvaluationContext(
14952       ExpressionEvaluationContext::PotentiallyEvaluated);
14953 }
14954 
14955 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
14956                                Scope *CurScope) {
14957   assert(ParamInfo.getIdentifier() == nullptr &&
14958          "block-id should have no identifier!");
14959   assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteralContext);
14960   BlockScopeInfo *CurBlock = getCurBlock();
14961 
14962   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
14963   QualType T = Sig->getType();
14964 
14965   // FIXME: We should allow unexpanded parameter packs here, but that would,
14966   // in turn, make the block expression contain unexpanded parameter packs.
14967   if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
14968     // Drop the parameters.
14969     FunctionProtoType::ExtProtoInfo EPI;
14970     EPI.HasTrailingReturn = false;
14971     EPI.TypeQuals.addConst();
14972     T = Context.getFunctionType(Context.DependentTy, None, EPI);
14973     Sig = Context.getTrivialTypeSourceInfo(T);
14974   }
14975 
14976   // GetTypeForDeclarator always produces a function type for a block
14977   // literal signature.  Furthermore, it is always a FunctionProtoType
14978   // unless the function was written with a typedef.
14979   assert(T->isFunctionType() &&
14980          "GetTypeForDeclarator made a non-function block signature");
14981 
14982   // Look for an explicit signature in that function type.
14983   FunctionProtoTypeLoc ExplicitSignature;
14984 
14985   if ((ExplicitSignature = Sig->getTypeLoc()
14986                                .getAsAdjusted<FunctionProtoTypeLoc>())) {
14987 
14988     // Check whether that explicit signature was synthesized by
14989     // GetTypeForDeclarator.  If so, don't save that as part of the
14990     // written signature.
14991     if (ExplicitSignature.getLocalRangeBegin() ==
14992         ExplicitSignature.getLocalRangeEnd()) {
14993       // This would be much cheaper if we stored TypeLocs instead of
14994       // TypeSourceInfos.
14995       TypeLoc Result = ExplicitSignature.getReturnLoc();
14996       unsigned Size = Result.getFullDataSize();
14997       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
14998       Sig->getTypeLoc().initializeFullCopy(Result, Size);
14999 
15000       ExplicitSignature = FunctionProtoTypeLoc();
15001     }
15002   }
15003 
15004   CurBlock->TheDecl->setSignatureAsWritten(Sig);
15005   CurBlock->FunctionType = T;
15006 
15007   const FunctionType *Fn = T->getAs<FunctionType>();
15008   QualType RetTy = Fn->getReturnType();
15009   bool isVariadic =
15010     (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
15011 
15012   CurBlock->TheDecl->setIsVariadic(isVariadic);
15013 
15014   // Context.DependentTy is used as a placeholder for a missing block
15015   // return type.  TODO:  what should we do with declarators like:
15016   //   ^ * { ... }
15017   // If the answer is "apply template argument deduction"....
15018   if (RetTy != Context.DependentTy) {
15019     CurBlock->ReturnType = RetTy;
15020     CurBlock->TheDecl->setBlockMissingReturnType(false);
15021     CurBlock->HasImplicitReturnType = false;
15022   }
15023 
15024   // Push block parameters from the declarator if we had them.
15025   SmallVector<ParmVarDecl*, 8> Params;
15026   if (ExplicitSignature) {
15027     for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
15028       ParmVarDecl *Param = ExplicitSignature.getParam(I);
15029       if (Param->getIdentifier() == nullptr && !Param->isImplicit() &&
15030           !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) {
15031         // Diagnose this as an extension in C17 and earlier.
15032         if (!getLangOpts().C2x)
15033           Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x);
15034       }
15035       Params.push_back(Param);
15036     }
15037 
15038   // Fake up parameter variables if we have a typedef, like
15039   //   ^ fntype { ... }
15040   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
15041     for (const auto &I : Fn->param_types()) {
15042       ParmVarDecl *Param = BuildParmVarDeclForTypedef(
15043           CurBlock->TheDecl, ParamInfo.getBeginLoc(), I);
15044       Params.push_back(Param);
15045     }
15046   }
15047 
15048   // Set the parameters on the block decl.
15049   if (!Params.empty()) {
15050     CurBlock->TheDecl->setParams(Params);
15051     CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
15052                              /*CheckParameterNames=*/false);
15053   }
15054 
15055   // Finally we can process decl attributes.
15056   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
15057 
15058   // Put the parameter variables in scope.
15059   for (auto AI : CurBlock->TheDecl->parameters()) {
15060     AI->setOwningFunction(CurBlock->TheDecl);
15061 
15062     // If this has an identifier, add it to the scope stack.
15063     if (AI->getIdentifier()) {
15064       CheckShadow(CurBlock->TheScope, AI);
15065 
15066       PushOnScopeChains(AI, CurBlock->TheScope);
15067     }
15068   }
15069 }
15070 
15071 /// ActOnBlockError - If there is an error parsing a block, this callback
15072 /// is invoked to pop the information about the block from the action impl.
15073 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
15074   // Leave the expression-evaluation context.
15075   DiscardCleanupsInEvaluationContext();
15076   PopExpressionEvaluationContext();
15077 
15078   // Pop off CurBlock, handle nested blocks.
15079   PopDeclContext();
15080   PopFunctionScopeInfo();
15081 }
15082 
15083 /// ActOnBlockStmtExpr - This is called when the body of a block statement
15084 /// literal was successfully completed.  ^(int x){...}
15085 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
15086                                     Stmt *Body, Scope *CurScope) {
15087   // If blocks are disabled, emit an error.
15088   if (!LangOpts.Blocks)
15089     Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
15090 
15091   // Leave the expression-evaluation context.
15092   if (hasAnyUnrecoverableErrorsInThisFunction())
15093     DiscardCleanupsInEvaluationContext();
15094   assert(!Cleanup.exprNeedsCleanups() &&
15095          "cleanups within block not correctly bound!");
15096   PopExpressionEvaluationContext();
15097 
15098   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
15099   BlockDecl *BD = BSI->TheDecl;
15100 
15101   if (BSI->HasImplicitReturnType)
15102     deduceClosureReturnType(*BSI);
15103 
15104   QualType RetTy = Context.VoidTy;
15105   if (!BSI->ReturnType.isNull())
15106     RetTy = BSI->ReturnType;
15107 
15108   bool NoReturn = BD->hasAttr<NoReturnAttr>();
15109   QualType BlockTy;
15110 
15111   // If the user wrote a function type in some form, try to use that.
15112   if (!BSI->FunctionType.isNull()) {
15113     const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>();
15114 
15115     FunctionType::ExtInfo Ext = FTy->getExtInfo();
15116     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
15117 
15118     // Turn protoless block types into nullary block types.
15119     if (isa<FunctionNoProtoType>(FTy)) {
15120       FunctionProtoType::ExtProtoInfo EPI;
15121       EPI.ExtInfo = Ext;
15122       BlockTy = Context.getFunctionType(RetTy, None, EPI);
15123 
15124     // Otherwise, if we don't need to change anything about the function type,
15125     // preserve its sugar structure.
15126     } else if (FTy->getReturnType() == RetTy &&
15127                (!NoReturn || FTy->getNoReturnAttr())) {
15128       BlockTy = BSI->FunctionType;
15129 
15130     // Otherwise, make the minimal modifications to the function type.
15131     } else {
15132       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
15133       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
15134       EPI.TypeQuals = Qualifiers();
15135       EPI.ExtInfo = Ext;
15136       BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
15137     }
15138 
15139   // If we don't have a function type, just build one from nothing.
15140   } else {
15141     FunctionProtoType::ExtProtoInfo EPI;
15142     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
15143     BlockTy = Context.getFunctionType(RetTy, None, EPI);
15144   }
15145 
15146   DiagnoseUnusedParameters(BD->parameters());
15147   BlockTy = Context.getBlockPointerType(BlockTy);
15148 
15149   // If needed, diagnose invalid gotos and switches in the block.
15150   if (getCurFunction()->NeedsScopeChecking() &&
15151       !PP.isCodeCompletionEnabled())
15152     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
15153 
15154   BD->setBody(cast<CompoundStmt>(Body));
15155 
15156   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
15157     DiagnoseUnguardedAvailabilityViolations(BD);
15158 
15159   // Try to apply the named return value optimization. We have to check again
15160   // if we can do this, though, because blocks keep return statements around
15161   // to deduce an implicit return type.
15162   if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
15163       !BD->isDependentContext())
15164     computeNRVO(Body, BSI);
15165 
15166   if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() ||
15167       RetTy.hasNonTrivialToPrimitiveCopyCUnion())
15168     checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn,
15169                           NTCUK_Destruct|NTCUK_Copy);
15170 
15171   PopDeclContext();
15172 
15173   // Pop the block scope now but keep it alive to the end of this function.
15174   AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
15175   PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy);
15176 
15177   // Set the captured variables on the block.
15178   SmallVector<BlockDecl::Capture, 4> Captures;
15179   for (Capture &Cap : BSI->Captures) {
15180     if (Cap.isInvalid() || Cap.isThisCapture())
15181       continue;
15182 
15183     VarDecl *Var = Cap.getVariable();
15184     Expr *CopyExpr = nullptr;
15185     if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) {
15186       if (const RecordType *Record =
15187               Cap.getCaptureType()->getAs<RecordType>()) {
15188         // The capture logic needs the destructor, so make sure we mark it.
15189         // Usually this is unnecessary because most local variables have
15190         // their destructors marked at declaration time, but parameters are
15191         // an exception because it's technically only the call site that
15192         // actually requires the destructor.
15193         if (isa<ParmVarDecl>(Var))
15194           FinalizeVarWithDestructor(Var, Record);
15195 
15196         // Enter a separate potentially-evaluated context while building block
15197         // initializers to isolate their cleanups from those of the block
15198         // itself.
15199         // FIXME: Is this appropriate even when the block itself occurs in an
15200         // unevaluated operand?
15201         EnterExpressionEvaluationContext EvalContext(
15202             *this, ExpressionEvaluationContext::PotentiallyEvaluated);
15203 
15204         SourceLocation Loc = Cap.getLocation();
15205 
15206         ExprResult Result = BuildDeclarationNameExpr(
15207             CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
15208 
15209         // According to the blocks spec, the capture of a variable from
15210         // the stack requires a const copy constructor.  This is not true
15211         // of the copy/move done to move a __block variable to the heap.
15212         if (!Result.isInvalid() &&
15213             !Result.get()->getType().isConstQualified()) {
15214           Result = ImpCastExprToType(Result.get(),
15215                                      Result.get()->getType().withConst(),
15216                                      CK_NoOp, VK_LValue);
15217         }
15218 
15219         if (!Result.isInvalid()) {
15220           Result = PerformCopyInitialization(
15221               InitializedEntity::InitializeBlock(Var->getLocation(),
15222                                                  Cap.getCaptureType(), false),
15223               Loc, Result.get());
15224         }
15225 
15226         // Build a full-expression copy expression if initialization
15227         // succeeded and used a non-trivial constructor.  Recover from
15228         // errors by pretending that the copy isn't necessary.
15229         if (!Result.isInvalid() &&
15230             !cast<CXXConstructExpr>(Result.get())->getConstructor()
15231                 ->isTrivial()) {
15232           Result = MaybeCreateExprWithCleanups(Result);
15233           CopyExpr = Result.get();
15234         }
15235       }
15236     }
15237 
15238     BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(),
15239                               CopyExpr);
15240     Captures.push_back(NewCap);
15241   }
15242   BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
15243 
15244   BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy);
15245 
15246   // If the block isn't obviously global, i.e. it captures anything at
15247   // all, then we need to do a few things in the surrounding context:
15248   if (Result->getBlockDecl()->hasCaptures()) {
15249     // First, this expression has a new cleanup object.
15250     ExprCleanupObjects.push_back(Result->getBlockDecl());
15251     Cleanup.setExprNeedsCleanups(true);
15252 
15253     // It also gets a branch-protected scope if any of the captured
15254     // variables needs destruction.
15255     for (const auto &CI : Result->getBlockDecl()->captures()) {
15256       const VarDecl *var = CI.getVariable();
15257       if (var->getType().isDestructedType() != QualType::DK_none) {
15258         setFunctionHasBranchProtectedScope();
15259         break;
15260       }
15261     }
15262   }
15263 
15264   if (getCurFunction())
15265     getCurFunction()->addBlock(BD);
15266 
15267   return Result;
15268 }
15269 
15270 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
15271                             SourceLocation RPLoc) {
15272   TypeSourceInfo *TInfo;
15273   GetTypeFromParser(Ty, &TInfo);
15274   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
15275 }
15276 
15277 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
15278                                 Expr *E, TypeSourceInfo *TInfo,
15279                                 SourceLocation RPLoc) {
15280   Expr *OrigExpr = E;
15281   bool IsMS = false;
15282 
15283   // CUDA device code does not support varargs.
15284   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
15285     if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
15286       CUDAFunctionTarget T = IdentifyCUDATarget(F);
15287       if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
15288         return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device));
15289     }
15290   }
15291 
15292   // NVPTX does not support va_arg expression.
15293   if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
15294       Context.getTargetInfo().getTriple().isNVPTX())
15295     targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device);
15296 
15297   // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
15298   // as Microsoft ABI on an actual Microsoft platform, where
15299   // __builtin_ms_va_list and __builtin_va_list are the same.)
15300   if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
15301       Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
15302     QualType MSVaListType = Context.getBuiltinMSVaListType();
15303     if (Context.hasSameType(MSVaListType, E->getType())) {
15304       if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
15305         return ExprError();
15306       IsMS = true;
15307     }
15308   }
15309 
15310   // Get the va_list type
15311   QualType VaListType = Context.getBuiltinVaListType();
15312   if (!IsMS) {
15313     if (VaListType->isArrayType()) {
15314       // Deal with implicit array decay; for example, on x86-64,
15315       // va_list is an array, but it's supposed to decay to
15316       // a pointer for va_arg.
15317       VaListType = Context.getArrayDecayedType(VaListType);
15318       // Make sure the input expression also decays appropriately.
15319       ExprResult Result = UsualUnaryConversions(E);
15320       if (Result.isInvalid())
15321         return ExprError();
15322       E = Result.get();
15323     } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
15324       // If va_list is a record type and we are compiling in C++ mode,
15325       // check the argument using reference binding.
15326       InitializedEntity Entity = InitializedEntity::InitializeParameter(
15327           Context, Context.getLValueReferenceType(VaListType), false);
15328       ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
15329       if (Init.isInvalid())
15330         return ExprError();
15331       E = Init.getAs<Expr>();
15332     } else {
15333       // Otherwise, the va_list argument must be an l-value because
15334       // it is modified by va_arg.
15335       if (!E->isTypeDependent() &&
15336           CheckForModifiableLvalue(E, BuiltinLoc, *this))
15337         return ExprError();
15338     }
15339   }
15340 
15341   if (!IsMS && !E->isTypeDependent() &&
15342       !Context.hasSameType(VaListType, E->getType()))
15343     return ExprError(
15344         Diag(E->getBeginLoc(),
15345              diag::err_first_argument_to_va_arg_not_of_type_va_list)
15346         << OrigExpr->getType() << E->getSourceRange());
15347 
15348   if (!TInfo->getType()->isDependentType()) {
15349     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
15350                             diag::err_second_parameter_to_va_arg_incomplete,
15351                             TInfo->getTypeLoc()))
15352       return ExprError();
15353 
15354     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
15355                                TInfo->getType(),
15356                                diag::err_second_parameter_to_va_arg_abstract,
15357                                TInfo->getTypeLoc()))
15358       return ExprError();
15359 
15360     if (!TInfo->getType().isPODType(Context)) {
15361       Diag(TInfo->getTypeLoc().getBeginLoc(),
15362            TInfo->getType()->isObjCLifetimeType()
15363              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
15364              : diag::warn_second_parameter_to_va_arg_not_pod)
15365         << TInfo->getType()
15366         << TInfo->getTypeLoc().getSourceRange();
15367     }
15368 
15369     // Check for va_arg where arguments of the given type will be promoted
15370     // (i.e. this va_arg is guaranteed to have undefined behavior).
15371     QualType PromoteType;
15372     if (TInfo->getType()->isPromotableIntegerType()) {
15373       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
15374       if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
15375         PromoteType = QualType();
15376     }
15377     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
15378       PromoteType = Context.DoubleTy;
15379     if (!PromoteType.isNull())
15380       DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
15381                   PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
15382                           << TInfo->getType()
15383                           << PromoteType
15384                           << TInfo->getTypeLoc().getSourceRange());
15385   }
15386 
15387   QualType T = TInfo->getType().getNonLValueExprType(Context);
15388   return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
15389 }
15390 
15391 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
15392   // The type of __null will be int or long, depending on the size of
15393   // pointers on the target.
15394   QualType Ty;
15395   unsigned pw = Context.getTargetInfo().getPointerWidth(0);
15396   if (pw == Context.getTargetInfo().getIntWidth())
15397     Ty = Context.IntTy;
15398   else if (pw == Context.getTargetInfo().getLongWidth())
15399     Ty = Context.LongTy;
15400   else if (pw == Context.getTargetInfo().getLongLongWidth())
15401     Ty = Context.LongLongTy;
15402   else {
15403     llvm_unreachable("I don't know size of pointer!");
15404   }
15405 
15406   return new (Context) GNUNullExpr(Ty, TokenLoc);
15407 }
15408 
15409 ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind,
15410                                     SourceLocation BuiltinLoc,
15411                                     SourceLocation RPLoc) {
15412   return BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, CurContext);
15413 }
15414 
15415 ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind,
15416                                     SourceLocation BuiltinLoc,
15417                                     SourceLocation RPLoc,
15418                                     DeclContext *ParentContext) {
15419   return new (Context)
15420       SourceLocExpr(Context, Kind, BuiltinLoc, RPLoc, ParentContext);
15421 }
15422 
15423 bool Sema::CheckConversionToObjCLiteral(QualType DstType, Expr *&Exp,
15424                                         bool Diagnose) {
15425   if (!getLangOpts().ObjC)
15426     return false;
15427 
15428   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
15429   if (!PT)
15430     return false;
15431   const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
15432 
15433   // Ignore any parens, implicit casts (should only be
15434   // array-to-pointer decays), and not-so-opaque values.  The last is
15435   // important for making this trigger for property assignments.
15436   Expr *SrcExpr = Exp->IgnoreParenImpCasts();
15437   if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
15438     if (OV->getSourceExpr())
15439       SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
15440 
15441   if (auto *SL = dyn_cast<StringLiteral>(SrcExpr)) {
15442     if (!PT->isObjCIdType() &&
15443         !(ID && ID->getIdentifier()->isStr("NSString")))
15444       return false;
15445     if (!SL->isAscii())
15446       return false;
15447 
15448     if (Diagnose) {
15449       Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix)
15450           << /*string*/0 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@");
15451       Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get();
15452     }
15453     return true;
15454   }
15455 
15456   if ((isa<IntegerLiteral>(SrcExpr) || isa<CharacterLiteral>(SrcExpr) ||
15457       isa<FloatingLiteral>(SrcExpr) || isa<ObjCBoolLiteralExpr>(SrcExpr) ||
15458       isa<CXXBoolLiteralExpr>(SrcExpr)) &&
15459       !SrcExpr->isNullPointerConstant(
15460           getASTContext(), Expr::NPC_NeverValueDependent)) {
15461     if (!ID || !ID->getIdentifier()->isStr("NSNumber"))
15462       return false;
15463     if (Diagnose) {
15464       Diag(SrcExpr->getBeginLoc(), diag::err_missing_atsign_prefix)
15465           << /*number*/1
15466           << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(), "@");
15467       Expr *NumLit =
15468           BuildObjCNumericLiteral(SrcExpr->getBeginLoc(), SrcExpr).get();
15469       if (NumLit)
15470         Exp = NumLit;
15471     }
15472     return true;
15473   }
15474 
15475   return false;
15476 }
15477 
15478 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
15479                                               const Expr *SrcExpr) {
15480   if (!DstType->isFunctionPointerType() ||
15481       !SrcExpr->getType()->isFunctionType())
15482     return false;
15483 
15484   auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
15485   if (!DRE)
15486     return false;
15487 
15488   auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
15489   if (!FD)
15490     return false;
15491 
15492   return !S.checkAddressOfFunctionIsAvailable(FD,
15493                                               /*Complain=*/true,
15494                                               SrcExpr->getBeginLoc());
15495 }
15496 
15497 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
15498                                     SourceLocation Loc,
15499                                     QualType DstType, QualType SrcType,
15500                                     Expr *SrcExpr, AssignmentAction Action,
15501                                     bool *Complained) {
15502   if (Complained)
15503     *Complained = false;
15504 
15505   // Decode the result (notice that AST's are still created for extensions).
15506   bool CheckInferredResultType = false;
15507   bool isInvalid = false;
15508   unsigned DiagKind = 0;
15509   FixItHint Hint;
15510   ConversionFixItGenerator ConvHints;
15511   bool MayHaveConvFixit = false;
15512   bool MayHaveFunctionDiff = false;
15513   const ObjCInterfaceDecl *IFace = nullptr;
15514   const ObjCProtocolDecl *PDecl = nullptr;
15515 
15516   switch (ConvTy) {
15517   case Compatible:
15518       DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
15519       return false;
15520 
15521   case PointerToInt:
15522     if (getLangOpts().CPlusPlus) {
15523       DiagKind = diag::err_typecheck_convert_pointer_int;
15524       isInvalid = true;
15525     } else {
15526       DiagKind = diag::ext_typecheck_convert_pointer_int;
15527     }
15528     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15529     MayHaveConvFixit = true;
15530     break;
15531   case IntToPointer:
15532     if (getLangOpts().CPlusPlus) {
15533       DiagKind = diag::err_typecheck_convert_int_pointer;
15534       isInvalid = true;
15535     } else {
15536       DiagKind = diag::ext_typecheck_convert_int_pointer;
15537     }
15538     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15539     MayHaveConvFixit = true;
15540     break;
15541   case IncompatibleFunctionPointer:
15542     if (getLangOpts().CPlusPlus) {
15543       DiagKind = diag::err_typecheck_convert_incompatible_function_pointer;
15544       isInvalid = true;
15545     } else {
15546       DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
15547     }
15548     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15549     MayHaveConvFixit = true;
15550     break;
15551   case IncompatiblePointer:
15552     if (Action == AA_Passing_CFAudited) {
15553       DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
15554     } else if (getLangOpts().CPlusPlus) {
15555       DiagKind = diag::err_typecheck_convert_incompatible_pointer;
15556       isInvalid = true;
15557     } else {
15558       DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
15559     }
15560     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
15561       SrcType->isObjCObjectPointerType();
15562     if (Hint.isNull() && !CheckInferredResultType) {
15563       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15564     }
15565     else if (CheckInferredResultType) {
15566       SrcType = SrcType.getUnqualifiedType();
15567       DstType = DstType.getUnqualifiedType();
15568     }
15569     MayHaveConvFixit = true;
15570     break;
15571   case IncompatiblePointerSign:
15572     if (getLangOpts().CPlusPlus) {
15573       DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign;
15574       isInvalid = true;
15575     } else {
15576       DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
15577     }
15578     break;
15579   case FunctionVoidPointer:
15580     if (getLangOpts().CPlusPlus) {
15581       DiagKind = diag::err_typecheck_convert_pointer_void_func;
15582       isInvalid = true;
15583     } else {
15584       DiagKind = diag::ext_typecheck_convert_pointer_void_func;
15585     }
15586     break;
15587   case IncompatiblePointerDiscardsQualifiers: {
15588     // Perform array-to-pointer decay if necessary.
15589     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
15590 
15591     isInvalid = true;
15592 
15593     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
15594     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
15595     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
15596       DiagKind = diag::err_typecheck_incompatible_address_space;
15597       break;
15598 
15599     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
15600       DiagKind = diag::err_typecheck_incompatible_ownership;
15601       break;
15602     }
15603 
15604     llvm_unreachable("unknown error case for discarding qualifiers!");
15605     // fallthrough
15606   }
15607   case CompatiblePointerDiscardsQualifiers:
15608     // If the qualifiers lost were because we were applying the
15609     // (deprecated) C++ conversion from a string literal to a char*
15610     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
15611     // Ideally, this check would be performed in
15612     // checkPointerTypesForAssignment. However, that would require a
15613     // bit of refactoring (so that the second argument is an
15614     // expression, rather than a type), which should be done as part
15615     // of a larger effort to fix checkPointerTypesForAssignment for
15616     // C++ semantics.
15617     if (getLangOpts().CPlusPlus &&
15618         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
15619       return false;
15620     if (getLangOpts().CPlusPlus) {
15621       DiagKind =  diag::err_typecheck_convert_discards_qualifiers;
15622       isInvalid = true;
15623     } else {
15624       DiagKind =  diag::ext_typecheck_convert_discards_qualifiers;
15625     }
15626 
15627     break;
15628   case IncompatibleNestedPointerQualifiers:
15629     if (getLangOpts().CPlusPlus) {
15630       isInvalid = true;
15631       DiagKind = diag::err_nested_pointer_qualifier_mismatch;
15632     } else {
15633       DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
15634     }
15635     break;
15636   case IncompatibleNestedPointerAddressSpaceMismatch:
15637     DiagKind = diag::err_typecheck_incompatible_nested_address_space;
15638     isInvalid = true;
15639     break;
15640   case IntToBlockPointer:
15641     DiagKind = diag::err_int_to_block_pointer;
15642     isInvalid = true;
15643     break;
15644   case IncompatibleBlockPointer:
15645     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
15646     isInvalid = true;
15647     break;
15648   case IncompatibleObjCQualifiedId: {
15649     if (SrcType->isObjCQualifiedIdType()) {
15650       const ObjCObjectPointerType *srcOPT =
15651                 SrcType->castAs<ObjCObjectPointerType>();
15652       for (auto *srcProto : srcOPT->quals()) {
15653         PDecl = srcProto;
15654         break;
15655       }
15656       if (const ObjCInterfaceType *IFaceT =
15657             DstType->castAs<ObjCObjectPointerType>()->getInterfaceType())
15658         IFace = IFaceT->getDecl();
15659     }
15660     else if (DstType->isObjCQualifiedIdType()) {
15661       const ObjCObjectPointerType *dstOPT =
15662         DstType->castAs<ObjCObjectPointerType>();
15663       for (auto *dstProto : dstOPT->quals()) {
15664         PDecl = dstProto;
15665         break;
15666       }
15667       if (const ObjCInterfaceType *IFaceT =
15668             SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType())
15669         IFace = IFaceT->getDecl();
15670     }
15671     if (getLangOpts().CPlusPlus) {
15672       DiagKind = diag::err_incompatible_qualified_id;
15673       isInvalid = true;
15674     } else {
15675       DiagKind = diag::warn_incompatible_qualified_id;
15676     }
15677     break;
15678   }
15679   case IncompatibleVectors:
15680     if (getLangOpts().CPlusPlus) {
15681       DiagKind = diag::err_incompatible_vectors;
15682       isInvalid = true;
15683     } else {
15684       DiagKind = diag::warn_incompatible_vectors;
15685     }
15686     break;
15687   case IncompatibleObjCWeakRef:
15688     DiagKind = diag::err_arc_weak_unavailable_assign;
15689     isInvalid = true;
15690     break;
15691   case Incompatible:
15692     if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
15693       if (Complained)
15694         *Complained = true;
15695       return true;
15696     }
15697 
15698     DiagKind = diag::err_typecheck_convert_incompatible;
15699     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15700     MayHaveConvFixit = true;
15701     isInvalid = true;
15702     MayHaveFunctionDiff = true;
15703     break;
15704   }
15705 
15706   QualType FirstType, SecondType;
15707   switch (Action) {
15708   case AA_Assigning:
15709   case AA_Initializing:
15710     // The destination type comes first.
15711     FirstType = DstType;
15712     SecondType = SrcType;
15713     break;
15714 
15715   case AA_Returning:
15716   case AA_Passing:
15717   case AA_Passing_CFAudited:
15718   case AA_Converting:
15719   case AA_Sending:
15720   case AA_Casting:
15721     // The source type comes first.
15722     FirstType = SrcType;
15723     SecondType = DstType;
15724     break;
15725   }
15726 
15727   PartialDiagnostic FDiag = PDiag(DiagKind);
15728   if (Action == AA_Passing_CFAudited)
15729     FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
15730   else
15731     FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
15732 
15733   // If we can fix the conversion, suggest the FixIts.
15734   assert(ConvHints.isNull() || Hint.isNull());
15735   if (!ConvHints.isNull()) {
15736     for (FixItHint &H : ConvHints.Hints)
15737       FDiag << H;
15738   } else {
15739     FDiag << Hint;
15740   }
15741   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
15742 
15743   if (MayHaveFunctionDiff)
15744     HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
15745 
15746   Diag(Loc, FDiag);
15747   if ((DiagKind == diag::warn_incompatible_qualified_id ||
15748        DiagKind == diag::err_incompatible_qualified_id) &&
15749       PDecl && IFace && !IFace->hasDefinition())
15750     Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
15751         << IFace << PDecl;
15752 
15753   if (SecondType == Context.OverloadTy)
15754     NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
15755                               FirstType, /*TakingAddress=*/true);
15756 
15757   if (CheckInferredResultType)
15758     EmitRelatedResultTypeNote(SrcExpr);
15759 
15760   if (Action == AA_Returning && ConvTy == IncompatiblePointer)
15761     EmitRelatedResultTypeNoteForReturn(DstType);
15762 
15763   if (Complained)
15764     *Complained = true;
15765   return isInvalid;
15766 }
15767 
15768 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
15769                                                  llvm::APSInt *Result) {
15770   class SimpleICEDiagnoser : public VerifyICEDiagnoser {
15771   public:
15772     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
15773       S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
15774     }
15775   } Diagnoser;
15776 
15777   return VerifyIntegerConstantExpression(E, Result, Diagnoser);
15778 }
15779 
15780 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
15781                                                  llvm::APSInt *Result,
15782                                                  unsigned DiagID,
15783                                                  bool AllowFold) {
15784   class IDDiagnoser : public VerifyICEDiagnoser {
15785     unsigned DiagID;
15786 
15787   public:
15788     IDDiagnoser(unsigned DiagID)
15789       : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
15790 
15791     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
15792       S.Diag(Loc, DiagID) << SR;
15793     }
15794   } Diagnoser(DiagID);
15795 
15796   return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
15797 }
15798 
15799 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
15800                                             SourceRange SR) {
15801   S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
15802 }
15803 
15804 ExprResult
15805 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
15806                                       VerifyICEDiagnoser &Diagnoser,
15807                                       bool AllowFold) {
15808   SourceLocation DiagLoc = E->getBeginLoc();
15809 
15810   if (getLangOpts().CPlusPlus11) {
15811     // C++11 [expr.const]p5:
15812     //   If an expression of literal class type is used in a context where an
15813     //   integral constant expression is required, then that class type shall
15814     //   have a single non-explicit conversion function to an integral or
15815     //   unscoped enumeration type
15816     ExprResult Converted;
15817     class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
15818     public:
15819       CXX11ConvertDiagnoser(bool Silent)
15820           : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
15821                                 Silent, true) {}
15822 
15823       SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
15824                                            QualType T) override {
15825         return S.Diag(Loc, diag::err_ice_not_integral) << T;
15826       }
15827 
15828       SemaDiagnosticBuilder diagnoseIncomplete(
15829           Sema &S, SourceLocation Loc, QualType T) override {
15830         return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
15831       }
15832 
15833       SemaDiagnosticBuilder diagnoseExplicitConv(
15834           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
15835         return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
15836       }
15837 
15838       SemaDiagnosticBuilder noteExplicitConv(
15839           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
15840         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
15841                  << ConvTy->isEnumeralType() << ConvTy;
15842       }
15843 
15844       SemaDiagnosticBuilder diagnoseAmbiguous(
15845           Sema &S, SourceLocation Loc, QualType T) override {
15846         return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
15847       }
15848 
15849       SemaDiagnosticBuilder noteAmbiguous(
15850           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
15851         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
15852                  << ConvTy->isEnumeralType() << ConvTy;
15853       }
15854 
15855       SemaDiagnosticBuilder diagnoseConversion(
15856           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
15857         llvm_unreachable("conversion functions are permitted");
15858       }
15859     } ConvertDiagnoser(Diagnoser.Suppress);
15860 
15861     Converted = PerformContextualImplicitConversion(DiagLoc, E,
15862                                                     ConvertDiagnoser);
15863     if (Converted.isInvalid())
15864       return Converted;
15865     E = Converted.get();
15866     if (!E->getType()->isIntegralOrUnscopedEnumerationType())
15867       return ExprError();
15868   } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
15869     // An ICE must be of integral or unscoped enumeration type.
15870     if (!Diagnoser.Suppress)
15871       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
15872     return ExprError();
15873   }
15874 
15875   ExprResult RValueExpr = DefaultLvalueConversion(E);
15876   if (RValueExpr.isInvalid())
15877     return ExprError();
15878 
15879   E = RValueExpr.get();
15880 
15881   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
15882   // in the non-ICE case.
15883   if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
15884     if (Result)
15885       *Result = E->EvaluateKnownConstIntCheckOverflow(Context);
15886     if (!isa<ConstantExpr>(E))
15887       E = ConstantExpr::Create(Context, E);
15888     return E;
15889   }
15890 
15891   Expr::EvalResult EvalResult;
15892   SmallVector<PartialDiagnosticAt, 8> Notes;
15893   EvalResult.Diag = &Notes;
15894 
15895   // Try to evaluate the expression, and produce diagnostics explaining why it's
15896   // not a constant expression as a side-effect.
15897   bool Folded =
15898       E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) &&
15899       EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
15900 
15901   if (!isa<ConstantExpr>(E))
15902     E = ConstantExpr::Create(Context, E, EvalResult.Val);
15903 
15904   // In C++11, we can rely on diagnostics being produced for any expression
15905   // which is not a constant expression. If no diagnostics were produced, then
15906   // this is a constant expression.
15907   if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
15908     if (Result)
15909       *Result = EvalResult.Val.getInt();
15910     return E;
15911   }
15912 
15913   // If our only note is the usual "invalid subexpression" note, just point
15914   // the caret at its location rather than producing an essentially
15915   // redundant note.
15916   if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
15917         diag::note_invalid_subexpr_in_const_expr) {
15918     DiagLoc = Notes[0].first;
15919     Notes.clear();
15920   }
15921 
15922   if (!Folded || !AllowFold) {
15923     if (!Diagnoser.Suppress) {
15924       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
15925       for (const PartialDiagnosticAt &Note : Notes)
15926         Diag(Note.first, Note.second);
15927     }
15928 
15929     return ExprError();
15930   }
15931 
15932   Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
15933   for (const PartialDiagnosticAt &Note : Notes)
15934     Diag(Note.first, Note.second);
15935 
15936   if (Result)
15937     *Result = EvalResult.Val.getInt();
15938   return E;
15939 }
15940 
15941 namespace {
15942   // Handle the case where we conclude a expression which we speculatively
15943   // considered to be unevaluated is actually evaluated.
15944   class TransformToPE : public TreeTransform<TransformToPE> {
15945     typedef TreeTransform<TransformToPE> BaseTransform;
15946 
15947   public:
15948     TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
15949 
15950     // Make sure we redo semantic analysis
15951     bool AlwaysRebuild() { return true; }
15952     bool ReplacingOriginal() { return true; }
15953 
15954     // We need to special-case DeclRefExprs referring to FieldDecls which
15955     // are not part of a member pointer formation; normal TreeTransforming
15956     // doesn't catch this case because of the way we represent them in the AST.
15957     // FIXME: This is a bit ugly; is it really the best way to handle this
15958     // case?
15959     //
15960     // Error on DeclRefExprs referring to FieldDecls.
15961     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
15962       if (isa<FieldDecl>(E->getDecl()) &&
15963           !SemaRef.isUnevaluatedContext())
15964         return SemaRef.Diag(E->getLocation(),
15965                             diag::err_invalid_non_static_member_use)
15966             << E->getDecl() << E->getSourceRange();
15967 
15968       return BaseTransform::TransformDeclRefExpr(E);
15969     }
15970 
15971     // Exception: filter out member pointer formation
15972     ExprResult TransformUnaryOperator(UnaryOperator *E) {
15973       if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
15974         return E;
15975 
15976       return BaseTransform::TransformUnaryOperator(E);
15977     }
15978 
15979     // The body of a lambda-expression is in a separate expression evaluation
15980     // context so never needs to be transformed.
15981     // FIXME: Ideally we wouldn't transform the closure type either, and would
15982     // just recreate the capture expressions and lambda expression.
15983     StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
15984       return SkipLambdaBody(E, Body);
15985     }
15986   };
15987 }
15988 
15989 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
15990   assert(isUnevaluatedContext() &&
15991          "Should only transform unevaluated expressions");
15992   ExprEvalContexts.back().Context =
15993       ExprEvalContexts[ExprEvalContexts.size()-2].Context;
15994   if (isUnevaluatedContext())
15995     return E;
15996   return TransformToPE(*this).TransformExpr(E);
15997 }
15998 
15999 void
16000 Sema::PushExpressionEvaluationContext(
16001     ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
16002     ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
16003   ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
16004                                 LambdaContextDecl, ExprContext);
16005   Cleanup.reset();
16006   if (!MaybeODRUseExprs.empty())
16007     std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
16008 }
16009 
16010 void
16011 Sema::PushExpressionEvaluationContext(
16012     ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
16013     ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
16014   Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
16015   PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);
16016 }
16017 
16018 namespace {
16019 
16020 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
16021   PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
16022   if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) {
16023     if (E->getOpcode() == UO_Deref)
16024       return CheckPossibleDeref(S, E->getSubExpr());
16025   } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) {
16026     return CheckPossibleDeref(S, E->getBase());
16027   } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) {
16028     return CheckPossibleDeref(S, E->getBase());
16029   } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) {
16030     QualType Inner;
16031     QualType Ty = E->getType();
16032     if (const auto *Ptr = Ty->getAs<PointerType>())
16033       Inner = Ptr->getPointeeType();
16034     else if (const auto *Arr = S.Context.getAsArrayType(Ty))
16035       Inner = Arr->getElementType();
16036     else
16037       return nullptr;
16038 
16039     if (Inner->hasAttr(attr::NoDeref))
16040       return E;
16041   }
16042   return nullptr;
16043 }
16044 
16045 } // namespace
16046 
16047 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) {
16048   for (const Expr *E : Rec.PossibleDerefs) {
16049     const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E);
16050     if (DeclRef) {
16051       const ValueDecl *Decl = DeclRef->getDecl();
16052       Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type)
16053           << Decl->getName() << E->getSourceRange();
16054       Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName();
16055     } else {
16056       Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl)
16057           << E->getSourceRange();
16058     }
16059   }
16060   Rec.PossibleDerefs.clear();
16061 }
16062 
16063 /// Check whether E, which is either a discarded-value expression or an
16064 /// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue,
16065 /// and if so, remove it from the list of volatile-qualified assignments that
16066 /// we are going to warn are deprecated.
16067 void Sema::CheckUnusedVolatileAssignment(Expr *E) {
16068   if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20)
16069     return;
16070 
16071   // Note: ignoring parens here is not justified by the standard rules, but
16072   // ignoring parentheses seems like a more reasonable approach, and this only
16073   // drives a deprecation warning so doesn't affect conformance.
16074   if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) {
16075     if (BO->getOpcode() == BO_Assign) {
16076       auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs;
16077       LHSs.erase(std::remove(LHSs.begin(), LHSs.end(), BO->getLHS()),
16078                  LHSs.end());
16079     }
16080   }
16081 }
16082 
16083 ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) {
16084   if (!E.isUsable() || !Decl || !Decl->isConsteval() || isConstantEvaluated() ||
16085       RebuildingImmediateInvocation)
16086     return E;
16087 
16088   /// Opportunistically remove the callee from ReferencesToConsteval if we can.
16089   /// It's OK if this fails; we'll also remove this in
16090   /// HandleImmediateInvocations, but catching it here allows us to avoid
16091   /// walking the AST looking for it in simple cases.
16092   if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit()))
16093     if (auto *DeclRef =
16094             dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()))
16095       ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef);
16096 
16097   E = MaybeCreateExprWithCleanups(E);
16098 
16099   ConstantExpr *Res = ConstantExpr::Create(
16100       getASTContext(), E.get(),
16101       ConstantExpr::getStorageKind(E.get()->getType().getTypePtr(),
16102                                    getASTContext()),
16103       /*IsImmediateInvocation*/ true);
16104   ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0);
16105   return Res;
16106 }
16107 
16108 static void EvaluateAndDiagnoseImmediateInvocation(
16109     Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) {
16110   llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
16111   Expr::EvalResult Eval;
16112   Eval.Diag = &Notes;
16113   ConstantExpr *CE = Candidate.getPointer();
16114   bool Result = CE->EvaluateAsConstantExpr(Eval, Expr::EvaluateForCodeGen,
16115                                            SemaRef.getASTContext(), true);
16116   if (!Result || !Notes.empty()) {
16117     Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit();
16118     if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr))
16119       InnerExpr = FunctionalCast->getSubExpr();
16120     FunctionDecl *FD = nullptr;
16121     if (auto *Call = dyn_cast<CallExpr>(InnerExpr))
16122       FD = cast<FunctionDecl>(Call->getCalleeDecl());
16123     else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr))
16124       FD = Call->getConstructor();
16125     else
16126       llvm_unreachable("unhandled decl kind");
16127     assert(FD->isConsteval());
16128     SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call) << FD;
16129     for (auto &Note : Notes)
16130       SemaRef.Diag(Note.first, Note.second);
16131     return;
16132   }
16133   CE->MoveIntoResult(Eval.Val, SemaRef.getASTContext());
16134 }
16135 
16136 static void RemoveNestedImmediateInvocation(
16137     Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec,
16138     SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) {
16139   struct ComplexRemove : TreeTransform<ComplexRemove> {
16140     using Base = TreeTransform<ComplexRemove>;
16141     llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
16142     SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet;
16143     SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator
16144         CurrentII;
16145     ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR,
16146                   SmallVector<Sema::ImmediateInvocationCandidate, 4> &II,
16147                   SmallVector<Sema::ImmediateInvocationCandidate,
16148                               4>::reverse_iterator Current)
16149         : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {}
16150     void RemoveImmediateInvocation(ConstantExpr* E) {
16151       auto It = std::find_if(CurrentII, IISet.rend(),
16152                              [E](Sema::ImmediateInvocationCandidate Elem) {
16153                                return Elem.getPointer() == E;
16154                              });
16155       assert(It != IISet.rend() &&
16156              "ConstantExpr marked IsImmediateInvocation should "
16157              "be present");
16158       It->setInt(1); // Mark as deleted
16159     }
16160     ExprResult TransformConstantExpr(ConstantExpr *E) {
16161       if (!E->isImmediateInvocation())
16162         return Base::TransformConstantExpr(E);
16163       RemoveImmediateInvocation(E);
16164       return Base::TransformExpr(E->getSubExpr());
16165     }
16166     /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so
16167     /// we need to remove its DeclRefExpr from the DRSet.
16168     ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
16169       DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit()));
16170       return Base::TransformCXXOperatorCallExpr(E);
16171     }
16172     /// Base::TransformInitializer skip ConstantExpr so we need to visit them
16173     /// here.
16174     ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) {
16175       if (!Init)
16176         return Init;
16177       /// ConstantExpr are the first layer of implicit node to be removed so if
16178       /// Init isn't a ConstantExpr, no ConstantExpr will be skipped.
16179       if (auto *CE = dyn_cast<ConstantExpr>(Init))
16180         if (CE->isImmediateInvocation())
16181           RemoveImmediateInvocation(CE);
16182       return Base::TransformInitializer(Init, NotCopyInit);
16183     }
16184     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
16185       DRSet.erase(E);
16186       return E;
16187     }
16188     bool AlwaysRebuild() { return false; }
16189     bool ReplacingOriginal() { return true; }
16190     bool AllowSkippingCXXConstructExpr() {
16191       bool Res = AllowSkippingFirstCXXConstructExpr;
16192       AllowSkippingFirstCXXConstructExpr = true;
16193       return Res;
16194     }
16195     bool AllowSkippingFirstCXXConstructExpr = true;
16196   } Transformer(SemaRef, Rec.ReferenceToConsteval,
16197                 Rec.ImmediateInvocationCandidates, It);
16198 
16199   /// CXXConstructExpr with a single argument are getting skipped by
16200   /// TreeTransform in some situtation because they could be implicit. This
16201   /// can only occur for the top-level CXXConstructExpr because it is used
16202   /// nowhere in the expression being transformed therefore will not be rebuilt.
16203   /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from
16204   /// skipping the first CXXConstructExpr.
16205   if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit()))
16206     Transformer.AllowSkippingFirstCXXConstructExpr = false;
16207 
16208   ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr());
16209   assert(Res.isUsable());
16210   Res = SemaRef.MaybeCreateExprWithCleanups(Res);
16211   It->getPointer()->setSubExpr(Res.get());
16212 }
16213 
16214 static void
16215 HandleImmediateInvocations(Sema &SemaRef,
16216                            Sema::ExpressionEvaluationContextRecord &Rec) {
16217   if ((Rec.ImmediateInvocationCandidates.size() == 0 &&
16218        Rec.ReferenceToConsteval.size() == 0) ||
16219       SemaRef.RebuildingImmediateInvocation)
16220     return;
16221 
16222   /// When we have more then 1 ImmediateInvocationCandidates we need to check
16223   /// for nested ImmediateInvocationCandidates. when we have only 1 we only
16224   /// need to remove ReferenceToConsteval in the immediate invocation.
16225   if (Rec.ImmediateInvocationCandidates.size() > 1) {
16226 
16227     /// Prevent sema calls during the tree transform from adding pointers that
16228     /// are already in the sets.
16229     llvm::SaveAndRestore<bool> DisableIITracking(
16230         SemaRef.RebuildingImmediateInvocation, true);
16231 
16232     /// Prevent diagnostic during tree transfrom as they are duplicates
16233     Sema::TentativeAnalysisScope DisableDiag(SemaRef);
16234 
16235     for (auto It = Rec.ImmediateInvocationCandidates.rbegin();
16236          It != Rec.ImmediateInvocationCandidates.rend(); It++)
16237       if (!It->getInt())
16238         RemoveNestedImmediateInvocation(SemaRef, Rec, It);
16239   } else if (Rec.ImmediateInvocationCandidates.size() == 1 &&
16240              Rec.ReferenceToConsteval.size()) {
16241     struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> {
16242       llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
16243       SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {}
16244       bool VisitDeclRefExpr(DeclRefExpr *E) {
16245         DRSet.erase(E);
16246         return DRSet.size();
16247       }
16248     } Visitor(Rec.ReferenceToConsteval);
16249     Visitor.TraverseStmt(
16250         Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr());
16251   }
16252   for (auto CE : Rec.ImmediateInvocationCandidates)
16253     if (!CE.getInt())
16254       EvaluateAndDiagnoseImmediateInvocation(SemaRef, CE);
16255   for (auto DR : Rec.ReferenceToConsteval) {
16256     auto *FD = cast<FunctionDecl>(DR->getDecl());
16257     SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address)
16258         << FD;
16259     SemaRef.Diag(FD->getLocation(), diag::note_declared_at);
16260   }
16261 }
16262 
16263 void Sema::PopExpressionEvaluationContext() {
16264   ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
16265   unsigned NumTypos = Rec.NumTypos;
16266 
16267   if (!Rec.Lambdas.empty()) {
16268     using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind;
16269     if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || Rec.isUnevaluated() ||
16270         (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17)) {
16271       unsigned D;
16272       if (Rec.isUnevaluated()) {
16273         // C++11 [expr.prim.lambda]p2:
16274         //   A lambda-expression shall not appear in an unevaluated operand
16275         //   (Clause 5).
16276         D = diag::err_lambda_unevaluated_operand;
16277       } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
16278         // C++1y [expr.const]p2:
16279         //   A conditional-expression e is a core constant expression unless the
16280         //   evaluation of e, following the rules of the abstract machine, would
16281         //   evaluate [...] a lambda-expression.
16282         D = diag::err_lambda_in_constant_expression;
16283       } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
16284         // C++17 [expr.prim.lamda]p2:
16285         // A lambda-expression shall not appear [...] in a template-argument.
16286         D = diag::err_lambda_in_invalid_context;
16287       } else
16288         llvm_unreachable("Couldn't infer lambda error message.");
16289 
16290       for (const auto *L : Rec.Lambdas)
16291         Diag(L->getBeginLoc(), D);
16292     }
16293   }
16294 
16295   WarnOnPendingNoDerefs(Rec);
16296   HandleImmediateInvocations(*this, Rec);
16297 
16298   // Warn on any volatile-qualified simple-assignments that are not discarded-
16299   // value expressions nor unevaluated operands (those cases get removed from
16300   // this list by CheckUnusedVolatileAssignment).
16301   for (auto *BO : Rec.VolatileAssignmentLHSs)
16302     Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile)
16303         << BO->getType();
16304 
16305   // When are coming out of an unevaluated context, clear out any
16306   // temporaries that we may have created as part of the evaluation of
16307   // the expression in that context: they aren't relevant because they
16308   // will never be constructed.
16309   if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
16310     ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
16311                              ExprCleanupObjects.end());
16312     Cleanup = Rec.ParentCleanup;
16313     CleanupVarDeclMarking();
16314     std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
16315   // Otherwise, merge the contexts together.
16316   } else {
16317     Cleanup.mergeFrom(Rec.ParentCleanup);
16318     MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
16319                             Rec.SavedMaybeODRUseExprs.end());
16320   }
16321 
16322   // Pop the current expression evaluation context off the stack.
16323   ExprEvalContexts.pop_back();
16324 
16325   // The global expression evaluation context record is never popped.
16326   ExprEvalContexts.back().NumTypos += NumTypos;
16327 }
16328 
16329 void Sema::DiscardCleanupsInEvaluationContext() {
16330   ExprCleanupObjects.erase(
16331          ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
16332          ExprCleanupObjects.end());
16333   Cleanup.reset();
16334   MaybeODRUseExprs.clear();
16335 }
16336 
16337 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
16338   ExprResult Result = CheckPlaceholderExpr(E);
16339   if (Result.isInvalid())
16340     return ExprError();
16341   E = Result.get();
16342   if (!E->getType()->isVariablyModifiedType())
16343     return E;
16344   return TransformToPotentiallyEvaluated(E);
16345 }
16346 
16347 /// Are we in a context that is potentially constant evaluated per C++20
16348 /// [expr.const]p12?
16349 static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) {
16350   /// C++2a [expr.const]p12:
16351   //   An expression or conversion is potentially constant evaluated if it is
16352   switch (SemaRef.ExprEvalContexts.back().Context) {
16353     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
16354       // -- a manifestly constant-evaluated expression,
16355     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
16356     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
16357     case Sema::ExpressionEvaluationContext::DiscardedStatement:
16358       // -- a potentially-evaluated expression,
16359     case Sema::ExpressionEvaluationContext::UnevaluatedList:
16360       // -- an immediate subexpression of a braced-init-list,
16361 
16362       // -- [FIXME] an expression of the form & cast-expression that occurs
16363       //    within a templated entity
16364       // -- a subexpression of one of the above that is not a subexpression of
16365       // a nested unevaluated operand.
16366       return true;
16367 
16368     case Sema::ExpressionEvaluationContext::Unevaluated:
16369     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
16370       // Expressions in this context are never evaluated.
16371       return false;
16372   }
16373   llvm_unreachable("Invalid context");
16374 }
16375 
16376 /// Return true if this function has a calling convention that requires mangling
16377 /// in the size of the parameter pack.
16378 static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) {
16379   // These manglings don't do anything on non-Windows or non-x86 platforms, so
16380   // we don't need parameter type sizes.
16381   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
16382   if (!TT.isOSWindows() || !TT.isX86())
16383     return false;
16384 
16385   // If this is C++ and this isn't an extern "C" function, parameters do not
16386   // need to be complete. In this case, C++ mangling will apply, which doesn't
16387   // use the size of the parameters.
16388   if (S.getLangOpts().CPlusPlus && !FD->isExternC())
16389     return false;
16390 
16391   // Stdcall, fastcall, and vectorcall need this special treatment.
16392   CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
16393   switch (CC) {
16394   case CC_X86StdCall:
16395   case CC_X86FastCall:
16396   case CC_X86VectorCall:
16397     return true;
16398   default:
16399     break;
16400   }
16401   return false;
16402 }
16403 
16404 /// Require that all of the parameter types of function be complete. Normally,
16405 /// parameter types are only required to be complete when a function is called
16406 /// or defined, but to mangle functions with certain calling conventions, the
16407 /// mangler needs to know the size of the parameter list. In this situation,
16408 /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles
16409 /// the function as _foo@0, i.e. zero bytes of parameters, which will usually
16410 /// result in a linker error. Clang doesn't implement this behavior, and instead
16411 /// attempts to error at compile time.
16412 static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD,
16413                                                   SourceLocation Loc) {
16414   class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser {
16415     FunctionDecl *FD;
16416     ParmVarDecl *Param;
16417 
16418   public:
16419     ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param)
16420         : FD(FD), Param(Param) {}
16421 
16422     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
16423       CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
16424       StringRef CCName;
16425       switch (CC) {
16426       case CC_X86StdCall:
16427         CCName = "stdcall";
16428         break;
16429       case CC_X86FastCall:
16430         CCName = "fastcall";
16431         break;
16432       case CC_X86VectorCall:
16433         CCName = "vectorcall";
16434         break;
16435       default:
16436         llvm_unreachable("CC does not need mangling");
16437       }
16438 
16439       S.Diag(Loc, diag::err_cconv_incomplete_param_type)
16440           << Param->getDeclName() << FD->getDeclName() << CCName;
16441     }
16442   };
16443 
16444   for (ParmVarDecl *Param : FD->parameters()) {
16445     ParamIncompleteTypeDiagnoser Diagnoser(FD, Param);
16446     S.RequireCompleteType(Loc, Param->getType(), Diagnoser);
16447   }
16448 }
16449 
16450 namespace {
16451 enum class OdrUseContext {
16452   /// Declarations in this context are not odr-used.
16453   None,
16454   /// Declarations in this context are formally odr-used, but this is a
16455   /// dependent context.
16456   Dependent,
16457   /// Declarations in this context are odr-used but not actually used (yet).
16458   FormallyOdrUsed,
16459   /// Declarations in this context are used.
16460   Used
16461 };
16462 }
16463 
16464 /// Are we within a context in which references to resolved functions or to
16465 /// variables result in odr-use?
16466 static OdrUseContext isOdrUseContext(Sema &SemaRef) {
16467   OdrUseContext Result;
16468 
16469   switch (SemaRef.ExprEvalContexts.back().Context) {
16470     case Sema::ExpressionEvaluationContext::Unevaluated:
16471     case Sema::ExpressionEvaluationContext::UnevaluatedList:
16472     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
16473       return OdrUseContext::None;
16474 
16475     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
16476     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
16477       Result = OdrUseContext::Used;
16478       break;
16479 
16480     case Sema::ExpressionEvaluationContext::DiscardedStatement:
16481       Result = OdrUseContext::FormallyOdrUsed;
16482       break;
16483 
16484     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
16485       // A default argument formally results in odr-use, but doesn't actually
16486       // result in a use in any real sense until it itself is used.
16487       Result = OdrUseContext::FormallyOdrUsed;
16488       break;
16489   }
16490 
16491   if (SemaRef.CurContext->isDependentContext())
16492     return OdrUseContext::Dependent;
16493 
16494   return Result;
16495 }
16496 
16497 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
16498   return Func->isConstexpr() &&
16499          (Func->isImplicitlyInstantiable() || !Func->isUserProvided());
16500 }
16501 
16502 /// Mark a function referenced, and check whether it is odr-used
16503 /// (C++ [basic.def.odr]p2, C99 6.9p3)
16504 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
16505                                   bool MightBeOdrUse) {
16506   assert(Func && "No function?");
16507 
16508   Func->setReferenced();
16509 
16510   // Recursive functions aren't really used until they're used from some other
16511   // context.
16512   bool IsRecursiveCall = CurContext == Func;
16513 
16514   // C++11 [basic.def.odr]p3:
16515   //   A function whose name appears as a potentially-evaluated expression is
16516   //   odr-used if it is the unique lookup result or the selected member of a
16517   //   set of overloaded functions [...].
16518   //
16519   // We (incorrectly) mark overload resolution as an unevaluated context, so we
16520   // can just check that here.
16521   OdrUseContext OdrUse =
16522       MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None;
16523   if (IsRecursiveCall && OdrUse == OdrUseContext::Used)
16524     OdrUse = OdrUseContext::FormallyOdrUsed;
16525 
16526   // Trivial default constructors and destructors are never actually used.
16527   // FIXME: What about other special members?
16528   if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() &&
16529       OdrUse == OdrUseContext::Used) {
16530     if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func))
16531       if (Constructor->isDefaultConstructor())
16532         OdrUse = OdrUseContext::FormallyOdrUsed;
16533     if (isa<CXXDestructorDecl>(Func))
16534       OdrUse = OdrUseContext::FormallyOdrUsed;
16535   }
16536 
16537   // C++20 [expr.const]p12:
16538   //   A function [...] is needed for constant evaluation if it is [...] a
16539   //   constexpr function that is named by an expression that is potentially
16540   //   constant evaluated
16541   bool NeededForConstantEvaluation =
16542       isPotentiallyConstantEvaluatedContext(*this) &&
16543       isImplicitlyDefinableConstexprFunction(Func);
16544 
16545   // Determine whether we require a function definition to exist, per
16546   // C++11 [temp.inst]p3:
16547   //   Unless a function template specialization has been explicitly
16548   //   instantiated or explicitly specialized, the function template
16549   //   specialization is implicitly instantiated when the specialization is
16550   //   referenced in a context that requires a function definition to exist.
16551   // C++20 [temp.inst]p7:
16552   //   The existence of a definition of a [...] function is considered to
16553   //   affect the semantics of the program if the [...] function is needed for
16554   //   constant evaluation by an expression
16555   // C++20 [basic.def.odr]p10:
16556   //   Every program shall contain exactly one definition of every non-inline
16557   //   function or variable that is odr-used in that program outside of a
16558   //   discarded statement
16559   // C++20 [special]p1:
16560   //   The implementation will implicitly define [defaulted special members]
16561   //   if they are odr-used or needed for constant evaluation.
16562   //
16563   // Note that we skip the implicit instantiation of templates that are only
16564   // used in unused default arguments or by recursive calls to themselves.
16565   // This is formally non-conforming, but seems reasonable in practice.
16566   bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used ||
16567                                              NeededForConstantEvaluation);
16568 
16569   // C++14 [temp.expl.spec]p6:
16570   //   If a template [...] is explicitly specialized then that specialization
16571   //   shall be declared before the first use of that specialization that would
16572   //   cause an implicit instantiation to take place, in every translation unit
16573   //   in which such a use occurs
16574   if (NeedDefinition &&
16575       (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
16576        Func->getMemberSpecializationInfo()))
16577     checkSpecializationVisibility(Loc, Func);
16578 
16579   if (getLangOpts().CUDA)
16580     CheckCUDACall(Loc, Func);
16581 
16582   if (getLangOpts().SYCLIsDevice)
16583     checkSYCLDeviceFunction(Loc, Func);
16584 
16585   // If we need a definition, try to create one.
16586   if (NeedDefinition && !Func->getBody()) {
16587     runWithSufficientStackSpace(Loc, [&] {
16588       if (CXXConstructorDecl *Constructor =
16589               dyn_cast<CXXConstructorDecl>(Func)) {
16590         Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
16591         if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
16592           if (Constructor->isDefaultConstructor()) {
16593             if (Constructor->isTrivial() &&
16594                 !Constructor->hasAttr<DLLExportAttr>())
16595               return;
16596             DefineImplicitDefaultConstructor(Loc, Constructor);
16597           } else if (Constructor->isCopyConstructor()) {
16598             DefineImplicitCopyConstructor(Loc, Constructor);
16599           } else if (Constructor->isMoveConstructor()) {
16600             DefineImplicitMoveConstructor(Loc, Constructor);
16601           }
16602         } else if (Constructor->getInheritedConstructor()) {
16603           DefineInheritingConstructor(Loc, Constructor);
16604         }
16605       } else if (CXXDestructorDecl *Destructor =
16606                      dyn_cast<CXXDestructorDecl>(Func)) {
16607         Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
16608         if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
16609           if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
16610             return;
16611           DefineImplicitDestructor(Loc, Destructor);
16612         }
16613         if (Destructor->isVirtual() && getLangOpts().AppleKext)
16614           MarkVTableUsed(Loc, Destructor->getParent());
16615       } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
16616         if (MethodDecl->isOverloadedOperator() &&
16617             MethodDecl->getOverloadedOperator() == OO_Equal) {
16618           MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
16619           if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
16620             if (MethodDecl->isCopyAssignmentOperator())
16621               DefineImplicitCopyAssignment(Loc, MethodDecl);
16622             else if (MethodDecl->isMoveAssignmentOperator())
16623               DefineImplicitMoveAssignment(Loc, MethodDecl);
16624           }
16625         } else if (isa<CXXConversionDecl>(MethodDecl) &&
16626                    MethodDecl->getParent()->isLambda()) {
16627           CXXConversionDecl *Conversion =
16628               cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
16629           if (Conversion->isLambdaToBlockPointerConversion())
16630             DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
16631           else
16632             DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
16633         } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
16634           MarkVTableUsed(Loc, MethodDecl->getParent());
16635       }
16636 
16637       if (Func->isDefaulted() && !Func->isDeleted()) {
16638         DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func);
16639         if (DCK != DefaultedComparisonKind::None)
16640           DefineDefaultedComparison(Loc, Func, DCK);
16641       }
16642 
16643       // Implicit instantiation of function templates and member functions of
16644       // class templates.
16645       if (Func->isImplicitlyInstantiable()) {
16646         TemplateSpecializationKind TSK =
16647             Func->getTemplateSpecializationKindForInstantiation();
16648         SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
16649         bool FirstInstantiation = PointOfInstantiation.isInvalid();
16650         if (FirstInstantiation) {
16651           PointOfInstantiation = Loc;
16652           Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
16653         } else if (TSK != TSK_ImplicitInstantiation) {
16654           // Use the point of use as the point of instantiation, instead of the
16655           // point of explicit instantiation (which we track as the actual point
16656           // of instantiation). This gives better backtraces in diagnostics.
16657           PointOfInstantiation = Loc;
16658         }
16659 
16660         if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
16661             Func->isConstexpr()) {
16662           if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
16663               cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
16664               CodeSynthesisContexts.size())
16665             PendingLocalImplicitInstantiations.push_back(
16666                 std::make_pair(Func, PointOfInstantiation));
16667           else if (Func->isConstexpr())
16668             // Do not defer instantiations of constexpr functions, to avoid the
16669             // expression evaluator needing to call back into Sema if it sees a
16670             // call to such a function.
16671             InstantiateFunctionDefinition(PointOfInstantiation, Func);
16672           else {
16673             Func->setInstantiationIsPending(true);
16674             PendingInstantiations.push_back(
16675                 std::make_pair(Func, PointOfInstantiation));
16676             // Notify the consumer that a function was implicitly instantiated.
16677             Consumer.HandleCXXImplicitFunctionInstantiation(Func);
16678           }
16679         }
16680       } else {
16681         // Walk redefinitions, as some of them may be instantiable.
16682         for (auto i : Func->redecls()) {
16683           if (!i->isUsed(false) && i->isImplicitlyInstantiable())
16684             MarkFunctionReferenced(Loc, i, MightBeOdrUse);
16685         }
16686       }
16687     });
16688   }
16689 
16690   // C++14 [except.spec]p17:
16691   //   An exception-specification is considered to be needed when:
16692   //   - the function is odr-used or, if it appears in an unevaluated operand,
16693   //     would be odr-used if the expression were potentially-evaluated;
16694   //
16695   // Note, we do this even if MightBeOdrUse is false. That indicates that the
16696   // function is a pure virtual function we're calling, and in that case the
16697   // function was selected by overload resolution and we need to resolve its
16698   // exception specification for a different reason.
16699   const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
16700   if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
16701     ResolveExceptionSpec(Loc, FPT);
16702 
16703   // If this is the first "real" use, act on that.
16704   if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) {
16705     // Keep track of used but undefined functions.
16706     if (!Func->isDefined()) {
16707       if (mightHaveNonExternalLinkage(Func))
16708         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
16709       else if (Func->getMostRecentDecl()->isInlined() &&
16710                !LangOpts.GNUInline &&
16711                !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
16712         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
16713       else if (isExternalWithNoLinkageType(Func))
16714         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
16715     }
16716 
16717     // Some x86 Windows calling conventions mangle the size of the parameter
16718     // pack into the name. Computing the size of the parameters requires the
16719     // parameter types to be complete. Check that now.
16720     if (funcHasParameterSizeMangling(*this, Func))
16721       CheckCompleteParameterTypesForMangler(*this, Func, Loc);
16722 
16723     // In the MS C++ ABI, the compiler emits destructor variants where they are
16724     // used. If the destructor is used here but defined elsewhere, mark the
16725     // virtual base destructors referenced. If those virtual base destructors
16726     // are inline, this will ensure they are defined when emitting the complete
16727     // destructor variant. This checking may be redundant if the destructor is
16728     // provided later in this TU.
16729     if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
16730       if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) {
16731         CXXRecordDecl *Parent = Dtor->getParent();
16732         if (Parent->getNumVBases() > 0 && !Dtor->getBody())
16733           CheckCompleteDestructorVariant(Loc, Dtor);
16734       }
16735     }
16736 
16737     Func->markUsed(Context);
16738   }
16739 }
16740 
16741 /// Directly mark a variable odr-used. Given a choice, prefer to use
16742 /// MarkVariableReferenced since it does additional checks and then
16743 /// calls MarkVarDeclODRUsed.
16744 /// If the variable must be captured:
16745 ///  - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
16746 ///  - else capture it in the DeclContext that maps to the
16747 ///    *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
16748 static void
16749 MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef,
16750                    const unsigned *const FunctionScopeIndexToStopAt = nullptr) {
16751   // Keep track of used but undefined variables.
16752   // FIXME: We shouldn't suppress this warning for static data members.
16753   if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
16754       (!Var->isExternallyVisible() || Var->isInline() ||
16755        SemaRef.isExternalWithNoLinkageType(Var)) &&
16756       !(Var->isStaticDataMember() && Var->hasInit())) {
16757     SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()];
16758     if (old.isInvalid())
16759       old = Loc;
16760   }
16761   QualType CaptureType, DeclRefType;
16762   if (SemaRef.LangOpts.OpenMP)
16763     SemaRef.tryCaptureOpenMPLambdas(Var);
16764   SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit,
16765     /*EllipsisLoc*/ SourceLocation(),
16766     /*BuildAndDiagnose*/ true,
16767     CaptureType, DeclRefType,
16768     FunctionScopeIndexToStopAt);
16769 
16770   Var->markUsed(SemaRef.Context);
16771 }
16772 
16773 void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture,
16774                                              SourceLocation Loc,
16775                                              unsigned CapturingScopeIndex) {
16776   MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex);
16777 }
16778 
16779 static void
16780 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
16781                                    ValueDecl *var, DeclContext *DC) {
16782   DeclContext *VarDC = var->getDeclContext();
16783 
16784   //  If the parameter still belongs to the translation unit, then
16785   //  we're actually just using one parameter in the declaration of
16786   //  the next.
16787   if (isa<ParmVarDecl>(var) &&
16788       isa<TranslationUnitDecl>(VarDC))
16789     return;
16790 
16791   // For C code, don't diagnose about capture if we're not actually in code
16792   // right now; it's impossible to write a non-constant expression outside of
16793   // function context, so we'll get other (more useful) diagnostics later.
16794   //
16795   // For C++, things get a bit more nasty... it would be nice to suppress this
16796   // diagnostic for certain cases like using a local variable in an array bound
16797   // for a member of a local class, but the correct predicate is not obvious.
16798   if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
16799     return;
16800 
16801   unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
16802   unsigned ContextKind = 3; // unknown
16803   if (isa<CXXMethodDecl>(VarDC) &&
16804       cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
16805     ContextKind = 2;
16806   } else if (isa<FunctionDecl>(VarDC)) {
16807     ContextKind = 0;
16808   } else if (isa<BlockDecl>(VarDC)) {
16809     ContextKind = 1;
16810   }
16811 
16812   S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
16813     << var << ValueKind << ContextKind << VarDC;
16814   S.Diag(var->getLocation(), diag::note_entity_declared_at)
16815       << var;
16816 
16817   // FIXME: Add additional diagnostic info about class etc. which prevents
16818   // capture.
16819 }
16820 
16821 
16822 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
16823                                       bool &SubCapturesAreNested,
16824                                       QualType &CaptureType,
16825                                       QualType &DeclRefType) {
16826    // Check whether we've already captured it.
16827   if (CSI->CaptureMap.count(Var)) {
16828     // If we found a capture, any subcaptures are nested.
16829     SubCapturesAreNested = true;
16830 
16831     // Retrieve the capture type for this variable.
16832     CaptureType = CSI->getCapture(Var).getCaptureType();
16833 
16834     // Compute the type of an expression that refers to this variable.
16835     DeclRefType = CaptureType.getNonReferenceType();
16836 
16837     // Similarly to mutable captures in lambda, all the OpenMP captures by copy
16838     // are mutable in the sense that user can change their value - they are
16839     // private instances of the captured declarations.
16840     const Capture &Cap = CSI->getCapture(Var);
16841     if (Cap.isCopyCapture() &&
16842         !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
16843         !(isa<CapturedRegionScopeInfo>(CSI) &&
16844           cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
16845       DeclRefType.addConst();
16846     return true;
16847   }
16848   return false;
16849 }
16850 
16851 // Only block literals, captured statements, and lambda expressions can
16852 // capture; other scopes don't work.
16853 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
16854                                  SourceLocation Loc,
16855                                  const bool Diagnose, Sema &S) {
16856   if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
16857     return getLambdaAwareParentOfDeclContext(DC);
16858   else if (Var->hasLocalStorage()) {
16859     if (Diagnose)
16860        diagnoseUncapturableValueReference(S, Loc, Var, DC);
16861   }
16862   return nullptr;
16863 }
16864 
16865 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
16866 // certain types of variables (unnamed, variably modified types etc.)
16867 // so check for eligibility.
16868 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
16869                                  SourceLocation Loc,
16870                                  const bool Diagnose, Sema &S) {
16871 
16872   bool IsBlock = isa<BlockScopeInfo>(CSI);
16873   bool IsLambda = isa<LambdaScopeInfo>(CSI);
16874 
16875   // Lambdas are not allowed to capture unnamed variables
16876   // (e.g. anonymous unions).
16877   // FIXME: The C++11 rule don't actually state this explicitly, but I'm
16878   // assuming that's the intent.
16879   if (IsLambda && !Var->getDeclName()) {
16880     if (Diagnose) {
16881       S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
16882       S.Diag(Var->getLocation(), diag::note_declared_at);
16883     }
16884     return false;
16885   }
16886 
16887   // Prohibit variably-modified types in blocks; they're difficult to deal with.
16888   if (Var->getType()->isVariablyModifiedType() && IsBlock) {
16889     if (Diagnose) {
16890       S.Diag(Loc, diag::err_ref_vm_type);
16891       S.Diag(Var->getLocation(), diag::note_previous_decl)
16892         << Var->getDeclName();
16893     }
16894     return false;
16895   }
16896   // Prohibit structs with flexible array members too.
16897   // We cannot capture what is in the tail end of the struct.
16898   if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
16899     if (VTTy->getDecl()->hasFlexibleArrayMember()) {
16900       if (Diagnose) {
16901         if (IsBlock)
16902           S.Diag(Loc, diag::err_ref_flexarray_type);
16903         else
16904           S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
16905             << Var->getDeclName();
16906         S.Diag(Var->getLocation(), diag::note_previous_decl)
16907           << Var->getDeclName();
16908       }
16909       return false;
16910     }
16911   }
16912   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
16913   // Lambdas and captured statements are not allowed to capture __block
16914   // variables; they don't support the expected semantics.
16915   if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
16916     if (Diagnose) {
16917       S.Diag(Loc, diag::err_capture_block_variable)
16918         << Var->getDeclName() << !IsLambda;
16919       S.Diag(Var->getLocation(), diag::note_previous_decl)
16920         << Var->getDeclName();
16921     }
16922     return false;
16923   }
16924   // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
16925   if (S.getLangOpts().OpenCL && IsBlock &&
16926       Var->getType()->isBlockPointerType()) {
16927     if (Diagnose)
16928       S.Diag(Loc, diag::err_opencl_block_ref_block);
16929     return false;
16930   }
16931 
16932   return true;
16933 }
16934 
16935 // Returns true if the capture by block was successful.
16936 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
16937                                  SourceLocation Loc,
16938                                  const bool BuildAndDiagnose,
16939                                  QualType &CaptureType,
16940                                  QualType &DeclRefType,
16941                                  const bool Nested,
16942                                  Sema &S, bool Invalid) {
16943   bool ByRef = false;
16944 
16945   // Blocks are not allowed to capture arrays, excepting OpenCL.
16946   // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
16947   // (decayed to pointers).
16948   if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
16949     if (BuildAndDiagnose) {
16950       S.Diag(Loc, diag::err_ref_array_type);
16951       S.Diag(Var->getLocation(), diag::note_previous_decl)
16952       << Var->getDeclName();
16953       Invalid = true;
16954     } else {
16955       return false;
16956     }
16957   }
16958 
16959   // Forbid the block-capture of autoreleasing variables.
16960   if (!Invalid &&
16961       CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
16962     if (BuildAndDiagnose) {
16963       S.Diag(Loc, diag::err_arc_autoreleasing_capture)
16964         << /*block*/ 0;
16965       S.Diag(Var->getLocation(), diag::note_previous_decl)
16966         << Var->getDeclName();
16967       Invalid = true;
16968     } else {
16969       return false;
16970     }
16971   }
16972 
16973   // Warn about implicitly autoreleasing indirect parameters captured by blocks.
16974   if (const auto *PT = CaptureType->getAs<PointerType>()) {
16975     QualType PointeeTy = PT->getPointeeType();
16976 
16977     if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() &&
16978         PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
16979         !S.Context.hasDirectOwnershipQualifier(PointeeTy)) {
16980       if (BuildAndDiagnose) {
16981         SourceLocation VarLoc = Var->getLocation();
16982         S.Diag(Loc, diag::warn_block_capture_autoreleasing);
16983         S.Diag(VarLoc, diag::note_declare_parameter_strong);
16984       }
16985     }
16986   }
16987 
16988   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
16989   if (HasBlocksAttr || CaptureType->isReferenceType() ||
16990       (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) {
16991     // Block capture by reference does not change the capture or
16992     // declaration reference types.
16993     ByRef = true;
16994   } else {
16995     // Block capture by copy introduces 'const'.
16996     CaptureType = CaptureType.getNonReferenceType().withConst();
16997     DeclRefType = CaptureType;
16998   }
16999 
17000   // Actually capture the variable.
17001   if (BuildAndDiagnose)
17002     BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(),
17003                     CaptureType, Invalid);
17004 
17005   return !Invalid;
17006 }
17007 
17008 
17009 /// Capture the given variable in the captured region.
17010 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
17011                                     VarDecl *Var,
17012                                     SourceLocation Loc,
17013                                     const bool BuildAndDiagnose,
17014                                     QualType &CaptureType,
17015                                     QualType &DeclRefType,
17016                                     const bool RefersToCapturedVariable,
17017                                     Sema &S, bool Invalid) {
17018   // By default, capture variables by reference.
17019   bool ByRef = true;
17020   // Using an LValue reference type is consistent with Lambdas (see below).
17021   if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
17022     if (S.isOpenMPCapturedDecl(Var)) {
17023       bool HasConst = DeclRefType.isConstQualified();
17024       DeclRefType = DeclRefType.getUnqualifiedType();
17025       // Don't lose diagnostics about assignments to const.
17026       if (HasConst)
17027         DeclRefType.addConst();
17028     }
17029     // Do not capture firstprivates in tasks.
17030     if (S.isOpenMPPrivateDecl(Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel) !=
17031         OMPC_unknown)
17032       return true;
17033     ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel,
17034                                     RSI->OpenMPCaptureLevel);
17035   }
17036 
17037   if (ByRef)
17038     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
17039   else
17040     CaptureType = DeclRefType;
17041 
17042   // Actually capture the variable.
17043   if (BuildAndDiagnose)
17044     RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable,
17045                     Loc, SourceLocation(), CaptureType, Invalid);
17046 
17047   return !Invalid;
17048 }
17049 
17050 /// Capture the given variable in the lambda.
17051 static bool captureInLambda(LambdaScopeInfo *LSI,
17052                             VarDecl *Var,
17053                             SourceLocation Loc,
17054                             const bool BuildAndDiagnose,
17055                             QualType &CaptureType,
17056                             QualType &DeclRefType,
17057                             const bool RefersToCapturedVariable,
17058                             const Sema::TryCaptureKind Kind,
17059                             SourceLocation EllipsisLoc,
17060                             const bool IsTopScope,
17061                             Sema &S, bool Invalid) {
17062   // Determine whether we are capturing by reference or by value.
17063   bool ByRef = false;
17064   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
17065     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
17066   } else {
17067     ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
17068   }
17069 
17070   // Compute the type of the field that will capture this variable.
17071   if (ByRef) {
17072     // C++11 [expr.prim.lambda]p15:
17073     //   An entity is captured by reference if it is implicitly or
17074     //   explicitly captured but not captured by copy. It is
17075     //   unspecified whether additional unnamed non-static data
17076     //   members are declared in the closure type for entities
17077     //   captured by reference.
17078     //
17079     // FIXME: It is not clear whether we want to build an lvalue reference
17080     // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
17081     // to do the former, while EDG does the latter. Core issue 1249 will
17082     // clarify, but for now we follow GCC because it's a more permissive and
17083     // easily defensible position.
17084     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
17085   } else {
17086     // C++11 [expr.prim.lambda]p14:
17087     //   For each entity captured by copy, an unnamed non-static
17088     //   data member is declared in the closure type. The
17089     //   declaration order of these members is unspecified. The type
17090     //   of such a data member is the type of the corresponding
17091     //   captured entity if the entity is not a reference to an
17092     //   object, or the referenced type otherwise. [Note: If the
17093     //   captured entity is a reference to a function, the
17094     //   corresponding data member is also a reference to a
17095     //   function. - end note ]
17096     if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
17097       if (!RefType->getPointeeType()->isFunctionType())
17098         CaptureType = RefType->getPointeeType();
17099     }
17100 
17101     // Forbid the lambda copy-capture of autoreleasing variables.
17102     if (!Invalid &&
17103         CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
17104       if (BuildAndDiagnose) {
17105         S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
17106         S.Diag(Var->getLocation(), diag::note_previous_decl)
17107           << Var->getDeclName();
17108         Invalid = true;
17109       } else {
17110         return false;
17111       }
17112     }
17113 
17114     // Make sure that by-copy captures are of a complete and non-abstract type.
17115     if (!Invalid && BuildAndDiagnose) {
17116       if (!CaptureType->isDependentType() &&
17117           S.RequireCompleteSizedType(
17118               Loc, CaptureType,
17119               diag::err_capture_of_incomplete_or_sizeless_type,
17120               Var->getDeclName()))
17121         Invalid = true;
17122       else if (S.RequireNonAbstractType(Loc, CaptureType,
17123                                         diag::err_capture_of_abstract_type))
17124         Invalid = true;
17125     }
17126   }
17127 
17128   // Compute the type of a reference to this captured variable.
17129   if (ByRef)
17130     DeclRefType = CaptureType.getNonReferenceType();
17131   else {
17132     // C++ [expr.prim.lambda]p5:
17133     //   The closure type for a lambda-expression has a public inline
17134     //   function call operator [...]. This function call operator is
17135     //   declared const (9.3.1) if and only if the lambda-expression's
17136     //   parameter-declaration-clause is not followed by mutable.
17137     DeclRefType = CaptureType.getNonReferenceType();
17138     if (!LSI->Mutable && !CaptureType->isReferenceType())
17139       DeclRefType.addConst();
17140   }
17141 
17142   // Add the capture.
17143   if (BuildAndDiagnose)
17144     LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable,
17145                     Loc, EllipsisLoc, CaptureType, Invalid);
17146 
17147   return !Invalid;
17148 }
17149 
17150 bool Sema::tryCaptureVariable(
17151     VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
17152     SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
17153     QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
17154   // An init-capture is notionally from the context surrounding its
17155   // declaration, but its parent DC is the lambda class.
17156   DeclContext *VarDC = Var->getDeclContext();
17157   if (Var->isInitCapture())
17158     VarDC = VarDC->getParent();
17159 
17160   DeclContext *DC = CurContext;
17161   const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
17162       ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
17163   // We need to sync up the Declaration Context with the
17164   // FunctionScopeIndexToStopAt
17165   if (FunctionScopeIndexToStopAt) {
17166     unsigned FSIndex = FunctionScopes.size() - 1;
17167     while (FSIndex != MaxFunctionScopesIndex) {
17168       DC = getLambdaAwareParentOfDeclContext(DC);
17169       --FSIndex;
17170     }
17171   }
17172 
17173 
17174   // If the variable is declared in the current context, there is no need to
17175   // capture it.
17176   if (VarDC == DC) return true;
17177 
17178   // Capture global variables if it is required to use private copy of this
17179   // variable.
17180   bool IsGlobal = !Var->hasLocalStorage();
17181   if (IsGlobal &&
17182       !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true,
17183                                                 MaxFunctionScopesIndex)))
17184     return true;
17185   Var = Var->getCanonicalDecl();
17186 
17187   // Walk up the stack to determine whether we can capture the variable,
17188   // performing the "simple" checks that don't depend on type. We stop when
17189   // we've either hit the declared scope of the variable or find an existing
17190   // capture of that variable.  We start from the innermost capturing-entity
17191   // (the DC) and ensure that all intervening capturing-entities
17192   // (blocks/lambdas etc.) between the innermost capturer and the variable`s
17193   // declcontext can either capture the variable or have already captured
17194   // the variable.
17195   CaptureType = Var->getType();
17196   DeclRefType = CaptureType.getNonReferenceType();
17197   bool Nested = false;
17198   bool Explicit = (Kind != TryCapture_Implicit);
17199   unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
17200   do {
17201     // Only block literals, captured statements, and lambda expressions can
17202     // capture; other scopes don't work.
17203     DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
17204                                                               ExprLoc,
17205                                                               BuildAndDiagnose,
17206                                                               *this);
17207     // We need to check for the parent *first* because, if we *have*
17208     // private-captured a global variable, we need to recursively capture it in
17209     // intermediate blocks, lambdas, etc.
17210     if (!ParentDC) {
17211       if (IsGlobal) {
17212         FunctionScopesIndex = MaxFunctionScopesIndex - 1;
17213         break;
17214       }
17215       return true;
17216     }
17217 
17218     FunctionScopeInfo  *FSI = FunctionScopes[FunctionScopesIndex];
17219     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
17220 
17221 
17222     // Check whether we've already captured it.
17223     if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
17224                                              DeclRefType)) {
17225       CSI->getCapture(Var).markUsed(BuildAndDiagnose);
17226       break;
17227     }
17228     // If we are instantiating a generic lambda call operator body,
17229     // we do not want to capture new variables.  What was captured
17230     // during either a lambdas transformation or initial parsing
17231     // should be used.
17232     if (isGenericLambdaCallOperatorSpecialization(DC)) {
17233       if (BuildAndDiagnose) {
17234         LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
17235         if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
17236           Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
17237           Diag(Var->getLocation(), diag::note_previous_decl)
17238              << Var->getDeclName();
17239           Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
17240         } else
17241           diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
17242       }
17243       return true;
17244     }
17245 
17246     // Try to capture variable-length arrays types.
17247     if (Var->getType()->isVariablyModifiedType()) {
17248       // We're going to walk down into the type and look for VLA
17249       // expressions.
17250       QualType QTy = Var->getType();
17251       if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
17252         QTy = PVD->getOriginalType();
17253       captureVariablyModifiedType(Context, QTy, CSI);
17254     }
17255 
17256     if (getLangOpts().OpenMP) {
17257       if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
17258         // OpenMP private variables should not be captured in outer scope, so
17259         // just break here. Similarly, global variables that are captured in a
17260         // target region should not be captured outside the scope of the region.
17261         if (RSI->CapRegionKind == CR_OpenMP) {
17262           OpenMPClauseKind IsOpenMPPrivateDecl = isOpenMPPrivateDecl(
17263               Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel);
17264           // If the variable is private (i.e. not captured) and has variably
17265           // modified type, we still need to capture the type for correct
17266           // codegen in all regions, associated with the construct. Currently,
17267           // it is captured in the innermost captured region only.
17268           if (IsOpenMPPrivateDecl != OMPC_unknown &&
17269               Var->getType()->isVariablyModifiedType()) {
17270             QualType QTy = Var->getType();
17271             if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
17272               QTy = PVD->getOriginalType();
17273             for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel);
17274                  I < E; ++I) {
17275               auto *OuterRSI = cast<CapturedRegionScopeInfo>(
17276                   FunctionScopes[FunctionScopesIndex - I]);
17277               assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel &&
17278                      "Wrong number of captured regions associated with the "
17279                      "OpenMP construct.");
17280               captureVariablyModifiedType(Context, QTy, OuterRSI);
17281             }
17282           }
17283           bool IsTargetCap =
17284               IsOpenMPPrivateDecl != OMPC_private &&
17285               isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel,
17286                                          RSI->OpenMPCaptureLevel);
17287           // Do not capture global if it is not privatized in outer regions.
17288           bool IsGlobalCap =
17289               IsGlobal && isOpenMPGlobalCapturedDecl(Var, RSI->OpenMPLevel,
17290                                                      RSI->OpenMPCaptureLevel);
17291 
17292           // When we detect target captures we are looking from inside the
17293           // target region, therefore we need to propagate the capture from the
17294           // enclosing region. Therefore, the capture is not initially nested.
17295           if (IsTargetCap)
17296             adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel);
17297 
17298           if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private ||
17299               (IsGlobal && !IsGlobalCap)) {
17300             Nested = !IsTargetCap;
17301             DeclRefType = DeclRefType.getUnqualifiedType();
17302             CaptureType = Context.getLValueReferenceType(DeclRefType);
17303             break;
17304           }
17305         }
17306       }
17307     }
17308     if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
17309       // No capture-default, and this is not an explicit capture
17310       // so cannot capture this variable.
17311       if (BuildAndDiagnose) {
17312         Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
17313         Diag(Var->getLocation(), diag::note_previous_decl)
17314           << Var->getDeclName();
17315         if (cast<LambdaScopeInfo>(CSI)->Lambda)
17316           Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getBeginLoc(),
17317                diag::note_lambda_decl);
17318         // FIXME: If we error out because an outer lambda can not implicitly
17319         // capture a variable that an inner lambda explicitly captures, we
17320         // should have the inner lambda do the explicit capture - because
17321         // it makes for cleaner diagnostics later.  This would purely be done
17322         // so that the diagnostic does not misleadingly claim that a variable
17323         // can not be captured by a lambda implicitly even though it is captured
17324         // explicitly.  Suggestion:
17325         //  - create const bool VariableCaptureWasInitiallyExplicit = Explicit
17326         //    at the function head
17327         //  - cache the StartingDeclContext - this must be a lambda
17328         //  - captureInLambda in the innermost lambda the variable.
17329       }
17330       return true;
17331     }
17332 
17333     FunctionScopesIndex--;
17334     DC = ParentDC;
17335     Explicit = false;
17336   } while (!VarDC->Equals(DC));
17337 
17338   // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
17339   // computing the type of the capture at each step, checking type-specific
17340   // requirements, and adding captures if requested.
17341   // If the variable had already been captured previously, we start capturing
17342   // at the lambda nested within that one.
17343   bool Invalid = false;
17344   for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
17345        ++I) {
17346     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
17347 
17348     // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
17349     // certain types of variables (unnamed, variably modified types etc.)
17350     // so check for eligibility.
17351     if (!Invalid)
17352       Invalid =
17353           !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this);
17354 
17355     // After encountering an error, if we're actually supposed to capture, keep
17356     // capturing in nested contexts to suppress any follow-on diagnostics.
17357     if (Invalid && !BuildAndDiagnose)
17358       return true;
17359 
17360     if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
17361       Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
17362                                DeclRefType, Nested, *this, Invalid);
17363       Nested = true;
17364     } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
17365       Invalid = !captureInCapturedRegion(RSI, Var, ExprLoc, BuildAndDiagnose,
17366                                          CaptureType, DeclRefType, Nested,
17367                                          *this, Invalid);
17368       Nested = true;
17369     } else {
17370       LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
17371       Invalid =
17372           !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
17373                            DeclRefType, Nested, Kind, EllipsisLoc,
17374                            /*IsTopScope*/ I == N - 1, *this, Invalid);
17375       Nested = true;
17376     }
17377 
17378     if (Invalid && !BuildAndDiagnose)
17379       return true;
17380   }
17381   return Invalid;
17382 }
17383 
17384 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
17385                               TryCaptureKind Kind, SourceLocation EllipsisLoc) {
17386   QualType CaptureType;
17387   QualType DeclRefType;
17388   return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
17389                             /*BuildAndDiagnose=*/true, CaptureType,
17390                             DeclRefType, nullptr);
17391 }
17392 
17393 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
17394   QualType CaptureType;
17395   QualType DeclRefType;
17396   return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
17397                              /*BuildAndDiagnose=*/false, CaptureType,
17398                              DeclRefType, nullptr);
17399 }
17400 
17401 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
17402   QualType CaptureType;
17403   QualType DeclRefType;
17404 
17405   // Determine whether we can capture this variable.
17406   if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
17407                          /*BuildAndDiagnose=*/false, CaptureType,
17408                          DeclRefType, nullptr))
17409     return QualType();
17410 
17411   return DeclRefType;
17412 }
17413 
17414 namespace {
17415 // Helper to copy the template arguments from a DeclRefExpr or MemberExpr.
17416 // The produced TemplateArgumentListInfo* points to data stored within this
17417 // object, so should only be used in contexts where the pointer will not be
17418 // used after the CopiedTemplateArgs object is destroyed.
17419 class CopiedTemplateArgs {
17420   bool HasArgs;
17421   TemplateArgumentListInfo TemplateArgStorage;
17422 public:
17423   template<typename RefExpr>
17424   CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) {
17425     if (HasArgs)
17426       E->copyTemplateArgumentsInto(TemplateArgStorage);
17427   }
17428   operator TemplateArgumentListInfo*()
17429 #ifdef __has_cpp_attribute
17430 #if __has_cpp_attribute(clang::lifetimebound)
17431   [[clang::lifetimebound]]
17432 #endif
17433 #endif
17434   {
17435     return HasArgs ? &TemplateArgStorage : nullptr;
17436   }
17437 };
17438 }
17439 
17440 /// Walk the set of potential results of an expression and mark them all as
17441 /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason.
17442 ///
17443 /// \return A new expression if we found any potential results, ExprEmpty() if
17444 ///         not, and ExprError() if we diagnosed an error.
17445 static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E,
17446                                                       NonOdrUseReason NOUR) {
17447   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
17448   // an object that satisfies the requirements for appearing in a
17449   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
17450   // is immediately applied."  This function handles the lvalue-to-rvalue
17451   // conversion part.
17452   //
17453   // If we encounter a node that claims to be an odr-use but shouldn't be, we
17454   // transform it into the relevant kind of non-odr-use node and rebuild the
17455   // tree of nodes leading to it.
17456   //
17457   // This is a mini-TreeTransform that only transforms a restricted subset of
17458   // nodes (and only certain operands of them).
17459 
17460   // Rebuild a subexpression.
17461   auto Rebuild = [&](Expr *Sub) {
17462     return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR);
17463   };
17464 
17465   // Check whether a potential result satisfies the requirements of NOUR.
17466   auto IsPotentialResultOdrUsed = [&](NamedDecl *D) {
17467     // Any entity other than a VarDecl is always odr-used whenever it's named
17468     // in a potentially-evaluated expression.
17469     auto *VD = dyn_cast<VarDecl>(D);
17470     if (!VD)
17471       return true;
17472 
17473     // C++2a [basic.def.odr]p4:
17474     //   A variable x whose name appears as a potentially-evalauted expression
17475     //   e is odr-used by e unless
17476     //   -- x is a reference that is usable in constant expressions, or
17477     //   -- x is a variable of non-reference type that is usable in constant
17478     //      expressions and has no mutable subobjects, and e is an element of
17479     //      the set of potential results of an expression of
17480     //      non-volatile-qualified non-class type to which the lvalue-to-rvalue
17481     //      conversion is applied, or
17482     //   -- x is a variable of non-reference type, and e is an element of the
17483     //      set of potential results of a discarded-value expression to which
17484     //      the lvalue-to-rvalue conversion is not applied
17485     //
17486     // We check the first bullet and the "potentially-evaluated" condition in
17487     // BuildDeclRefExpr. We check the type requirements in the second bullet
17488     // in CheckLValueToRValueConversionOperand below.
17489     switch (NOUR) {
17490     case NOUR_None:
17491     case NOUR_Unevaluated:
17492       llvm_unreachable("unexpected non-odr-use-reason");
17493 
17494     case NOUR_Constant:
17495       // Constant references were handled when they were built.
17496       if (VD->getType()->isReferenceType())
17497         return true;
17498       if (auto *RD = VD->getType()->getAsCXXRecordDecl())
17499         if (RD->hasMutableFields())
17500           return true;
17501       if (!VD->isUsableInConstantExpressions(S.Context))
17502         return true;
17503       break;
17504 
17505     case NOUR_Discarded:
17506       if (VD->getType()->isReferenceType())
17507         return true;
17508       break;
17509     }
17510     return false;
17511   };
17512 
17513   // Mark that this expression does not constitute an odr-use.
17514   auto MarkNotOdrUsed = [&] {
17515     S.MaybeODRUseExprs.erase(E);
17516     if (LambdaScopeInfo *LSI = S.getCurLambda())
17517       LSI->markVariableExprAsNonODRUsed(E);
17518   };
17519 
17520   // C++2a [basic.def.odr]p2:
17521   //   The set of potential results of an expression e is defined as follows:
17522   switch (E->getStmtClass()) {
17523   //   -- If e is an id-expression, ...
17524   case Expr::DeclRefExprClass: {
17525     auto *DRE = cast<DeclRefExpr>(E);
17526     if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl()))
17527       break;
17528 
17529     // Rebuild as a non-odr-use DeclRefExpr.
17530     MarkNotOdrUsed();
17531     return DeclRefExpr::Create(
17532         S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(),
17533         DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(),
17534         DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(),
17535         DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR);
17536   }
17537 
17538   case Expr::FunctionParmPackExprClass: {
17539     auto *FPPE = cast<FunctionParmPackExpr>(E);
17540     // If any of the declarations in the pack is odr-used, then the expression
17541     // as a whole constitutes an odr-use.
17542     for (VarDecl *D : *FPPE)
17543       if (IsPotentialResultOdrUsed(D))
17544         return ExprEmpty();
17545 
17546     // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice,
17547     // nothing cares about whether we marked this as an odr-use, but it might
17548     // be useful for non-compiler tools.
17549     MarkNotOdrUsed();
17550     break;
17551   }
17552 
17553   //   -- If e is a subscripting operation with an array operand...
17554   case Expr::ArraySubscriptExprClass: {
17555     auto *ASE = cast<ArraySubscriptExpr>(E);
17556     Expr *OldBase = ASE->getBase()->IgnoreImplicit();
17557     if (!OldBase->getType()->isArrayType())
17558       break;
17559     ExprResult Base = Rebuild(OldBase);
17560     if (!Base.isUsable())
17561       return Base;
17562     Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS();
17563     Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS();
17564     SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored.
17565     return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS,
17566                                      ASE->getRBracketLoc());
17567   }
17568 
17569   case Expr::MemberExprClass: {
17570     auto *ME = cast<MemberExpr>(E);
17571     // -- If e is a class member access expression [...] naming a non-static
17572     //    data member...
17573     if (isa<FieldDecl>(ME->getMemberDecl())) {
17574       ExprResult Base = Rebuild(ME->getBase());
17575       if (!Base.isUsable())
17576         return Base;
17577       return MemberExpr::Create(
17578           S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(),
17579           ME->getQualifierLoc(), ME->getTemplateKeywordLoc(),
17580           ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(),
17581           CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(),
17582           ME->getObjectKind(), ME->isNonOdrUse());
17583     }
17584 
17585     if (ME->getMemberDecl()->isCXXInstanceMember())
17586       break;
17587 
17588     // -- If e is a class member access expression naming a static data member,
17589     //    ...
17590     if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl()))
17591       break;
17592 
17593     // Rebuild as a non-odr-use MemberExpr.
17594     MarkNotOdrUsed();
17595     return MemberExpr::Create(
17596         S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(),
17597         ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(),
17598         ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME),
17599         ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR);
17600     return ExprEmpty();
17601   }
17602 
17603   case Expr::BinaryOperatorClass: {
17604     auto *BO = cast<BinaryOperator>(E);
17605     Expr *LHS = BO->getLHS();
17606     Expr *RHS = BO->getRHS();
17607     // -- If e is a pointer-to-member expression of the form e1 .* e2 ...
17608     if (BO->getOpcode() == BO_PtrMemD) {
17609       ExprResult Sub = Rebuild(LHS);
17610       if (!Sub.isUsable())
17611         return Sub;
17612       LHS = Sub.get();
17613     //   -- If e is a comma expression, ...
17614     } else if (BO->getOpcode() == BO_Comma) {
17615       ExprResult Sub = Rebuild(RHS);
17616       if (!Sub.isUsable())
17617         return Sub;
17618       RHS = Sub.get();
17619     } else {
17620       break;
17621     }
17622     return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(),
17623                         LHS, RHS);
17624   }
17625 
17626   //   -- If e has the form (e1)...
17627   case Expr::ParenExprClass: {
17628     auto *PE = cast<ParenExpr>(E);
17629     ExprResult Sub = Rebuild(PE->getSubExpr());
17630     if (!Sub.isUsable())
17631       return Sub;
17632     return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get());
17633   }
17634 
17635   //   -- If e is a glvalue conditional expression, ...
17636   // We don't apply this to a binary conditional operator. FIXME: Should we?
17637   case Expr::ConditionalOperatorClass: {
17638     auto *CO = cast<ConditionalOperator>(E);
17639     ExprResult LHS = Rebuild(CO->getLHS());
17640     if (LHS.isInvalid())
17641       return ExprError();
17642     ExprResult RHS = Rebuild(CO->getRHS());
17643     if (RHS.isInvalid())
17644       return ExprError();
17645     if (!LHS.isUsable() && !RHS.isUsable())
17646       return ExprEmpty();
17647     if (!LHS.isUsable())
17648       LHS = CO->getLHS();
17649     if (!RHS.isUsable())
17650       RHS = CO->getRHS();
17651     return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(),
17652                                 CO->getCond(), LHS.get(), RHS.get());
17653   }
17654 
17655   // [Clang extension]
17656   //   -- If e has the form __extension__ e1...
17657   case Expr::UnaryOperatorClass: {
17658     auto *UO = cast<UnaryOperator>(E);
17659     if (UO->getOpcode() != UO_Extension)
17660       break;
17661     ExprResult Sub = Rebuild(UO->getSubExpr());
17662     if (!Sub.isUsable())
17663       return Sub;
17664     return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension,
17665                           Sub.get());
17666   }
17667 
17668   // [Clang extension]
17669   //   -- If e has the form _Generic(...), the set of potential results is the
17670   //      union of the sets of potential results of the associated expressions.
17671   case Expr::GenericSelectionExprClass: {
17672     auto *GSE = cast<GenericSelectionExpr>(E);
17673 
17674     SmallVector<Expr *, 4> AssocExprs;
17675     bool AnyChanged = false;
17676     for (Expr *OrigAssocExpr : GSE->getAssocExprs()) {
17677       ExprResult AssocExpr = Rebuild(OrigAssocExpr);
17678       if (AssocExpr.isInvalid())
17679         return ExprError();
17680       if (AssocExpr.isUsable()) {
17681         AssocExprs.push_back(AssocExpr.get());
17682         AnyChanged = true;
17683       } else {
17684         AssocExprs.push_back(OrigAssocExpr);
17685       }
17686     }
17687 
17688     return AnyChanged ? S.CreateGenericSelectionExpr(
17689                             GSE->getGenericLoc(), GSE->getDefaultLoc(),
17690                             GSE->getRParenLoc(), GSE->getControllingExpr(),
17691                             GSE->getAssocTypeSourceInfos(), AssocExprs)
17692                       : ExprEmpty();
17693   }
17694 
17695   // [Clang extension]
17696   //   -- If e has the form __builtin_choose_expr(...), the set of potential
17697   //      results is the union of the sets of potential results of the
17698   //      second and third subexpressions.
17699   case Expr::ChooseExprClass: {
17700     auto *CE = cast<ChooseExpr>(E);
17701 
17702     ExprResult LHS = Rebuild(CE->getLHS());
17703     if (LHS.isInvalid())
17704       return ExprError();
17705 
17706     ExprResult RHS = Rebuild(CE->getLHS());
17707     if (RHS.isInvalid())
17708       return ExprError();
17709 
17710     if (!LHS.get() && !RHS.get())
17711       return ExprEmpty();
17712     if (!LHS.isUsable())
17713       LHS = CE->getLHS();
17714     if (!RHS.isUsable())
17715       RHS = CE->getRHS();
17716 
17717     return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(),
17718                              RHS.get(), CE->getRParenLoc());
17719   }
17720 
17721   // Step through non-syntactic nodes.
17722   case Expr::ConstantExprClass: {
17723     auto *CE = cast<ConstantExpr>(E);
17724     ExprResult Sub = Rebuild(CE->getSubExpr());
17725     if (!Sub.isUsable())
17726       return Sub;
17727     return ConstantExpr::Create(S.Context, Sub.get());
17728   }
17729 
17730   // We could mostly rely on the recursive rebuilding to rebuild implicit
17731   // casts, but not at the top level, so rebuild them here.
17732   case Expr::ImplicitCastExprClass: {
17733     auto *ICE = cast<ImplicitCastExpr>(E);
17734     // Only step through the narrow set of cast kinds we expect to encounter.
17735     // Anything else suggests we've left the region in which potential results
17736     // can be found.
17737     switch (ICE->getCastKind()) {
17738     case CK_NoOp:
17739     case CK_DerivedToBase:
17740     case CK_UncheckedDerivedToBase: {
17741       ExprResult Sub = Rebuild(ICE->getSubExpr());
17742       if (!Sub.isUsable())
17743         return Sub;
17744       CXXCastPath Path(ICE->path());
17745       return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(),
17746                                  ICE->getValueKind(), &Path);
17747     }
17748 
17749     default:
17750       break;
17751     }
17752     break;
17753   }
17754 
17755   default:
17756     break;
17757   }
17758 
17759   // Can't traverse through this node. Nothing to do.
17760   return ExprEmpty();
17761 }
17762 
17763 ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) {
17764   // Check whether the operand is or contains an object of non-trivial C union
17765   // type.
17766   if (E->getType().isVolatileQualified() &&
17767       (E->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
17768        E->getType().hasNonTrivialToPrimitiveCopyCUnion()))
17769     checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
17770                           Sema::NTCUC_LValueToRValueVolatile,
17771                           NTCUK_Destruct|NTCUK_Copy);
17772 
17773   // C++2a [basic.def.odr]p4:
17774   //   [...] an expression of non-volatile-qualified non-class type to which
17775   //   the lvalue-to-rvalue conversion is applied [...]
17776   if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>())
17777     return E;
17778 
17779   ExprResult Result =
17780       rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant);
17781   if (Result.isInvalid())
17782     return ExprError();
17783   return Result.get() ? Result : E;
17784 }
17785 
17786 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
17787   Res = CorrectDelayedTyposInExpr(Res);
17788 
17789   if (!Res.isUsable())
17790     return Res;
17791 
17792   // If a constant-expression is a reference to a variable where we delay
17793   // deciding whether it is an odr-use, just assume we will apply the
17794   // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
17795   // (a non-type template argument), we have special handling anyway.
17796   return CheckLValueToRValueConversionOperand(Res.get());
17797 }
17798 
17799 void Sema::CleanupVarDeclMarking() {
17800   // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
17801   // call.
17802   MaybeODRUseExprSet LocalMaybeODRUseExprs;
17803   std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs);
17804 
17805   for (Expr *E : LocalMaybeODRUseExprs) {
17806     if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
17807       MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()),
17808                          DRE->getLocation(), *this);
17809     } else if (auto *ME = dyn_cast<MemberExpr>(E)) {
17810       MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(),
17811                          *this);
17812     } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) {
17813       for (VarDecl *VD : *FP)
17814         MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this);
17815     } else {
17816       llvm_unreachable("Unexpected expression");
17817     }
17818   }
17819 
17820   assert(MaybeODRUseExprs.empty() &&
17821          "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?");
17822 }
17823 
17824 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
17825                                     VarDecl *Var, Expr *E) {
17826   assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||
17827           isa<FunctionParmPackExpr>(E)) &&
17828          "Invalid Expr argument to DoMarkVarDeclReferenced");
17829   Var->setReferenced();
17830 
17831   if (Var->isInvalidDecl())
17832     return;
17833 
17834   auto *MSI = Var->getMemberSpecializationInfo();
17835   TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind()
17836                                        : Var->getTemplateSpecializationKind();
17837 
17838   OdrUseContext OdrUse = isOdrUseContext(SemaRef);
17839   bool UsableInConstantExpr =
17840       Var->mightBeUsableInConstantExpressions(SemaRef.Context);
17841 
17842   // C++20 [expr.const]p12:
17843   //   A variable [...] is needed for constant evaluation if it is [...] a
17844   //   variable whose name appears as a potentially constant evaluated
17845   //   expression that is either a contexpr variable or is of non-volatile
17846   //   const-qualified integral type or of reference type
17847   bool NeededForConstantEvaluation =
17848       isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr;
17849 
17850   bool NeedDefinition =
17851       OdrUse == OdrUseContext::Used || NeededForConstantEvaluation;
17852 
17853   VarTemplateSpecializationDecl *VarSpec =
17854       dyn_cast<VarTemplateSpecializationDecl>(Var);
17855   assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
17856          "Can't instantiate a partial template specialization.");
17857 
17858   // If this might be a member specialization of a static data member, check
17859   // the specialization is visible. We already did the checks for variable
17860   // template specializations when we created them.
17861   if (NeedDefinition && TSK != TSK_Undeclared &&
17862       !isa<VarTemplateSpecializationDecl>(Var))
17863     SemaRef.checkSpecializationVisibility(Loc, Var);
17864 
17865   // Perform implicit instantiation of static data members, static data member
17866   // templates of class templates, and variable template specializations. Delay
17867   // instantiations of variable templates, except for those that could be used
17868   // in a constant expression.
17869   if (NeedDefinition && isTemplateInstantiation(TSK)) {
17870     // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
17871     // instantiation declaration if a variable is usable in a constant
17872     // expression (among other cases).
17873     bool TryInstantiating =
17874         TSK == TSK_ImplicitInstantiation ||
17875         (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
17876 
17877     if (TryInstantiating) {
17878       SourceLocation PointOfInstantiation =
17879           MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation();
17880       bool FirstInstantiation = PointOfInstantiation.isInvalid();
17881       if (FirstInstantiation) {
17882         PointOfInstantiation = Loc;
17883         if (MSI)
17884           MSI->setPointOfInstantiation(PointOfInstantiation);
17885         else
17886           Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
17887       }
17888 
17889       bool InstantiationDependent = false;
17890       bool IsNonDependent =
17891           VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
17892                         VarSpec->getTemplateArgsInfo(), InstantiationDependent)
17893                   : true;
17894 
17895       // Do not instantiate specializations that are still type-dependent.
17896       if (IsNonDependent) {
17897         if (UsableInConstantExpr) {
17898           // Do not defer instantiations of variables that could be used in a
17899           // constant expression.
17900           SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] {
17901             SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
17902           });
17903         } else if (FirstInstantiation ||
17904                    isa<VarTemplateSpecializationDecl>(Var)) {
17905           // FIXME: For a specialization of a variable template, we don't
17906           // distinguish between "declaration and type implicitly instantiated"
17907           // and "implicit instantiation of definition requested", so we have
17908           // no direct way to avoid enqueueing the pending instantiation
17909           // multiple times.
17910           SemaRef.PendingInstantiations
17911               .push_back(std::make_pair(Var, PointOfInstantiation));
17912         }
17913       }
17914     }
17915   }
17916 
17917   // C++2a [basic.def.odr]p4:
17918   //   A variable x whose name appears as a potentially-evaluated expression e
17919   //   is odr-used by e unless
17920   //   -- x is a reference that is usable in constant expressions
17921   //   -- x is a variable of non-reference type that is usable in constant
17922   //      expressions and has no mutable subobjects [FIXME], and e is an
17923   //      element of the set of potential results of an expression of
17924   //      non-volatile-qualified non-class type to which the lvalue-to-rvalue
17925   //      conversion is applied
17926   //   -- x is a variable of non-reference type, and e is an element of the set
17927   //      of potential results of a discarded-value expression to which the
17928   //      lvalue-to-rvalue conversion is not applied [FIXME]
17929   //
17930   // We check the first part of the second bullet here, and
17931   // Sema::CheckLValueToRValueConversionOperand deals with the second part.
17932   // FIXME: To get the third bullet right, we need to delay this even for
17933   // variables that are not usable in constant expressions.
17934 
17935   // If we already know this isn't an odr-use, there's nothing more to do.
17936   if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E))
17937     if (DRE->isNonOdrUse())
17938       return;
17939   if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E))
17940     if (ME->isNonOdrUse())
17941       return;
17942 
17943   switch (OdrUse) {
17944   case OdrUseContext::None:
17945     assert((!E || isa<FunctionParmPackExpr>(E)) &&
17946            "missing non-odr-use marking for unevaluated decl ref");
17947     break;
17948 
17949   case OdrUseContext::FormallyOdrUsed:
17950     // FIXME: Ignoring formal odr-uses results in incorrect lambda capture
17951     // behavior.
17952     break;
17953 
17954   case OdrUseContext::Used:
17955     // If we might later find that this expression isn't actually an odr-use,
17956     // delay the marking.
17957     if (E && Var->isUsableInConstantExpressions(SemaRef.Context))
17958       SemaRef.MaybeODRUseExprs.insert(E);
17959     else
17960       MarkVarDeclODRUsed(Var, Loc, SemaRef);
17961     break;
17962 
17963   case OdrUseContext::Dependent:
17964     // If this is a dependent context, we don't need to mark variables as
17965     // odr-used, but we may still need to track them for lambda capture.
17966     // FIXME: Do we also need to do this inside dependent typeid expressions
17967     // (which are modeled as unevaluated at this point)?
17968     const bool RefersToEnclosingScope =
17969         (SemaRef.CurContext != Var->getDeclContext() &&
17970          Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
17971     if (RefersToEnclosingScope) {
17972       LambdaScopeInfo *const LSI =
17973           SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
17974       if (LSI && (!LSI->CallOperator ||
17975                   !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
17976         // If a variable could potentially be odr-used, defer marking it so
17977         // until we finish analyzing the full expression for any
17978         // lvalue-to-rvalue
17979         // or discarded value conversions that would obviate odr-use.
17980         // Add it to the list of potential captures that will be analyzed
17981         // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
17982         // unless the variable is a reference that was initialized by a constant
17983         // expression (this will never need to be captured or odr-used).
17984         //
17985         // FIXME: We can simplify this a lot after implementing P0588R1.
17986         assert(E && "Capture variable should be used in an expression.");
17987         if (!Var->getType()->isReferenceType() ||
17988             !Var->isUsableInConstantExpressions(SemaRef.Context))
17989           LSI->addPotentialCapture(E->IgnoreParens());
17990       }
17991     }
17992     break;
17993   }
17994 }
17995 
17996 /// Mark a variable referenced, and check whether it is odr-used
17997 /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
17998 /// used directly for normal expressions referring to VarDecl.
17999 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
18000   DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
18001 }
18002 
18003 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
18004                                Decl *D, Expr *E, bool MightBeOdrUse) {
18005   if (SemaRef.isInOpenMPDeclareTargetContext())
18006     SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
18007 
18008   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
18009     DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
18010     return;
18011   }
18012 
18013   SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
18014 
18015   // If this is a call to a method via a cast, also mark the method in the
18016   // derived class used in case codegen can devirtualize the call.
18017   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
18018   if (!ME)
18019     return;
18020   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
18021   if (!MD)
18022     return;
18023   // Only attempt to devirtualize if this is truly a virtual call.
18024   bool IsVirtualCall = MD->isVirtual() &&
18025                           ME->performsVirtualDispatch(SemaRef.getLangOpts());
18026   if (!IsVirtualCall)
18027     return;
18028 
18029   // If it's possible to devirtualize the call, mark the called function
18030   // referenced.
18031   CXXMethodDecl *DM = MD->getDevirtualizedMethod(
18032       ME->getBase(), SemaRef.getLangOpts().AppleKext);
18033   if (DM)
18034     SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
18035 }
18036 
18037 /// Perform reference-marking and odr-use handling for a DeclRefExpr.
18038 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) {
18039   // TODO: update this with DR# once a defect report is filed.
18040   // C++11 defect. The address of a pure member should not be an ODR use, even
18041   // if it's a qualified reference.
18042   bool OdrUse = true;
18043   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
18044     if (Method->isVirtual() &&
18045         !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
18046       OdrUse = false;
18047 
18048   if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl()))
18049     if (!isConstantEvaluated() && FD->isConsteval() &&
18050         !RebuildingImmediateInvocation)
18051       ExprEvalContexts.back().ReferenceToConsteval.insert(E);
18052   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
18053 }
18054 
18055 /// Perform reference-marking and odr-use handling for a MemberExpr.
18056 void Sema::MarkMemberReferenced(MemberExpr *E) {
18057   // C++11 [basic.def.odr]p2:
18058   //   A non-overloaded function whose name appears as a potentially-evaluated
18059   //   expression or a member of a set of candidate functions, if selected by
18060   //   overload resolution when referred to from a potentially-evaluated
18061   //   expression, is odr-used, unless it is a pure virtual function and its
18062   //   name is not explicitly qualified.
18063   bool MightBeOdrUse = true;
18064   if (E->performsVirtualDispatch(getLangOpts())) {
18065     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
18066       if (Method->isPure())
18067         MightBeOdrUse = false;
18068   }
18069   SourceLocation Loc =
18070       E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
18071   MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse);
18072 }
18073 
18074 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr.
18075 void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) {
18076   for (VarDecl *VD : *E)
18077     MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true);
18078 }
18079 
18080 /// Perform marking for a reference to an arbitrary declaration.  It
18081 /// marks the declaration referenced, and performs odr-use checking for
18082 /// functions and variables. This method should not be used when building a
18083 /// normal expression which refers to a variable.
18084 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
18085                                  bool MightBeOdrUse) {
18086   if (MightBeOdrUse) {
18087     if (auto *VD = dyn_cast<VarDecl>(D)) {
18088       MarkVariableReferenced(Loc, VD);
18089       return;
18090     }
18091   }
18092   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
18093     MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
18094     return;
18095   }
18096   D->setReferenced();
18097 }
18098 
18099 namespace {
18100   // Mark all of the declarations used by a type as referenced.
18101   // FIXME: Not fully implemented yet! We need to have a better understanding
18102   // of when we're entering a context we should not recurse into.
18103   // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
18104   // TreeTransforms rebuilding the type in a new context. Rather than
18105   // duplicating the TreeTransform logic, we should consider reusing it here.
18106   // Currently that causes problems when rebuilding LambdaExprs.
18107   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
18108     Sema &S;
18109     SourceLocation Loc;
18110 
18111   public:
18112     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
18113 
18114     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
18115 
18116     bool TraverseTemplateArgument(const TemplateArgument &Arg);
18117   };
18118 }
18119 
18120 bool MarkReferencedDecls::TraverseTemplateArgument(
18121     const TemplateArgument &Arg) {
18122   {
18123     // A non-type template argument is a constant-evaluated context.
18124     EnterExpressionEvaluationContext Evaluated(
18125         S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
18126     if (Arg.getKind() == TemplateArgument::Declaration) {
18127       if (Decl *D = Arg.getAsDecl())
18128         S.MarkAnyDeclReferenced(Loc, D, true);
18129     } else if (Arg.getKind() == TemplateArgument::Expression) {
18130       S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false);
18131     }
18132   }
18133 
18134   return Inherited::TraverseTemplateArgument(Arg);
18135 }
18136 
18137 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
18138   MarkReferencedDecls Marker(*this, Loc);
18139   Marker.TraverseType(T);
18140 }
18141 
18142 namespace {
18143 /// Helper class that marks all of the declarations referenced by
18144 /// potentially-evaluated subexpressions as "referenced".
18145 class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> {
18146 public:
18147   typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited;
18148   bool SkipLocalVariables;
18149 
18150   EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
18151       : Inherited(S), SkipLocalVariables(SkipLocalVariables) {}
18152 
18153   void visitUsedDecl(SourceLocation Loc, Decl *D) {
18154     S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D));
18155   }
18156 
18157   void VisitDeclRefExpr(DeclRefExpr *E) {
18158     // If we were asked not to visit local variables, don't.
18159     if (SkipLocalVariables) {
18160       if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
18161         if (VD->hasLocalStorage())
18162           return;
18163     }
18164     S.MarkDeclRefReferenced(E);
18165   }
18166 
18167   void VisitMemberExpr(MemberExpr *E) {
18168     S.MarkMemberReferenced(E);
18169     Visit(E->getBase());
18170   }
18171 };
18172 } // namespace
18173 
18174 /// Mark any declarations that appear within this expression or any
18175 /// potentially-evaluated subexpressions as "referenced".
18176 ///
18177 /// \param SkipLocalVariables If true, don't mark local variables as
18178 /// 'referenced'.
18179 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
18180                                             bool SkipLocalVariables) {
18181   EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
18182 }
18183 
18184 /// Emit a diagnostic that describes an effect on the run-time behavior
18185 /// of the program being compiled.
18186 ///
18187 /// This routine emits the given diagnostic when the code currently being
18188 /// type-checked is "potentially evaluated", meaning that there is a
18189 /// possibility that the code will actually be executable. Code in sizeof()
18190 /// expressions, code used only during overload resolution, etc., are not
18191 /// potentially evaluated. This routine will suppress such diagnostics or,
18192 /// in the absolutely nutty case of potentially potentially evaluated
18193 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
18194 /// later.
18195 ///
18196 /// This routine should be used for all diagnostics that describe the run-time
18197 /// behavior of a program, such as passing a non-POD value through an ellipsis.
18198 /// Failure to do so will likely result in spurious diagnostics or failures
18199 /// during overload resolution or within sizeof/alignof/typeof/typeid.
18200 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts,
18201                                const PartialDiagnostic &PD) {
18202   switch (ExprEvalContexts.back().Context) {
18203   case ExpressionEvaluationContext::Unevaluated:
18204   case ExpressionEvaluationContext::UnevaluatedList:
18205   case ExpressionEvaluationContext::UnevaluatedAbstract:
18206   case ExpressionEvaluationContext::DiscardedStatement:
18207     // The argument will never be evaluated, so don't complain.
18208     break;
18209 
18210   case ExpressionEvaluationContext::ConstantEvaluated:
18211     // Relevant diagnostics should be produced by constant evaluation.
18212     break;
18213 
18214   case ExpressionEvaluationContext::PotentiallyEvaluated:
18215   case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
18216     if (!Stmts.empty() && getCurFunctionOrMethodDecl()) {
18217       FunctionScopes.back()->PossiblyUnreachableDiags.
18218         push_back(sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
18219       return true;
18220     }
18221 
18222     // The initializer of a constexpr variable or of the first declaration of a
18223     // static data member is not syntactically a constant evaluated constant,
18224     // but nonetheless is always required to be a constant expression, so we
18225     // can skip diagnosing.
18226     // FIXME: Using the mangling context here is a hack.
18227     if (auto *VD = dyn_cast_or_null<VarDecl>(
18228             ExprEvalContexts.back().ManglingContextDecl)) {
18229       if (VD->isConstexpr() ||
18230           (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline()))
18231         break;
18232       // FIXME: For any other kind of variable, we should build a CFG for its
18233       // initializer and check whether the context in question is reachable.
18234     }
18235 
18236     Diag(Loc, PD);
18237     return true;
18238   }
18239 
18240   return false;
18241 }
18242 
18243 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
18244                                const PartialDiagnostic &PD) {
18245   return DiagRuntimeBehavior(
18246       Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD);
18247 }
18248 
18249 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
18250                                CallExpr *CE, FunctionDecl *FD) {
18251   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
18252     return false;
18253 
18254   // If we're inside a decltype's expression, don't check for a valid return
18255   // type or construct temporaries until we know whether this is the last call.
18256   if (ExprEvalContexts.back().ExprContext ==
18257       ExpressionEvaluationContextRecord::EK_Decltype) {
18258     ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
18259     return false;
18260   }
18261 
18262   class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
18263     FunctionDecl *FD;
18264     CallExpr *CE;
18265 
18266   public:
18267     CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
18268       : FD(FD), CE(CE) { }
18269 
18270     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
18271       if (!FD) {
18272         S.Diag(Loc, diag::err_call_incomplete_return)
18273           << T << CE->getSourceRange();
18274         return;
18275       }
18276 
18277       S.Diag(Loc, diag::err_call_function_incomplete_return)
18278         << CE->getSourceRange() << FD->getDeclName() << T;
18279       S.Diag(FD->getLocation(), diag::note_entity_declared_at)
18280           << FD->getDeclName();
18281     }
18282   } Diagnoser(FD, CE);
18283 
18284   if (RequireCompleteType(Loc, ReturnType, Diagnoser))
18285     return true;
18286 
18287   return false;
18288 }
18289 
18290 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
18291 // will prevent this condition from triggering, which is what we want.
18292 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
18293   SourceLocation Loc;
18294 
18295   unsigned diagnostic = diag::warn_condition_is_assignment;
18296   bool IsOrAssign = false;
18297 
18298   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
18299     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
18300       return;
18301 
18302     IsOrAssign = Op->getOpcode() == BO_OrAssign;
18303 
18304     // Greylist some idioms by putting them into a warning subcategory.
18305     if (ObjCMessageExpr *ME
18306           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
18307       Selector Sel = ME->getSelector();
18308 
18309       // self = [<foo> init...]
18310       if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
18311         diagnostic = diag::warn_condition_is_idiomatic_assignment;
18312 
18313       // <foo> = [<bar> nextObject]
18314       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
18315         diagnostic = diag::warn_condition_is_idiomatic_assignment;
18316     }
18317 
18318     Loc = Op->getOperatorLoc();
18319   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
18320     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
18321       return;
18322 
18323     IsOrAssign = Op->getOperator() == OO_PipeEqual;
18324     Loc = Op->getOperatorLoc();
18325   } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
18326     return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
18327   else {
18328     // Not an assignment.
18329     return;
18330   }
18331 
18332   Diag(Loc, diagnostic) << E->getSourceRange();
18333 
18334   SourceLocation Open = E->getBeginLoc();
18335   SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
18336   Diag(Loc, diag::note_condition_assign_silence)
18337         << FixItHint::CreateInsertion(Open, "(")
18338         << FixItHint::CreateInsertion(Close, ")");
18339 
18340   if (IsOrAssign)
18341     Diag(Loc, diag::note_condition_or_assign_to_comparison)
18342       << FixItHint::CreateReplacement(Loc, "!=");
18343   else
18344     Diag(Loc, diag::note_condition_assign_to_comparison)
18345       << FixItHint::CreateReplacement(Loc, "==");
18346 }
18347 
18348 /// Redundant parentheses over an equality comparison can indicate
18349 /// that the user intended an assignment used as condition.
18350 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
18351   // Don't warn if the parens came from a macro.
18352   SourceLocation parenLoc = ParenE->getBeginLoc();
18353   if (parenLoc.isInvalid() || parenLoc.isMacroID())
18354     return;
18355   // Don't warn for dependent expressions.
18356   if (ParenE->isTypeDependent())
18357     return;
18358 
18359   Expr *E = ParenE->IgnoreParens();
18360 
18361   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
18362     if (opE->getOpcode() == BO_EQ &&
18363         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
18364                                                            == Expr::MLV_Valid) {
18365       SourceLocation Loc = opE->getOperatorLoc();
18366 
18367       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
18368       SourceRange ParenERange = ParenE->getSourceRange();
18369       Diag(Loc, diag::note_equality_comparison_silence)
18370         << FixItHint::CreateRemoval(ParenERange.getBegin())
18371         << FixItHint::CreateRemoval(ParenERange.getEnd());
18372       Diag(Loc, diag::note_equality_comparison_to_assign)
18373         << FixItHint::CreateReplacement(Loc, "=");
18374     }
18375 }
18376 
18377 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
18378                                        bool IsConstexpr) {
18379   DiagnoseAssignmentAsCondition(E);
18380   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
18381     DiagnoseEqualityWithExtraParens(parenE);
18382 
18383   ExprResult result = CheckPlaceholderExpr(E);
18384   if (result.isInvalid()) return ExprError();
18385   E = result.get();
18386 
18387   if (!E->isTypeDependent()) {
18388     if (getLangOpts().CPlusPlus)
18389       return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
18390 
18391     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
18392     if (ERes.isInvalid())
18393       return ExprError();
18394     E = ERes.get();
18395 
18396     QualType T = E->getType();
18397     if (!T->isScalarType()) { // C99 6.8.4.1p1
18398       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
18399         << T << E->getSourceRange();
18400       return ExprError();
18401     }
18402     CheckBoolLikeConversion(E, Loc);
18403   }
18404 
18405   return E;
18406 }
18407 
18408 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
18409                                            Expr *SubExpr, ConditionKind CK) {
18410   // Empty conditions are valid in for-statements.
18411   if (!SubExpr)
18412     return ConditionResult();
18413 
18414   ExprResult Cond;
18415   switch (CK) {
18416   case ConditionKind::Boolean:
18417     Cond = CheckBooleanCondition(Loc, SubExpr);
18418     break;
18419 
18420   case ConditionKind::ConstexprIf:
18421     Cond = CheckBooleanCondition(Loc, SubExpr, true);
18422     break;
18423 
18424   case ConditionKind::Switch:
18425     Cond = CheckSwitchCondition(Loc, SubExpr);
18426     break;
18427   }
18428   if (Cond.isInvalid())
18429     return ConditionError();
18430 
18431   // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
18432   FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
18433   if (!FullExpr.get())
18434     return ConditionError();
18435 
18436   return ConditionResult(*this, nullptr, FullExpr,
18437                          CK == ConditionKind::ConstexprIf);
18438 }
18439 
18440 namespace {
18441   /// A visitor for rebuilding a call to an __unknown_any expression
18442   /// to have an appropriate type.
18443   struct RebuildUnknownAnyFunction
18444     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
18445 
18446     Sema &S;
18447 
18448     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
18449 
18450     ExprResult VisitStmt(Stmt *S) {
18451       llvm_unreachable("unexpected statement!");
18452     }
18453 
18454     ExprResult VisitExpr(Expr *E) {
18455       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
18456         << E->getSourceRange();
18457       return ExprError();
18458     }
18459 
18460     /// Rebuild an expression which simply semantically wraps another
18461     /// expression which it shares the type and value kind of.
18462     template <class T> ExprResult rebuildSugarExpr(T *E) {
18463       ExprResult SubResult = Visit(E->getSubExpr());
18464       if (SubResult.isInvalid()) return ExprError();
18465 
18466       Expr *SubExpr = SubResult.get();
18467       E->setSubExpr(SubExpr);
18468       E->setType(SubExpr->getType());
18469       E->setValueKind(SubExpr->getValueKind());
18470       assert(E->getObjectKind() == OK_Ordinary);
18471       return E;
18472     }
18473 
18474     ExprResult VisitParenExpr(ParenExpr *E) {
18475       return rebuildSugarExpr(E);
18476     }
18477 
18478     ExprResult VisitUnaryExtension(UnaryOperator *E) {
18479       return rebuildSugarExpr(E);
18480     }
18481 
18482     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
18483       ExprResult SubResult = Visit(E->getSubExpr());
18484       if (SubResult.isInvalid()) return ExprError();
18485 
18486       Expr *SubExpr = SubResult.get();
18487       E->setSubExpr(SubExpr);
18488       E->setType(S.Context.getPointerType(SubExpr->getType()));
18489       assert(E->getValueKind() == VK_RValue);
18490       assert(E->getObjectKind() == OK_Ordinary);
18491       return E;
18492     }
18493 
18494     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
18495       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
18496 
18497       E->setType(VD->getType());
18498 
18499       assert(E->getValueKind() == VK_RValue);
18500       if (S.getLangOpts().CPlusPlus &&
18501           !(isa<CXXMethodDecl>(VD) &&
18502             cast<CXXMethodDecl>(VD)->isInstance()))
18503         E->setValueKind(VK_LValue);
18504 
18505       return E;
18506     }
18507 
18508     ExprResult VisitMemberExpr(MemberExpr *E) {
18509       return resolveDecl(E, E->getMemberDecl());
18510     }
18511 
18512     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
18513       return resolveDecl(E, E->getDecl());
18514     }
18515   };
18516 }
18517 
18518 /// Given a function expression of unknown-any type, try to rebuild it
18519 /// to have a function type.
18520 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
18521   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
18522   if (Result.isInvalid()) return ExprError();
18523   return S.DefaultFunctionArrayConversion(Result.get());
18524 }
18525 
18526 namespace {
18527   /// A visitor for rebuilding an expression of type __unknown_anytype
18528   /// into one which resolves the type directly on the referring
18529   /// expression.  Strict preservation of the original source
18530   /// structure is not a goal.
18531   struct RebuildUnknownAnyExpr
18532     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
18533 
18534     Sema &S;
18535 
18536     /// The current destination type.
18537     QualType DestType;
18538 
18539     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
18540       : S(S), DestType(CastType) {}
18541 
18542     ExprResult VisitStmt(Stmt *S) {
18543       llvm_unreachable("unexpected statement!");
18544     }
18545 
18546     ExprResult VisitExpr(Expr *E) {
18547       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
18548         << E->getSourceRange();
18549       return ExprError();
18550     }
18551 
18552     ExprResult VisitCallExpr(CallExpr *E);
18553     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
18554 
18555     /// Rebuild an expression which simply semantically wraps another
18556     /// expression which it shares the type and value kind of.
18557     template <class T> ExprResult rebuildSugarExpr(T *E) {
18558       ExprResult SubResult = Visit(E->getSubExpr());
18559       if (SubResult.isInvalid()) return ExprError();
18560       Expr *SubExpr = SubResult.get();
18561       E->setSubExpr(SubExpr);
18562       E->setType(SubExpr->getType());
18563       E->setValueKind(SubExpr->getValueKind());
18564       assert(E->getObjectKind() == OK_Ordinary);
18565       return E;
18566     }
18567 
18568     ExprResult VisitParenExpr(ParenExpr *E) {
18569       return rebuildSugarExpr(E);
18570     }
18571 
18572     ExprResult VisitUnaryExtension(UnaryOperator *E) {
18573       return rebuildSugarExpr(E);
18574     }
18575 
18576     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
18577       const PointerType *Ptr = DestType->getAs<PointerType>();
18578       if (!Ptr) {
18579         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
18580           << E->getSourceRange();
18581         return ExprError();
18582       }
18583 
18584       if (isa<CallExpr>(E->getSubExpr())) {
18585         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
18586           << E->getSourceRange();
18587         return ExprError();
18588       }
18589 
18590       assert(E->getValueKind() == VK_RValue);
18591       assert(E->getObjectKind() == OK_Ordinary);
18592       E->setType(DestType);
18593 
18594       // Build the sub-expression as if it were an object of the pointee type.
18595       DestType = Ptr->getPointeeType();
18596       ExprResult SubResult = Visit(E->getSubExpr());
18597       if (SubResult.isInvalid()) return ExprError();
18598       E->setSubExpr(SubResult.get());
18599       return E;
18600     }
18601 
18602     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
18603 
18604     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
18605 
18606     ExprResult VisitMemberExpr(MemberExpr *E) {
18607       return resolveDecl(E, E->getMemberDecl());
18608     }
18609 
18610     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
18611       return resolveDecl(E, E->getDecl());
18612     }
18613   };
18614 }
18615 
18616 /// Rebuilds a call expression which yielded __unknown_anytype.
18617 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
18618   Expr *CalleeExpr = E->getCallee();
18619 
18620   enum FnKind {
18621     FK_MemberFunction,
18622     FK_FunctionPointer,
18623     FK_BlockPointer
18624   };
18625 
18626   FnKind Kind;
18627   QualType CalleeType = CalleeExpr->getType();
18628   if (CalleeType == S.Context.BoundMemberTy) {
18629     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
18630     Kind = FK_MemberFunction;
18631     CalleeType = Expr::findBoundMemberType(CalleeExpr);
18632   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
18633     CalleeType = Ptr->getPointeeType();
18634     Kind = FK_FunctionPointer;
18635   } else {
18636     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
18637     Kind = FK_BlockPointer;
18638   }
18639   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
18640 
18641   // Verify that this is a legal result type of a function.
18642   if (DestType->isArrayType() || DestType->isFunctionType()) {
18643     unsigned diagID = diag::err_func_returning_array_function;
18644     if (Kind == FK_BlockPointer)
18645       diagID = diag::err_block_returning_array_function;
18646 
18647     S.Diag(E->getExprLoc(), diagID)
18648       << DestType->isFunctionType() << DestType;
18649     return ExprError();
18650   }
18651 
18652   // Otherwise, go ahead and set DestType as the call's result.
18653   E->setType(DestType.getNonLValueExprType(S.Context));
18654   E->setValueKind(Expr::getValueKindForType(DestType));
18655   assert(E->getObjectKind() == OK_Ordinary);
18656 
18657   // Rebuild the function type, replacing the result type with DestType.
18658   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
18659   if (Proto) {
18660     // __unknown_anytype(...) is a special case used by the debugger when
18661     // it has no idea what a function's signature is.
18662     //
18663     // We want to build this call essentially under the K&R
18664     // unprototyped rules, but making a FunctionNoProtoType in C++
18665     // would foul up all sorts of assumptions.  However, we cannot
18666     // simply pass all arguments as variadic arguments, nor can we
18667     // portably just call the function under a non-variadic type; see
18668     // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
18669     // However, it turns out that in practice it is generally safe to
18670     // call a function declared as "A foo(B,C,D);" under the prototype
18671     // "A foo(B,C,D,...);".  The only known exception is with the
18672     // Windows ABI, where any variadic function is implicitly cdecl
18673     // regardless of its normal CC.  Therefore we change the parameter
18674     // types to match the types of the arguments.
18675     //
18676     // This is a hack, but it is far superior to moving the
18677     // corresponding target-specific code from IR-gen to Sema/AST.
18678 
18679     ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
18680     SmallVector<QualType, 8> ArgTypes;
18681     if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
18682       ArgTypes.reserve(E->getNumArgs());
18683       for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
18684         Expr *Arg = E->getArg(i);
18685         QualType ArgType = Arg->getType();
18686         if (E->isLValue()) {
18687           ArgType = S.Context.getLValueReferenceType(ArgType);
18688         } else if (E->isXValue()) {
18689           ArgType = S.Context.getRValueReferenceType(ArgType);
18690         }
18691         ArgTypes.push_back(ArgType);
18692       }
18693       ParamTypes = ArgTypes;
18694     }
18695     DestType = S.Context.getFunctionType(DestType, ParamTypes,
18696                                          Proto->getExtProtoInfo());
18697   } else {
18698     DestType = S.Context.getFunctionNoProtoType(DestType,
18699                                                 FnType->getExtInfo());
18700   }
18701 
18702   // Rebuild the appropriate pointer-to-function type.
18703   switch (Kind) {
18704   case FK_MemberFunction:
18705     // Nothing to do.
18706     break;
18707 
18708   case FK_FunctionPointer:
18709     DestType = S.Context.getPointerType(DestType);
18710     break;
18711 
18712   case FK_BlockPointer:
18713     DestType = S.Context.getBlockPointerType(DestType);
18714     break;
18715   }
18716 
18717   // Finally, we can recurse.
18718   ExprResult CalleeResult = Visit(CalleeExpr);
18719   if (!CalleeResult.isUsable()) return ExprError();
18720   E->setCallee(CalleeResult.get());
18721 
18722   // Bind a temporary if necessary.
18723   return S.MaybeBindToTemporary(E);
18724 }
18725 
18726 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
18727   // Verify that this is a legal result type of a call.
18728   if (DestType->isArrayType() || DestType->isFunctionType()) {
18729     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
18730       << DestType->isFunctionType() << DestType;
18731     return ExprError();
18732   }
18733 
18734   // Rewrite the method result type if available.
18735   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
18736     assert(Method->getReturnType() == S.Context.UnknownAnyTy);
18737     Method->setReturnType(DestType);
18738   }
18739 
18740   // Change the type of the message.
18741   E->setType(DestType.getNonReferenceType());
18742   E->setValueKind(Expr::getValueKindForType(DestType));
18743 
18744   return S.MaybeBindToTemporary(E);
18745 }
18746 
18747 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
18748   // The only case we should ever see here is a function-to-pointer decay.
18749   if (E->getCastKind() == CK_FunctionToPointerDecay) {
18750     assert(E->getValueKind() == VK_RValue);
18751     assert(E->getObjectKind() == OK_Ordinary);
18752 
18753     E->setType(DestType);
18754 
18755     // Rebuild the sub-expression as the pointee (function) type.
18756     DestType = DestType->castAs<PointerType>()->getPointeeType();
18757 
18758     ExprResult Result = Visit(E->getSubExpr());
18759     if (!Result.isUsable()) return ExprError();
18760 
18761     E->setSubExpr(Result.get());
18762     return E;
18763   } else if (E->getCastKind() == CK_LValueToRValue) {
18764     assert(E->getValueKind() == VK_RValue);
18765     assert(E->getObjectKind() == OK_Ordinary);
18766 
18767     assert(isa<BlockPointerType>(E->getType()));
18768 
18769     E->setType(DestType);
18770 
18771     // The sub-expression has to be a lvalue reference, so rebuild it as such.
18772     DestType = S.Context.getLValueReferenceType(DestType);
18773 
18774     ExprResult Result = Visit(E->getSubExpr());
18775     if (!Result.isUsable()) return ExprError();
18776 
18777     E->setSubExpr(Result.get());
18778     return E;
18779   } else {
18780     llvm_unreachable("Unhandled cast type!");
18781   }
18782 }
18783 
18784 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
18785   ExprValueKind ValueKind = VK_LValue;
18786   QualType Type = DestType;
18787 
18788   // We know how to make this work for certain kinds of decls:
18789 
18790   //  - functions
18791   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
18792     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
18793       DestType = Ptr->getPointeeType();
18794       ExprResult Result = resolveDecl(E, VD);
18795       if (Result.isInvalid()) return ExprError();
18796       return S.ImpCastExprToType(Result.get(), Type,
18797                                  CK_FunctionToPointerDecay, VK_RValue);
18798     }
18799 
18800     if (!Type->isFunctionType()) {
18801       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
18802         << VD << E->getSourceRange();
18803       return ExprError();
18804     }
18805     if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
18806       // We must match the FunctionDecl's type to the hack introduced in
18807       // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
18808       // type. See the lengthy commentary in that routine.
18809       QualType FDT = FD->getType();
18810       const FunctionType *FnType = FDT->castAs<FunctionType>();
18811       const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
18812       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
18813       if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
18814         SourceLocation Loc = FD->getLocation();
18815         FunctionDecl *NewFD = FunctionDecl::Create(
18816             S.Context, FD->getDeclContext(), Loc, Loc,
18817             FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(),
18818             SC_None, false /*isInlineSpecified*/, FD->hasPrototype(),
18819             /*ConstexprKind*/ CSK_unspecified);
18820 
18821         if (FD->getQualifier())
18822           NewFD->setQualifierInfo(FD->getQualifierLoc());
18823 
18824         SmallVector<ParmVarDecl*, 16> Params;
18825         for (const auto &AI : FT->param_types()) {
18826           ParmVarDecl *Param =
18827             S.BuildParmVarDeclForTypedef(FD, Loc, AI);
18828           Param->setScopeInfo(0, Params.size());
18829           Params.push_back(Param);
18830         }
18831         NewFD->setParams(Params);
18832         DRE->setDecl(NewFD);
18833         VD = DRE->getDecl();
18834       }
18835     }
18836 
18837     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
18838       if (MD->isInstance()) {
18839         ValueKind = VK_RValue;
18840         Type = S.Context.BoundMemberTy;
18841       }
18842 
18843     // Function references aren't l-values in C.
18844     if (!S.getLangOpts().CPlusPlus)
18845       ValueKind = VK_RValue;
18846 
18847   //  - variables
18848   } else if (isa<VarDecl>(VD)) {
18849     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
18850       Type = RefTy->getPointeeType();
18851     } else if (Type->isFunctionType()) {
18852       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
18853         << VD << E->getSourceRange();
18854       return ExprError();
18855     }
18856 
18857   //  - nothing else
18858   } else {
18859     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
18860       << VD << E->getSourceRange();
18861     return ExprError();
18862   }
18863 
18864   // Modifying the declaration like this is friendly to IR-gen but
18865   // also really dangerous.
18866   VD->setType(DestType);
18867   E->setType(Type);
18868   E->setValueKind(ValueKind);
18869   return E;
18870 }
18871 
18872 /// Check a cast of an unknown-any type.  We intentionally only
18873 /// trigger this for C-style casts.
18874 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
18875                                      Expr *CastExpr, CastKind &CastKind,
18876                                      ExprValueKind &VK, CXXCastPath &Path) {
18877   // The type we're casting to must be either void or complete.
18878   if (!CastType->isVoidType() &&
18879       RequireCompleteType(TypeRange.getBegin(), CastType,
18880                           diag::err_typecheck_cast_to_incomplete))
18881     return ExprError();
18882 
18883   // Rewrite the casted expression from scratch.
18884   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
18885   if (!result.isUsable()) return ExprError();
18886 
18887   CastExpr = result.get();
18888   VK = CastExpr->getValueKind();
18889   CastKind = CK_NoOp;
18890 
18891   return CastExpr;
18892 }
18893 
18894 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
18895   return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
18896 }
18897 
18898 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
18899                                     Expr *arg, QualType &paramType) {
18900   // If the syntactic form of the argument is not an explicit cast of
18901   // any sort, just do default argument promotion.
18902   ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
18903   if (!castArg) {
18904     ExprResult result = DefaultArgumentPromotion(arg);
18905     if (result.isInvalid()) return ExprError();
18906     paramType = result.get()->getType();
18907     return result;
18908   }
18909 
18910   // Otherwise, use the type that was written in the explicit cast.
18911   assert(!arg->hasPlaceholderType());
18912   paramType = castArg->getTypeAsWritten();
18913 
18914   // Copy-initialize a parameter of that type.
18915   InitializedEntity entity =
18916     InitializedEntity::InitializeParameter(Context, paramType,
18917                                            /*consumed*/ false);
18918   return PerformCopyInitialization(entity, callLoc, arg);
18919 }
18920 
18921 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
18922   Expr *orig = E;
18923   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
18924   while (true) {
18925     E = E->IgnoreParenImpCasts();
18926     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
18927       E = call->getCallee();
18928       diagID = diag::err_uncasted_call_of_unknown_any;
18929     } else {
18930       break;
18931     }
18932   }
18933 
18934   SourceLocation loc;
18935   NamedDecl *d;
18936   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
18937     loc = ref->getLocation();
18938     d = ref->getDecl();
18939   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
18940     loc = mem->getMemberLoc();
18941     d = mem->getMemberDecl();
18942   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
18943     diagID = diag::err_uncasted_call_of_unknown_any;
18944     loc = msg->getSelectorStartLoc();
18945     d = msg->getMethodDecl();
18946     if (!d) {
18947       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
18948         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
18949         << orig->getSourceRange();
18950       return ExprError();
18951     }
18952   } else {
18953     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
18954       << E->getSourceRange();
18955     return ExprError();
18956   }
18957 
18958   S.Diag(loc, diagID) << d << orig->getSourceRange();
18959 
18960   // Never recoverable.
18961   return ExprError();
18962 }
18963 
18964 /// Check for operands with placeholder types and complain if found.
18965 /// Returns ExprError() if there was an error and no recovery was possible.
18966 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
18967   if (!getLangOpts().CPlusPlus) {
18968     // C cannot handle TypoExpr nodes on either side of a binop because it
18969     // doesn't handle dependent types properly, so make sure any TypoExprs have
18970     // been dealt with before checking the operands.
18971     ExprResult Result = CorrectDelayedTyposInExpr(E);
18972     if (!Result.isUsable()) return ExprError();
18973     E = Result.get();
18974   }
18975 
18976   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
18977   if (!placeholderType) return E;
18978 
18979   switch (placeholderType->getKind()) {
18980 
18981   // Overloaded expressions.
18982   case BuiltinType::Overload: {
18983     // Try to resolve a single function template specialization.
18984     // This is obligatory.
18985     ExprResult Result = E;
18986     if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
18987       return Result;
18988 
18989     // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
18990     // leaves Result unchanged on failure.
18991     Result = E;
18992     if (resolveAndFixAddressOfSingleOverloadCandidate(Result))
18993       return Result;
18994 
18995     // If that failed, try to recover with a call.
18996     tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
18997                          /*complain*/ true);
18998     return Result;
18999   }
19000 
19001   // Bound member functions.
19002   case BuiltinType::BoundMember: {
19003     ExprResult result = E;
19004     const Expr *BME = E->IgnoreParens();
19005     PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
19006     // Try to give a nicer diagnostic if it is a bound member that we recognize.
19007     if (isa<CXXPseudoDestructorExpr>(BME)) {
19008       PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
19009     } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
19010       if (ME->getMemberNameInfo().getName().getNameKind() ==
19011           DeclarationName::CXXDestructorName)
19012         PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
19013     }
19014     tryToRecoverWithCall(result, PD,
19015                          /*complain*/ true);
19016     return result;
19017   }
19018 
19019   // ARC unbridged casts.
19020   case BuiltinType::ARCUnbridgedCast: {
19021     Expr *realCast = stripARCUnbridgedCast(E);
19022     diagnoseARCUnbridgedCast(realCast);
19023     return realCast;
19024   }
19025 
19026   // Expressions of unknown type.
19027   case BuiltinType::UnknownAny:
19028     return diagnoseUnknownAnyExpr(*this, E);
19029 
19030   // Pseudo-objects.
19031   case BuiltinType::PseudoObject:
19032     return checkPseudoObjectRValue(E);
19033 
19034   case BuiltinType::BuiltinFn: {
19035     // Accept __noop without parens by implicitly converting it to a call expr.
19036     auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
19037     if (DRE) {
19038       auto *FD = cast<FunctionDecl>(DRE->getDecl());
19039       if (FD->getBuiltinID() == Builtin::BI__noop) {
19040         E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
19041                               CK_BuiltinFnToFnPtr)
19042                 .get();
19043         return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy,
19044                                 VK_RValue, SourceLocation());
19045       }
19046     }
19047 
19048     Diag(E->getBeginLoc(), diag::err_builtin_fn_use);
19049     return ExprError();
19050   }
19051 
19052   case BuiltinType::IncompleteMatrixIdx:
19053     Diag(cast<MatrixSubscriptExpr>(E->IgnoreParens())
19054              ->getRowIdx()
19055              ->getBeginLoc(),
19056          diag::err_matrix_incomplete_index);
19057     return ExprError();
19058 
19059   // Expressions of unknown type.
19060   case BuiltinType::OMPArraySection:
19061     Diag(E->getBeginLoc(), diag::err_omp_array_section_use);
19062     return ExprError();
19063 
19064   // Expressions of unknown type.
19065   case BuiltinType::OMPArrayShaping:
19066     return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use));
19067 
19068   case BuiltinType::OMPIterator:
19069     return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use));
19070 
19071   // Everything else should be impossible.
19072 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
19073   case BuiltinType::Id:
19074 #include "clang/Basic/OpenCLImageTypes.def"
19075 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
19076   case BuiltinType::Id:
19077 #include "clang/Basic/OpenCLExtensionTypes.def"
19078 #define SVE_TYPE(Name, Id, SingletonId) \
19079   case BuiltinType::Id:
19080 #include "clang/Basic/AArch64SVEACLETypes.def"
19081 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
19082 #define PLACEHOLDER_TYPE(Id, SingletonId)
19083 #include "clang/AST/BuiltinTypes.def"
19084     break;
19085   }
19086 
19087   llvm_unreachable("invalid placeholder type!");
19088 }
19089 
19090 bool Sema::CheckCaseExpression(Expr *E) {
19091   if (E->isTypeDependent())
19092     return true;
19093   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
19094     return E->getType()->isIntegralOrEnumerationType();
19095   return false;
19096 }
19097 
19098 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
19099 ExprResult
19100 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
19101   assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
19102          "Unknown Objective-C Boolean value!");
19103   QualType BoolT = Context.ObjCBuiltinBoolTy;
19104   if (!Context.getBOOLDecl()) {
19105     LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
19106                         Sema::LookupOrdinaryName);
19107     if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
19108       NamedDecl *ND = Result.getFoundDecl();
19109       if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
19110         Context.setBOOLDecl(TD);
19111     }
19112   }
19113   if (Context.getBOOLDecl())
19114     BoolT = Context.getBOOLType();
19115   return new (Context)
19116       ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
19117 }
19118 
19119 ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
19120     llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
19121     SourceLocation RParen) {
19122 
19123   StringRef Platform = getASTContext().getTargetInfo().getPlatformName();
19124 
19125   auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) {
19126     return Spec.getPlatform() == Platform;
19127   });
19128 
19129   VersionTuple Version;
19130   if (Spec != AvailSpecs.end())
19131     Version = Spec->getVersion();
19132 
19133   // The use of `@available` in the enclosing function should be analyzed to
19134   // warn when it's used inappropriately (i.e. not if(@available)).
19135   if (getCurFunctionOrMethodDecl())
19136     getEnclosingFunction()->HasPotentialAvailabilityViolations = true;
19137   else if (getCurBlock() || getCurLambda())
19138     getCurFunction()->HasPotentialAvailabilityViolations = true;
19139 
19140   return new (Context)
19141       ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
19142 }
19143 
19144 ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End,
19145                                     ArrayRef<Expr *> SubExprs, QualType T) {
19146   // FIXME: enable it for C++, RecoveryExpr is type-dependent to suppress
19147   // bogus diagnostics and this trick does not work in C.
19148   // FIXME: use containsErrors() to suppress unwanted diags in C.
19149   if (!Context.getLangOpts().RecoveryAST)
19150     return ExprError();
19151 
19152   if (isSFINAEContext())
19153     return ExprError();
19154 
19155   if (T.isNull() || !Context.getLangOpts().RecoveryASTType)
19156     // We don't know the concrete type, fallback to dependent type.
19157     T = Context.DependentTy;
19158   return RecoveryExpr::Create(Context, T, Begin, End, SubExprs);
19159 }
19160