1 //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file implements semantic analysis for expressions.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "TreeTransform.h"
14 #include "UsedDeclVisitor.h"
15 #include "clang/AST/ASTConsumer.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/ASTLambda.h"
18 #include "clang/AST/ASTMutationListener.h"
19 #include "clang/AST/CXXInheritance.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "clang/AST/DeclTemplate.h"
22 #include "clang/AST/EvaluatedExprVisitor.h"
23 #include "clang/AST/Expr.h"
24 #include "clang/AST/ExprCXX.h"
25 #include "clang/AST/ExprObjC.h"
26 #include "clang/AST/ExprOpenMP.h"
27 #include "clang/AST/RecursiveASTVisitor.h"
28 #include "clang/AST/TypeLoc.h"
29 #include "clang/Basic/Builtins.h"
30 #include "clang/Basic/PartialDiagnostic.h"
31 #include "clang/Basic/SourceManager.h"
32 #include "clang/Basic/TargetInfo.h"
33 #include "clang/Lex/LiteralSupport.h"
34 #include "clang/Lex/Preprocessor.h"
35 #include "clang/Sema/AnalysisBasedWarnings.h"
36 #include "clang/Sema/DeclSpec.h"
37 #include "clang/Sema/DelayedDiagnostic.h"
38 #include "clang/Sema/Designator.h"
39 #include "clang/Sema/Initialization.h"
40 #include "clang/Sema/Lookup.h"
41 #include "clang/Sema/Overload.h"
42 #include "clang/Sema/ParsedTemplate.h"
43 #include "clang/Sema/Scope.h"
44 #include "clang/Sema/ScopeInfo.h"
45 #include "clang/Sema/SemaFixItUtils.h"
46 #include "clang/Sema/SemaInternal.h"
47 #include "clang/Sema/Template.h"
48 #include "llvm/Support/ConvertUTF.h"
49 #include "llvm/Support/SaveAndRestore.h"
50 using namespace clang;
51 using namespace sema;
52 using llvm::RoundingMode;
53 
54 /// Determine whether the use of this declaration is valid, without
55 /// emitting diagnostics.
56 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
57   // See if this is an auto-typed variable whose initializer we are parsing.
58   if (ParsingInitForAutoVars.count(D))
59     return false;
60 
61   // See if this is a deleted function.
62   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
63     if (FD->isDeleted())
64       return false;
65 
66     // If the function has a deduced return type, and we can't deduce it,
67     // then we can't use it either.
68     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
69         DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
70       return false;
71 
72     // See if this is an aligned allocation/deallocation function that is
73     // unavailable.
74     if (TreatUnavailableAsInvalid &&
75         isUnavailableAlignedAllocationFunction(*FD))
76       return false;
77   }
78 
79   // See if this function is unavailable.
80   if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
81       cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
82     return false;
83 
84   return true;
85 }
86 
87 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
88   // Warn if this is used but marked unused.
89   if (const auto *A = D->getAttr<UnusedAttr>()) {
90     // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
91     // should diagnose them.
92     if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused &&
93         A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) {
94       const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext());
95       if (DC && !DC->hasAttr<UnusedAttr>())
96         S.Diag(Loc, diag::warn_used_but_marked_unused) << D;
97     }
98   }
99 }
100 
101 /// Emit a note explaining that this function is deleted.
102 void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
103   assert(Decl && Decl->isDeleted());
104 
105   if (Decl->isDefaulted()) {
106     // If the method was explicitly defaulted, point at that declaration.
107     if (!Decl->isImplicit())
108       Diag(Decl->getLocation(), diag::note_implicitly_deleted);
109 
110     // Try to diagnose why this special member function was implicitly
111     // deleted. This might fail, if that reason no longer applies.
112     DiagnoseDeletedDefaultedFunction(Decl);
113     return;
114   }
115 
116   auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
117   if (Ctor && Ctor->isInheritingConstructor())
118     return NoteDeletedInheritingConstructor(Ctor);
119 
120   Diag(Decl->getLocation(), diag::note_availability_specified_here)
121     << Decl << 1;
122 }
123 
124 /// Determine whether a FunctionDecl was ever declared with an
125 /// explicit storage class.
126 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
127   for (auto I : D->redecls()) {
128     if (I->getStorageClass() != SC_None)
129       return true;
130   }
131   return false;
132 }
133 
134 /// Check whether we're in an extern inline function and referring to a
135 /// variable or function with internal linkage (C11 6.7.4p3).
136 ///
137 /// This is only a warning because we used to silently accept this code, but
138 /// in many cases it will not behave correctly. This is not enabled in C++ mode
139 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
140 /// and so while there may still be user mistakes, most of the time we can't
141 /// prove that there are errors.
142 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
143                                                       const NamedDecl *D,
144                                                       SourceLocation Loc) {
145   // This is disabled under C++; there are too many ways for this to fire in
146   // contexts where the warning is a false positive, or where it is technically
147   // correct but benign.
148   if (S.getLangOpts().CPlusPlus)
149     return;
150 
151   // Check if this is an inlined function or method.
152   FunctionDecl *Current = S.getCurFunctionDecl();
153   if (!Current)
154     return;
155   if (!Current->isInlined())
156     return;
157   if (!Current->isExternallyVisible())
158     return;
159 
160   // Check if the decl has internal linkage.
161   if (D->getFormalLinkage() != InternalLinkage)
162     return;
163 
164   // Downgrade from ExtWarn to Extension if
165   //  (1) the supposedly external inline function is in the main file,
166   //      and probably won't be included anywhere else.
167   //  (2) the thing we're referencing is a pure function.
168   //  (3) the thing we're referencing is another inline function.
169   // This last can give us false negatives, but it's better than warning on
170   // wrappers for simple C library functions.
171   const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
172   bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
173   if (!DowngradeWarning && UsedFn)
174     DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
175 
176   S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
177                                : diag::ext_internal_in_extern_inline)
178     << /*IsVar=*/!UsedFn << D;
179 
180   S.MaybeSuggestAddingStaticToDecl(Current);
181 
182   S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
183       << D;
184 }
185 
186 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
187   const FunctionDecl *First = Cur->getFirstDecl();
188 
189   // Suggest "static" on the function, if possible.
190   if (!hasAnyExplicitStorageClass(First)) {
191     SourceLocation DeclBegin = First->getSourceRange().getBegin();
192     Diag(DeclBegin, diag::note_convert_inline_to_static)
193       << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
194   }
195 }
196 
197 /// Determine whether the use of this declaration is valid, and
198 /// emit any corresponding diagnostics.
199 ///
200 /// This routine diagnoses various problems with referencing
201 /// declarations that can occur when using a declaration. For example,
202 /// it might warn if a deprecated or unavailable declaration is being
203 /// used, or produce an error (and return true) if a C++0x deleted
204 /// function is being used.
205 ///
206 /// \returns true if there was an error (this declaration cannot be
207 /// referenced), false otherwise.
208 ///
209 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
210                              const ObjCInterfaceDecl *UnknownObjCClass,
211                              bool ObjCPropertyAccess,
212                              bool AvoidPartialAvailabilityChecks,
213                              ObjCInterfaceDecl *ClassReceiver) {
214   SourceLocation Loc = Locs.front();
215   if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
216     // If there were any diagnostics suppressed by template argument deduction,
217     // emit them now.
218     auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
219     if (Pos != SuppressedDiagnostics.end()) {
220       for (const PartialDiagnosticAt &Suppressed : Pos->second)
221         Diag(Suppressed.first, Suppressed.second);
222 
223       // Clear out the list of suppressed diagnostics, so that we don't emit
224       // them again for this specialization. However, we don't obsolete this
225       // entry from the table, because we want to avoid ever emitting these
226       // diagnostics again.
227       Pos->second.clear();
228     }
229 
230     // C++ [basic.start.main]p3:
231     //   The function 'main' shall not be used within a program.
232     if (cast<FunctionDecl>(D)->isMain())
233       Diag(Loc, diag::ext_main_used);
234 
235     diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc);
236   }
237 
238   // See if this is an auto-typed variable whose initializer we are parsing.
239   if (ParsingInitForAutoVars.count(D)) {
240     if (isa<BindingDecl>(D)) {
241       Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
242         << D->getDeclName();
243     } else {
244       Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
245         << D->getDeclName() << cast<VarDecl>(D)->getType();
246     }
247     return true;
248   }
249 
250   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
251     // See if this is a deleted function.
252     if (FD->isDeleted()) {
253       auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
254       if (Ctor && Ctor->isInheritingConstructor())
255         Diag(Loc, diag::err_deleted_inherited_ctor_use)
256             << Ctor->getParent()
257             << Ctor->getInheritedConstructor().getConstructor()->getParent();
258       else
259         Diag(Loc, diag::err_deleted_function_use);
260       NoteDeletedFunction(FD);
261       return true;
262     }
263 
264     // [expr.prim.id]p4
265     //   A program that refers explicitly or implicitly to a function with a
266     //   trailing requires-clause whose constraint-expression is not satisfied,
267     //   other than to declare it, is ill-formed. [...]
268     //
269     // See if this is a function with constraints that need to be satisfied.
270     // Check this before deducing the return type, as it might instantiate the
271     // definition.
272     if (FD->getTrailingRequiresClause()) {
273       ConstraintSatisfaction Satisfaction;
274       if (CheckFunctionConstraints(FD, Satisfaction, Loc))
275         // A diagnostic will have already been generated (non-constant
276         // constraint expression, for example)
277         return true;
278       if (!Satisfaction.IsSatisfied) {
279         Diag(Loc,
280              diag::err_reference_to_function_with_unsatisfied_constraints)
281             << D;
282         DiagnoseUnsatisfiedConstraint(Satisfaction);
283         return true;
284       }
285     }
286 
287     // If the function has a deduced return type, and we can't deduce it,
288     // then we can't use it either.
289     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
290         DeduceReturnType(FD, Loc))
291       return true;
292 
293     if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD))
294       return true;
295 
296     if (getLangOpts().SYCLIsDevice && !checkSYCLDeviceFunction(Loc, FD))
297       return true;
298   }
299 
300   if (auto *MD = dyn_cast<CXXMethodDecl>(D)) {
301     // Lambdas are only default-constructible or assignable in C++2a onwards.
302     if (MD->getParent()->isLambda() &&
303         ((isa<CXXConstructorDecl>(MD) &&
304           cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) ||
305          MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) {
306       Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign)
307         << !isa<CXXConstructorDecl>(MD);
308     }
309   }
310 
311   auto getReferencedObjCProp = [](const NamedDecl *D) ->
312                                       const ObjCPropertyDecl * {
313     if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
314       return MD->findPropertyDecl();
315     return nullptr;
316   };
317   if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
318     if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc))
319       return true;
320   } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) {
321       return true;
322   }
323 
324   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
325   // Only the variables omp_in and omp_out are allowed in the combiner.
326   // Only the variables omp_priv and omp_orig are allowed in the
327   // initializer-clause.
328   auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
329   if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
330       isa<VarDecl>(D)) {
331     Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
332         << getCurFunction()->HasOMPDeclareReductionCombiner;
333     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
334     return true;
335   }
336 
337   // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions
338   //  List-items in map clauses on this construct may only refer to the declared
339   //  variable var and entities that could be referenced by a procedure defined
340   //  at the same location
341   if (LangOpts.OpenMP && isa<VarDecl>(D) &&
342       !isOpenMPDeclareMapperVarDeclAllowed(cast<VarDecl>(D))) {
343     Diag(Loc, diag::err_omp_declare_mapper_wrong_var)
344         << getOpenMPDeclareMapperVarName();
345     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
346     return true;
347   }
348 
349   DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,
350                              AvoidPartialAvailabilityChecks, ClassReceiver);
351 
352   DiagnoseUnusedOfDecl(*this, D, Loc);
353 
354   diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
355 
356   if (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)) {
357     if (const auto *VD = dyn_cast<ValueDecl>(D))
358       checkDeviceDecl(VD, Loc);
359 
360     if (!Context.getTargetInfo().isTLSSupported())
361       if (const auto *VD = dyn_cast<VarDecl>(D))
362         if (VD->getTLSKind() != VarDecl::TLS_None)
363           targetDiag(*Locs.begin(), diag::err_thread_unsupported);
364   }
365 
366   if (isa<ParmVarDecl>(D) && isa<RequiresExprBodyDecl>(D->getDeclContext()) &&
367       !isUnevaluatedContext()) {
368     // C++ [expr.prim.req.nested] p3
369     //   A local parameter shall only appear as an unevaluated operand
370     //   (Clause 8) within the constraint-expression.
371     Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context)
372         << D;
373     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
374     return true;
375   }
376 
377   return false;
378 }
379 
380 /// DiagnoseSentinelCalls - This routine checks whether a call or
381 /// message-send is to a declaration with the sentinel attribute, and
382 /// if so, it checks that the requirements of the sentinel are
383 /// satisfied.
384 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
385                                  ArrayRef<Expr *> Args) {
386   const SentinelAttr *attr = D->getAttr<SentinelAttr>();
387   if (!attr)
388     return;
389 
390   // The number of formal parameters of the declaration.
391   unsigned numFormalParams;
392 
393   // The kind of declaration.  This is also an index into a %select in
394   // the diagnostic.
395   enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
396 
397   if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
398     numFormalParams = MD->param_size();
399     calleeType = CT_Method;
400   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
401     numFormalParams = FD->param_size();
402     calleeType = CT_Function;
403   } else if (isa<VarDecl>(D)) {
404     QualType type = cast<ValueDecl>(D)->getType();
405     const FunctionType *fn = nullptr;
406     if (const PointerType *ptr = type->getAs<PointerType>()) {
407       fn = ptr->getPointeeType()->getAs<FunctionType>();
408       if (!fn) return;
409       calleeType = CT_Function;
410     } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
411       fn = ptr->getPointeeType()->castAs<FunctionType>();
412       calleeType = CT_Block;
413     } else {
414       return;
415     }
416 
417     if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
418       numFormalParams = proto->getNumParams();
419     } else {
420       numFormalParams = 0;
421     }
422   } else {
423     return;
424   }
425 
426   // "nullPos" is the number of formal parameters at the end which
427   // effectively count as part of the variadic arguments.  This is
428   // useful if you would prefer to not have *any* formal parameters,
429   // but the language forces you to have at least one.
430   unsigned nullPos = attr->getNullPos();
431   assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
432   numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
433 
434   // The number of arguments which should follow the sentinel.
435   unsigned numArgsAfterSentinel = attr->getSentinel();
436 
437   // If there aren't enough arguments for all the formal parameters,
438   // the sentinel, and the args after the sentinel, complain.
439   if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
440     Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
441     Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
442     return;
443   }
444 
445   // Otherwise, find the sentinel expression.
446   Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
447   if (!sentinelExpr) return;
448   if (sentinelExpr->isValueDependent()) return;
449   if (Context.isSentinelNullExpr(sentinelExpr)) return;
450 
451   // Pick a reasonable string to insert.  Optimistically use 'nil', 'nullptr',
452   // or 'NULL' if those are actually defined in the context.  Only use
453   // 'nil' for ObjC methods, where it's much more likely that the
454   // variadic arguments form a list of object pointers.
455   SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc());
456   std::string NullValue;
457   if (calleeType == CT_Method && PP.isMacroDefined("nil"))
458     NullValue = "nil";
459   else if (getLangOpts().CPlusPlus11)
460     NullValue = "nullptr";
461   else if (PP.isMacroDefined("NULL"))
462     NullValue = "NULL";
463   else
464     NullValue = "(void*) 0";
465 
466   if (MissingNilLoc.isInvalid())
467     Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
468   else
469     Diag(MissingNilLoc, diag::warn_missing_sentinel)
470       << int(calleeType)
471       << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
472   Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
473 }
474 
475 SourceRange Sema::getExprRange(Expr *E) const {
476   return E ? E->getSourceRange() : SourceRange();
477 }
478 
479 //===----------------------------------------------------------------------===//
480 //  Standard Promotions and Conversions
481 //===----------------------------------------------------------------------===//
482 
483 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
484 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
485   // Handle any placeholder expressions which made it here.
486   if (E->getType()->isPlaceholderType()) {
487     ExprResult result = CheckPlaceholderExpr(E);
488     if (result.isInvalid()) return ExprError();
489     E = result.get();
490   }
491 
492   QualType Ty = E->getType();
493   assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
494 
495   if (Ty->isFunctionType()) {
496     if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
497       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
498         if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
499           return ExprError();
500 
501     E = ImpCastExprToType(E, Context.getPointerType(Ty),
502                           CK_FunctionToPointerDecay).get();
503   } else if (Ty->isArrayType()) {
504     // In C90 mode, arrays only promote to pointers if the array expression is
505     // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
506     // type 'array of type' is converted to an expression that has type 'pointer
507     // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
508     // that has type 'array of type' ...".  The relevant change is "an lvalue"
509     // (C90) to "an expression" (C99).
510     //
511     // C++ 4.2p1:
512     // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
513     // T" can be converted to an rvalue of type "pointer to T".
514     //
515     if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
516       E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
517                             CK_ArrayToPointerDecay).get();
518   }
519   return E;
520 }
521 
522 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
523   // Check to see if we are dereferencing a null pointer.  If so,
524   // and if not volatile-qualified, this is undefined behavior that the
525   // optimizer will delete, so warn about it.  People sometimes try to use this
526   // to get a deterministic trap and are surprised by clang's behavior.  This
527   // only handles the pattern "*null", which is a very syntactic check.
528   const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts());
529   if (UO && UO->getOpcode() == UO_Deref &&
530       UO->getSubExpr()->getType()->isPointerType()) {
531     const LangAS AS =
532         UO->getSubExpr()->getType()->getPointeeType().getAddressSpace();
533     if ((!isTargetAddressSpace(AS) ||
534          (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) &&
535         UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant(
536             S.Context, Expr::NPC_ValueDependentIsNotNull) &&
537         !UO->getType().isVolatileQualified()) {
538       S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
539                             S.PDiag(diag::warn_indirection_through_null)
540                                 << UO->getSubExpr()->getSourceRange());
541       S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
542                             S.PDiag(diag::note_indirection_through_null));
543     }
544   }
545 }
546 
547 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
548                                     SourceLocation AssignLoc,
549                                     const Expr* RHS) {
550   const ObjCIvarDecl *IV = OIRE->getDecl();
551   if (!IV)
552     return;
553 
554   DeclarationName MemberName = IV->getDeclName();
555   IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
556   if (!Member || !Member->isStr("isa"))
557     return;
558 
559   const Expr *Base = OIRE->getBase();
560   QualType BaseType = Base->getType();
561   if (OIRE->isArrow())
562     BaseType = BaseType->getPointeeType();
563   if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
564     if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
565       ObjCInterfaceDecl *ClassDeclared = nullptr;
566       ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
567       if (!ClassDeclared->getSuperClass()
568           && (*ClassDeclared->ivar_begin()) == IV) {
569         if (RHS) {
570           NamedDecl *ObjectSetClass =
571             S.LookupSingleName(S.TUScope,
572                                &S.Context.Idents.get("object_setClass"),
573                                SourceLocation(), S.LookupOrdinaryName);
574           if (ObjectSetClass) {
575             SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc());
576             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign)
577                 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
578                                               "object_setClass(")
579                 << FixItHint::CreateReplacement(
580                        SourceRange(OIRE->getOpLoc(), AssignLoc), ",")
581                 << FixItHint::CreateInsertion(RHSLocEnd, ")");
582           }
583           else
584             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
585         } else {
586           NamedDecl *ObjectGetClass =
587             S.LookupSingleName(S.TUScope,
588                                &S.Context.Idents.get("object_getClass"),
589                                SourceLocation(), S.LookupOrdinaryName);
590           if (ObjectGetClass)
591             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use)
592                 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
593                                               "object_getClass(")
594                 << FixItHint::CreateReplacement(
595                        SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")");
596           else
597             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
598         }
599         S.Diag(IV->getLocation(), diag::note_ivar_decl);
600       }
601     }
602 }
603 
604 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
605   // Handle any placeholder expressions which made it here.
606   if (E->getType()->isPlaceholderType()) {
607     ExprResult result = CheckPlaceholderExpr(E);
608     if (result.isInvalid()) return ExprError();
609     E = result.get();
610   }
611 
612   // C++ [conv.lval]p1:
613   //   A glvalue of a non-function, non-array type T can be
614   //   converted to a prvalue.
615   if (!E->isGLValue()) return E;
616 
617   QualType T = E->getType();
618   assert(!T.isNull() && "r-value conversion on typeless expression?");
619 
620   // lvalue-to-rvalue conversion cannot be applied to function or array types.
621   if (T->isFunctionType() || T->isArrayType())
622     return E;
623 
624   // We don't want to throw lvalue-to-rvalue casts on top of
625   // expressions of certain types in C++.
626   if (getLangOpts().CPlusPlus &&
627       (E->getType() == Context.OverloadTy ||
628        T->isDependentType() ||
629        T->isRecordType()))
630     return E;
631 
632   // The C standard is actually really unclear on this point, and
633   // DR106 tells us what the result should be but not why.  It's
634   // generally best to say that void types just doesn't undergo
635   // lvalue-to-rvalue at all.  Note that expressions of unqualified
636   // 'void' type are never l-values, but qualified void can be.
637   if (T->isVoidType())
638     return E;
639 
640   // OpenCL usually rejects direct accesses to values of 'half' type.
641   if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
642       T->isHalfType()) {
643     Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
644       << 0 << T;
645     return ExprError();
646   }
647 
648   CheckForNullPointerDereference(*this, E);
649   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
650     NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
651                                      &Context.Idents.get("object_getClass"),
652                                      SourceLocation(), LookupOrdinaryName);
653     if (ObjectGetClass)
654       Diag(E->getExprLoc(), diag::warn_objc_isa_use)
655           << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(")
656           << FixItHint::CreateReplacement(
657                  SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
658     else
659       Diag(E->getExprLoc(), diag::warn_objc_isa_use);
660   }
661   else if (const ObjCIvarRefExpr *OIRE =
662             dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
663     DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
664 
665   // C++ [conv.lval]p1:
666   //   [...] If T is a non-class type, the type of the prvalue is the
667   //   cv-unqualified version of T. Otherwise, the type of the
668   //   rvalue is T.
669   //
670   // C99 6.3.2.1p2:
671   //   If the lvalue has qualified type, the value has the unqualified
672   //   version of the type of the lvalue; otherwise, the value has the
673   //   type of the lvalue.
674   if (T.hasQualifiers())
675     T = T.getUnqualifiedType();
676 
677   // Under the MS ABI, lock down the inheritance model now.
678   if (T->isMemberPointerType() &&
679       Context.getTargetInfo().getCXXABI().isMicrosoft())
680     (void)isCompleteType(E->getExprLoc(), T);
681 
682   ExprResult Res = CheckLValueToRValueConversionOperand(E);
683   if (Res.isInvalid())
684     return Res;
685   E = Res.get();
686 
687   // Loading a __weak object implicitly retains the value, so we need a cleanup to
688   // balance that.
689   if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
690     Cleanup.setExprNeedsCleanups(true);
691 
692   if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
693     Cleanup.setExprNeedsCleanups(true);
694 
695   // C++ [conv.lval]p3:
696   //   If T is cv std::nullptr_t, the result is a null pointer constant.
697   CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue;
698   Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_RValue,
699                                  FPOptionsOverride());
700 
701   // C11 6.3.2.1p2:
702   //   ... if the lvalue has atomic type, the value has the non-atomic version
703   //   of the type of the lvalue ...
704   if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
705     T = Atomic->getValueType().getUnqualifiedType();
706     Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
707                                    nullptr, VK_RValue, FPOptionsOverride());
708   }
709 
710   return Res;
711 }
712 
713 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
714   ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
715   if (Res.isInvalid())
716     return ExprError();
717   Res = DefaultLvalueConversion(Res.get());
718   if (Res.isInvalid())
719     return ExprError();
720   return Res;
721 }
722 
723 /// CallExprUnaryConversions - a special case of an unary conversion
724 /// performed on a function designator of a call expression.
725 ExprResult Sema::CallExprUnaryConversions(Expr *E) {
726   QualType Ty = E->getType();
727   ExprResult Res = E;
728   // Only do implicit cast for a function type, but not for a pointer
729   // to function type.
730   if (Ty->isFunctionType()) {
731     Res = ImpCastExprToType(E, Context.getPointerType(Ty),
732                             CK_FunctionToPointerDecay);
733     if (Res.isInvalid())
734       return ExprError();
735   }
736   Res = DefaultLvalueConversion(Res.get());
737   if (Res.isInvalid())
738     return ExprError();
739   return Res.get();
740 }
741 
742 /// UsualUnaryConversions - Performs various conversions that are common to most
743 /// operators (C99 6.3). The conversions of array and function types are
744 /// sometimes suppressed. For example, the array->pointer conversion doesn't
745 /// apply if the array is an argument to the sizeof or address (&) operators.
746 /// In these instances, this routine should *not* be called.
747 ExprResult Sema::UsualUnaryConversions(Expr *E) {
748   // First, convert to an r-value.
749   ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
750   if (Res.isInvalid())
751     return ExprError();
752   E = Res.get();
753 
754   QualType Ty = E->getType();
755   assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
756 
757   // Half FP have to be promoted to float unless it is natively supported
758   if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
759     return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
760 
761   // Try to perform integral promotions if the object has a theoretically
762   // promotable type.
763   if (Ty->isIntegralOrUnscopedEnumerationType()) {
764     // C99 6.3.1.1p2:
765     //
766     //   The following may be used in an expression wherever an int or
767     //   unsigned int may be used:
768     //     - an object or expression with an integer type whose integer
769     //       conversion rank is less than or equal to the rank of int
770     //       and unsigned int.
771     //     - A bit-field of type _Bool, int, signed int, or unsigned int.
772     //
773     //   If an int can represent all values of the original type, the
774     //   value is converted to an int; otherwise, it is converted to an
775     //   unsigned int. These are called the integer promotions. All
776     //   other types are unchanged by the integer promotions.
777 
778     QualType PTy = Context.isPromotableBitField(E);
779     if (!PTy.isNull()) {
780       E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
781       return E;
782     }
783     if (Ty->isPromotableIntegerType()) {
784       QualType PT = Context.getPromotedIntegerType(Ty);
785       E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
786       return E;
787     }
788   }
789   return E;
790 }
791 
792 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
793 /// do not have a prototype. Arguments that have type float or __fp16
794 /// are promoted to double. All other argument types are converted by
795 /// UsualUnaryConversions().
796 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
797   QualType Ty = E->getType();
798   assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
799 
800   ExprResult Res = UsualUnaryConversions(E);
801   if (Res.isInvalid())
802     return ExprError();
803   E = Res.get();
804 
805   // If this is a 'float'  or '__fp16' (CVR qualified or typedef)
806   // promote to double.
807   // Note that default argument promotion applies only to float (and
808   // half/fp16); it does not apply to _Float16.
809   const BuiltinType *BTy = Ty->getAs<BuiltinType>();
810   if (BTy && (BTy->getKind() == BuiltinType::Half ||
811               BTy->getKind() == BuiltinType::Float)) {
812     if (getLangOpts().OpenCL &&
813         !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
814         if (BTy->getKind() == BuiltinType::Half) {
815             E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
816         }
817     } else {
818       E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
819     }
820   }
821 
822   // C++ performs lvalue-to-rvalue conversion as a default argument
823   // promotion, even on class types, but note:
824   //   C++11 [conv.lval]p2:
825   //     When an lvalue-to-rvalue conversion occurs in an unevaluated
826   //     operand or a subexpression thereof the value contained in the
827   //     referenced object is not accessed. Otherwise, if the glvalue
828   //     has a class type, the conversion copy-initializes a temporary
829   //     of type T from the glvalue and the result of the conversion
830   //     is a prvalue for the temporary.
831   // FIXME: add some way to gate this entire thing for correctness in
832   // potentially potentially evaluated contexts.
833   if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
834     ExprResult Temp = PerformCopyInitialization(
835                        InitializedEntity::InitializeTemporary(E->getType()),
836                                                 E->getExprLoc(), E);
837     if (Temp.isInvalid())
838       return ExprError();
839     E = Temp.get();
840   }
841 
842   return E;
843 }
844 
845 /// Determine the degree of POD-ness for an expression.
846 /// Incomplete types are considered POD, since this check can be performed
847 /// when we're in an unevaluated context.
848 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
849   if (Ty->isIncompleteType()) {
850     // C++11 [expr.call]p7:
851     //   After these conversions, if the argument does not have arithmetic,
852     //   enumeration, pointer, pointer to member, or class type, the program
853     //   is ill-formed.
854     //
855     // Since we've already performed array-to-pointer and function-to-pointer
856     // decay, the only such type in C++ is cv void. This also handles
857     // initializer lists as variadic arguments.
858     if (Ty->isVoidType())
859       return VAK_Invalid;
860 
861     if (Ty->isObjCObjectType())
862       return VAK_Invalid;
863     return VAK_Valid;
864   }
865 
866   if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
867     return VAK_Invalid;
868 
869   if (Ty.isCXX98PODType(Context))
870     return VAK_Valid;
871 
872   // C++11 [expr.call]p7:
873   //   Passing a potentially-evaluated argument of class type (Clause 9)
874   //   having a non-trivial copy constructor, a non-trivial move constructor,
875   //   or a non-trivial destructor, with no corresponding parameter,
876   //   is conditionally-supported with implementation-defined semantics.
877   if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
878     if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
879       if (!Record->hasNonTrivialCopyConstructor() &&
880           !Record->hasNonTrivialMoveConstructor() &&
881           !Record->hasNonTrivialDestructor())
882         return VAK_ValidInCXX11;
883 
884   if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
885     return VAK_Valid;
886 
887   if (Ty->isObjCObjectType())
888     return VAK_Invalid;
889 
890   if (getLangOpts().MSVCCompat)
891     return VAK_MSVCUndefined;
892 
893   // FIXME: In C++11, these cases are conditionally-supported, meaning we're
894   // permitted to reject them. We should consider doing so.
895   return VAK_Undefined;
896 }
897 
898 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
899   // Don't allow one to pass an Objective-C interface to a vararg.
900   const QualType &Ty = E->getType();
901   VarArgKind VAK = isValidVarArgType(Ty);
902 
903   // Complain about passing non-POD types through varargs.
904   switch (VAK) {
905   case VAK_ValidInCXX11:
906     DiagRuntimeBehavior(
907         E->getBeginLoc(), nullptr,
908         PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT);
909     LLVM_FALLTHROUGH;
910   case VAK_Valid:
911     if (Ty->isRecordType()) {
912       // This is unlikely to be what the user intended. If the class has a
913       // 'c_str' member function, the user probably meant to call that.
914       DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
915                           PDiag(diag::warn_pass_class_arg_to_vararg)
916                               << Ty << CT << hasCStrMethod(E) << ".c_str()");
917     }
918     break;
919 
920   case VAK_Undefined:
921   case VAK_MSVCUndefined:
922     DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
923                         PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
924                             << getLangOpts().CPlusPlus11 << Ty << CT);
925     break;
926 
927   case VAK_Invalid:
928     if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
929       Diag(E->getBeginLoc(),
930            diag::err_cannot_pass_non_trivial_c_struct_to_vararg)
931           << Ty << CT;
932     else if (Ty->isObjCObjectType())
933       DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
934                           PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
935                               << Ty << CT);
936     else
937       Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg)
938           << isa<InitListExpr>(E) << Ty << CT;
939     break;
940   }
941 }
942 
943 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
944 /// will create a trap if the resulting type is not a POD type.
945 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
946                                                   FunctionDecl *FDecl) {
947   if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
948     // Strip the unbridged-cast placeholder expression off, if applicable.
949     if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
950         (CT == VariadicMethod ||
951          (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
952       E = stripARCUnbridgedCast(E);
953 
954     // Otherwise, do normal placeholder checking.
955     } else {
956       ExprResult ExprRes = CheckPlaceholderExpr(E);
957       if (ExprRes.isInvalid())
958         return ExprError();
959       E = ExprRes.get();
960     }
961   }
962 
963   ExprResult ExprRes = DefaultArgumentPromotion(E);
964   if (ExprRes.isInvalid())
965     return ExprError();
966 
967   // Copy blocks to the heap.
968   if (ExprRes.get()->getType()->isBlockPointerType())
969     maybeExtendBlockObject(ExprRes);
970 
971   E = ExprRes.get();
972 
973   // Diagnostics regarding non-POD argument types are
974   // emitted along with format string checking in Sema::CheckFunctionCall().
975   if (isValidVarArgType(E->getType()) == VAK_Undefined) {
976     // Turn this into a trap.
977     CXXScopeSpec SS;
978     SourceLocation TemplateKWLoc;
979     UnqualifiedId Name;
980     Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
981                        E->getBeginLoc());
982     ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name,
983                                           /*HasTrailingLParen=*/true,
984                                           /*IsAddressOfOperand=*/false);
985     if (TrapFn.isInvalid())
986       return ExprError();
987 
988     ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(),
989                                     None, E->getEndLoc());
990     if (Call.isInvalid())
991       return ExprError();
992 
993     ExprResult Comma =
994         ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E);
995     if (Comma.isInvalid())
996       return ExprError();
997     return Comma.get();
998   }
999 
1000   if (!getLangOpts().CPlusPlus &&
1001       RequireCompleteType(E->getExprLoc(), E->getType(),
1002                           diag::err_call_incomplete_argument))
1003     return ExprError();
1004 
1005   return E;
1006 }
1007 
1008 /// Converts an integer to complex float type.  Helper function of
1009 /// UsualArithmeticConversions()
1010 ///
1011 /// \return false if the integer expression is an integer type and is
1012 /// successfully converted to the complex type.
1013 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
1014                                                   ExprResult &ComplexExpr,
1015                                                   QualType IntTy,
1016                                                   QualType ComplexTy,
1017                                                   bool SkipCast) {
1018   if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
1019   if (SkipCast) return false;
1020   if (IntTy->isIntegerType()) {
1021     QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
1022     IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
1023     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1024                                   CK_FloatingRealToComplex);
1025   } else {
1026     assert(IntTy->isComplexIntegerType());
1027     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1028                                   CK_IntegralComplexToFloatingComplex);
1029   }
1030   return false;
1031 }
1032 
1033 /// Handle arithmetic conversion with complex types.  Helper function of
1034 /// UsualArithmeticConversions()
1035 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
1036                                              ExprResult &RHS, QualType LHSType,
1037                                              QualType RHSType,
1038                                              bool IsCompAssign) {
1039   // if we have an integer operand, the result is the complex type.
1040   if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
1041                                              /*skipCast*/false))
1042     return LHSType;
1043   if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
1044                                              /*skipCast*/IsCompAssign))
1045     return RHSType;
1046 
1047   // This handles complex/complex, complex/float, or float/complex.
1048   // When both operands are complex, the shorter operand is converted to the
1049   // type of the longer, and that is the type of the result. This corresponds
1050   // to what is done when combining two real floating-point operands.
1051   // The fun begins when size promotion occur across type domains.
1052   // From H&S 6.3.4: When one operand is complex and the other is a real
1053   // floating-point type, the less precise type is converted, within it's
1054   // real or complex domain, to the precision of the other type. For example,
1055   // when combining a "long double" with a "double _Complex", the
1056   // "double _Complex" is promoted to "long double _Complex".
1057 
1058   // Compute the rank of the two types, regardless of whether they are complex.
1059   int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1060 
1061   auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
1062   auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
1063   QualType LHSElementType =
1064       LHSComplexType ? LHSComplexType->getElementType() : LHSType;
1065   QualType RHSElementType =
1066       RHSComplexType ? RHSComplexType->getElementType() : RHSType;
1067 
1068   QualType ResultType = S.Context.getComplexType(LHSElementType);
1069   if (Order < 0) {
1070     // Promote the precision of the LHS if not an assignment.
1071     ResultType = S.Context.getComplexType(RHSElementType);
1072     if (!IsCompAssign) {
1073       if (LHSComplexType)
1074         LHS =
1075             S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
1076       else
1077         LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
1078     }
1079   } else if (Order > 0) {
1080     // Promote the precision of the RHS.
1081     if (RHSComplexType)
1082       RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
1083     else
1084       RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
1085   }
1086   return ResultType;
1087 }
1088 
1089 /// Handle arithmetic conversion from integer to float.  Helper function
1090 /// of UsualArithmeticConversions()
1091 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1092                                            ExprResult &IntExpr,
1093                                            QualType FloatTy, QualType IntTy,
1094                                            bool ConvertFloat, bool ConvertInt) {
1095   if (IntTy->isIntegerType()) {
1096     if (ConvertInt)
1097       // Convert intExpr to the lhs floating point type.
1098       IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1099                                     CK_IntegralToFloating);
1100     return FloatTy;
1101   }
1102 
1103   // Convert both sides to the appropriate complex float.
1104   assert(IntTy->isComplexIntegerType());
1105   QualType result = S.Context.getComplexType(FloatTy);
1106 
1107   // _Complex int -> _Complex float
1108   if (ConvertInt)
1109     IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1110                                   CK_IntegralComplexToFloatingComplex);
1111 
1112   // float -> _Complex float
1113   if (ConvertFloat)
1114     FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1115                                     CK_FloatingRealToComplex);
1116 
1117   return result;
1118 }
1119 
1120 /// Handle arithmethic conversion with floating point types.  Helper
1121 /// function of UsualArithmeticConversions()
1122 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1123                                       ExprResult &RHS, QualType LHSType,
1124                                       QualType RHSType, bool IsCompAssign) {
1125   bool LHSFloat = LHSType->isRealFloatingType();
1126   bool RHSFloat = RHSType->isRealFloatingType();
1127 
1128   // FIXME: Implement floating to fixed point conversion.(Bug 46268)
1129   // Reference N1169 4.1.4 (Type conversion, usual arithmetic conversions).
1130   if ((LHSType->isFixedPointType() && RHSFloat) ||
1131       (LHSFloat && RHSType->isFixedPointType()))
1132     return QualType();
1133   // If we have two real floating types, convert the smaller operand
1134   // to the bigger result.
1135   if (LHSFloat && RHSFloat) {
1136     int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1137     if (order > 0) {
1138       RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1139       return LHSType;
1140     }
1141 
1142     assert(order < 0 && "illegal float comparison");
1143     if (!IsCompAssign)
1144       LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1145     return RHSType;
1146   }
1147 
1148   if (LHSFloat) {
1149     // Half FP has to be promoted to float unless it is natively supported
1150     if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1151       LHSType = S.Context.FloatTy;
1152 
1153     return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1154                                       /*ConvertFloat=*/!IsCompAssign,
1155                                       /*ConvertInt=*/ true);
1156   }
1157   assert(RHSFloat);
1158   return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1159                                     /*ConvertFloat=*/ true,
1160                                     /*ConvertInt=*/!IsCompAssign);
1161 }
1162 
1163 /// Diagnose attempts to convert between __float128 and long double if
1164 /// there is no support for such conversion. Helper function of
1165 /// UsualArithmeticConversions().
1166 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1167                                       QualType RHSType) {
1168   /*  No issue converting if at least one of the types is not a floating point
1169       type or the two types have the same rank.
1170   */
1171   if (!LHSType->isFloatingType() || !RHSType->isFloatingType() ||
1172       S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0)
1173     return false;
1174 
1175   assert(LHSType->isFloatingType() && RHSType->isFloatingType() &&
1176          "The remaining types must be floating point types.");
1177 
1178   auto *LHSComplex = LHSType->getAs<ComplexType>();
1179   auto *RHSComplex = RHSType->getAs<ComplexType>();
1180 
1181   QualType LHSElemType = LHSComplex ?
1182     LHSComplex->getElementType() : LHSType;
1183   QualType RHSElemType = RHSComplex ?
1184     RHSComplex->getElementType() : RHSType;
1185 
1186   // No issue if the two types have the same representation
1187   if (&S.Context.getFloatTypeSemantics(LHSElemType) ==
1188       &S.Context.getFloatTypeSemantics(RHSElemType))
1189     return false;
1190 
1191   bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty &&
1192                                 RHSElemType == S.Context.LongDoubleTy);
1193   Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy &&
1194                             RHSElemType == S.Context.Float128Ty);
1195 
1196   // We've handled the situation where __float128 and long double have the same
1197   // representation. We allow all conversions for all possible long double types
1198   // except PPC's double double.
1199   return Float128AndLongDouble &&
1200     (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) ==
1201      &llvm::APFloat::PPCDoubleDouble());
1202 }
1203 
1204 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1205 
1206 namespace {
1207 /// These helper callbacks are placed in an anonymous namespace to
1208 /// permit their use as function template parameters.
1209 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1210   return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1211 }
1212 
1213 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1214   return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1215                              CK_IntegralComplexCast);
1216 }
1217 }
1218 
1219 /// Handle integer arithmetic conversions.  Helper function of
1220 /// UsualArithmeticConversions()
1221 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1222 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1223                                         ExprResult &RHS, QualType LHSType,
1224                                         QualType RHSType, bool IsCompAssign) {
1225   // The rules for this case are in C99 6.3.1.8
1226   int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1227   bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1228   bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1229   if (LHSSigned == RHSSigned) {
1230     // Same signedness; use the higher-ranked type
1231     if (order >= 0) {
1232       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1233       return LHSType;
1234     } else if (!IsCompAssign)
1235       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1236     return RHSType;
1237   } else if (order != (LHSSigned ? 1 : -1)) {
1238     // The unsigned type has greater than or equal rank to the
1239     // signed type, so use the unsigned type
1240     if (RHSSigned) {
1241       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1242       return LHSType;
1243     } else if (!IsCompAssign)
1244       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1245     return RHSType;
1246   } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1247     // The two types are different widths; if we are here, that
1248     // means the signed type is larger than the unsigned type, so
1249     // use the signed type.
1250     if (LHSSigned) {
1251       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1252       return LHSType;
1253     } else if (!IsCompAssign)
1254       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1255     return RHSType;
1256   } else {
1257     // The signed type is higher-ranked than the unsigned type,
1258     // but isn't actually any bigger (like unsigned int and long
1259     // on most 32-bit systems).  Use the unsigned type corresponding
1260     // to the signed type.
1261     QualType result =
1262       S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1263     RHS = (*doRHSCast)(S, RHS.get(), result);
1264     if (!IsCompAssign)
1265       LHS = (*doLHSCast)(S, LHS.get(), result);
1266     return result;
1267   }
1268 }
1269 
1270 /// Handle conversions with GCC complex int extension.  Helper function
1271 /// of UsualArithmeticConversions()
1272 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1273                                            ExprResult &RHS, QualType LHSType,
1274                                            QualType RHSType,
1275                                            bool IsCompAssign) {
1276   const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1277   const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1278 
1279   if (LHSComplexInt && RHSComplexInt) {
1280     QualType LHSEltType = LHSComplexInt->getElementType();
1281     QualType RHSEltType = RHSComplexInt->getElementType();
1282     QualType ScalarType =
1283       handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1284         (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1285 
1286     return S.Context.getComplexType(ScalarType);
1287   }
1288 
1289   if (LHSComplexInt) {
1290     QualType LHSEltType = LHSComplexInt->getElementType();
1291     QualType ScalarType =
1292       handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1293         (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1294     QualType ComplexType = S.Context.getComplexType(ScalarType);
1295     RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1296                               CK_IntegralRealToComplex);
1297 
1298     return ComplexType;
1299   }
1300 
1301   assert(RHSComplexInt);
1302 
1303   QualType RHSEltType = RHSComplexInt->getElementType();
1304   QualType ScalarType =
1305     handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1306       (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1307   QualType ComplexType = S.Context.getComplexType(ScalarType);
1308 
1309   if (!IsCompAssign)
1310     LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1311                               CK_IntegralRealToComplex);
1312   return ComplexType;
1313 }
1314 
1315 /// Return the rank of a given fixed point or integer type. The value itself
1316 /// doesn't matter, but the values must be increasing with proper increasing
1317 /// rank as described in N1169 4.1.1.
1318 static unsigned GetFixedPointRank(QualType Ty) {
1319   const auto *BTy = Ty->getAs<BuiltinType>();
1320   assert(BTy && "Expected a builtin type.");
1321 
1322   switch (BTy->getKind()) {
1323   case BuiltinType::ShortFract:
1324   case BuiltinType::UShortFract:
1325   case BuiltinType::SatShortFract:
1326   case BuiltinType::SatUShortFract:
1327     return 1;
1328   case BuiltinType::Fract:
1329   case BuiltinType::UFract:
1330   case BuiltinType::SatFract:
1331   case BuiltinType::SatUFract:
1332     return 2;
1333   case BuiltinType::LongFract:
1334   case BuiltinType::ULongFract:
1335   case BuiltinType::SatLongFract:
1336   case BuiltinType::SatULongFract:
1337     return 3;
1338   case BuiltinType::ShortAccum:
1339   case BuiltinType::UShortAccum:
1340   case BuiltinType::SatShortAccum:
1341   case BuiltinType::SatUShortAccum:
1342     return 4;
1343   case BuiltinType::Accum:
1344   case BuiltinType::UAccum:
1345   case BuiltinType::SatAccum:
1346   case BuiltinType::SatUAccum:
1347     return 5;
1348   case BuiltinType::LongAccum:
1349   case BuiltinType::ULongAccum:
1350   case BuiltinType::SatLongAccum:
1351   case BuiltinType::SatULongAccum:
1352     return 6;
1353   default:
1354     if (BTy->isInteger())
1355       return 0;
1356     llvm_unreachable("Unexpected fixed point or integer type");
1357   }
1358 }
1359 
1360 /// handleFixedPointConversion - Fixed point operations between fixed
1361 /// point types and integers or other fixed point types do not fall under
1362 /// usual arithmetic conversion since these conversions could result in loss
1363 /// of precsision (N1169 4.1.4). These operations should be calculated with
1364 /// the full precision of their result type (N1169 4.1.6.2.1).
1365 static QualType handleFixedPointConversion(Sema &S, QualType LHSTy,
1366                                            QualType RHSTy) {
1367   assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) &&
1368          "Expected at least one of the operands to be a fixed point type");
1369   assert((LHSTy->isFixedPointOrIntegerType() ||
1370           RHSTy->isFixedPointOrIntegerType()) &&
1371          "Special fixed point arithmetic operation conversions are only "
1372          "applied to ints or other fixed point types");
1373 
1374   // If one operand has signed fixed-point type and the other operand has
1375   // unsigned fixed-point type, then the unsigned fixed-point operand is
1376   // converted to its corresponding signed fixed-point type and the resulting
1377   // type is the type of the converted operand.
1378   if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType())
1379     LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy);
1380   else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType())
1381     RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy);
1382 
1383   // The result type is the type with the highest rank, whereby a fixed-point
1384   // conversion rank is always greater than an integer conversion rank; if the
1385   // type of either of the operands is a saturating fixedpoint type, the result
1386   // type shall be the saturating fixed-point type corresponding to the type
1387   // with the highest rank; the resulting value is converted (taking into
1388   // account rounding and overflow) to the precision of the resulting type.
1389   // Same ranks between signed and unsigned types are resolved earlier, so both
1390   // types are either signed or both unsigned at this point.
1391   unsigned LHSTyRank = GetFixedPointRank(LHSTy);
1392   unsigned RHSTyRank = GetFixedPointRank(RHSTy);
1393 
1394   QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy;
1395 
1396   if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType())
1397     ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy);
1398 
1399   return ResultTy;
1400 }
1401 
1402 /// Check that the usual arithmetic conversions can be performed on this pair of
1403 /// expressions that might be of enumeration type.
1404 static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS,
1405                                            SourceLocation Loc,
1406                                            Sema::ArithConvKind ACK) {
1407   // C++2a [expr.arith.conv]p1:
1408   //   If one operand is of enumeration type and the other operand is of a
1409   //   different enumeration type or a floating-point type, this behavior is
1410   //   deprecated ([depr.arith.conv.enum]).
1411   //
1412   // Warn on this in all language modes. Produce a deprecation warning in C++20.
1413   // Eventually we will presumably reject these cases (in C++23 onwards?).
1414   QualType L = LHS->getType(), R = RHS->getType();
1415   bool LEnum = L->isUnscopedEnumerationType(),
1416        REnum = R->isUnscopedEnumerationType();
1417   bool IsCompAssign = ACK == Sema::ACK_CompAssign;
1418   if ((!IsCompAssign && LEnum && R->isFloatingType()) ||
1419       (REnum && L->isFloatingType())) {
1420     S.Diag(Loc, S.getLangOpts().CPlusPlus20
1421                     ? diag::warn_arith_conv_enum_float_cxx20
1422                     : diag::warn_arith_conv_enum_float)
1423         << LHS->getSourceRange() << RHS->getSourceRange()
1424         << (int)ACK << LEnum << L << R;
1425   } else if (!IsCompAssign && LEnum && REnum &&
1426              !S.Context.hasSameUnqualifiedType(L, R)) {
1427     unsigned DiagID;
1428     if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() ||
1429         !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) {
1430       // If either enumeration type is unnamed, it's less likely that the
1431       // user cares about this, but this situation is still deprecated in
1432       // C++2a. Use a different warning group.
1433       DiagID = S.getLangOpts().CPlusPlus20
1434                     ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20
1435                     : diag::warn_arith_conv_mixed_anon_enum_types;
1436     } else if (ACK == Sema::ACK_Conditional) {
1437       // Conditional expressions are separated out because they have
1438       // historically had a different warning flag.
1439       DiagID = S.getLangOpts().CPlusPlus20
1440                    ? diag::warn_conditional_mixed_enum_types_cxx20
1441                    : diag::warn_conditional_mixed_enum_types;
1442     } else if (ACK == Sema::ACK_Comparison) {
1443       // Comparison expressions are separated out because they have
1444       // historically had a different warning flag.
1445       DiagID = S.getLangOpts().CPlusPlus20
1446                    ? diag::warn_comparison_mixed_enum_types_cxx20
1447                    : diag::warn_comparison_mixed_enum_types;
1448     } else {
1449       DiagID = S.getLangOpts().CPlusPlus20
1450                    ? diag::warn_arith_conv_mixed_enum_types_cxx20
1451                    : diag::warn_arith_conv_mixed_enum_types;
1452     }
1453     S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
1454                         << (int)ACK << L << R;
1455   }
1456 }
1457 
1458 /// UsualArithmeticConversions - Performs various conversions that are common to
1459 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1460 /// routine returns the first non-arithmetic type found. The client is
1461 /// responsible for emitting appropriate error diagnostics.
1462 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1463                                           SourceLocation Loc,
1464                                           ArithConvKind ACK) {
1465   checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK);
1466 
1467   if (ACK != ACK_CompAssign) {
1468     LHS = UsualUnaryConversions(LHS.get());
1469     if (LHS.isInvalid())
1470       return QualType();
1471   }
1472 
1473   RHS = UsualUnaryConversions(RHS.get());
1474   if (RHS.isInvalid())
1475     return QualType();
1476 
1477   // For conversion purposes, we ignore any qualifiers.
1478   // For example, "const float" and "float" are equivalent.
1479   QualType LHSType =
1480     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1481   QualType RHSType =
1482     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1483 
1484   // For conversion purposes, we ignore any atomic qualifier on the LHS.
1485   if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1486     LHSType = AtomicLHS->getValueType();
1487 
1488   // If both types are identical, no conversion is needed.
1489   if (LHSType == RHSType)
1490     return LHSType;
1491 
1492   // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1493   // The caller can deal with this (e.g. pointer + int).
1494   if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1495     return QualType();
1496 
1497   // Apply unary and bitfield promotions to the LHS's type.
1498   QualType LHSUnpromotedType = LHSType;
1499   if (LHSType->isPromotableIntegerType())
1500     LHSType = Context.getPromotedIntegerType(LHSType);
1501   QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1502   if (!LHSBitfieldPromoteTy.isNull())
1503     LHSType = LHSBitfieldPromoteTy;
1504   if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign)
1505     LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1506 
1507   // If both types are identical, no conversion is needed.
1508   if (LHSType == RHSType)
1509     return LHSType;
1510 
1511   // ExtInt types aren't subject to conversions between them or normal integers,
1512   // so this fails.
1513   if(LHSType->isExtIntType() || RHSType->isExtIntType())
1514     return QualType();
1515 
1516   // At this point, we have two different arithmetic types.
1517 
1518   // Diagnose attempts to convert between __float128 and long double where
1519   // such conversions currently can't be handled.
1520   if (unsupportedTypeConversion(*this, LHSType, RHSType))
1521     return QualType();
1522 
1523   // Handle complex types first (C99 6.3.1.8p1).
1524   if (LHSType->isComplexType() || RHSType->isComplexType())
1525     return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1526                                         ACK == ACK_CompAssign);
1527 
1528   // Now handle "real" floating types (i.e. float, double, long double).
1529   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1530     return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1531                                  ACK == ACK_CompAssign);
1532 
1533   // Handle GCC complex int extension.
1534   if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1535     return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1536                                       ACK == ACK_CompAssign);
1537 
1538   if (LHSType->isFixedPointType() || RHSType->isFixedPointType())
1539     return handleFixedPointConversion(*this, LHSType, RHSType);
1540 
1541   // Finally, we have two differing integer types.
1542   return handleIntegerConversion<doIntegralCast, doIntegralCast>
1543            (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign);
1544 }
1545 
1546 //===----------------------------------------------------------------------===//
1547 //  Semantic Analysis for various Expression Types
1548 //===----------------------------------------------------------------------===//
1549 
1550 
1551 ExprResult
1552 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1553                                 SourceLocation DefaultLoc,
1554                                 SourceLocation RParenLoc,
1555                                 Expr *ControllingExpr,
1556                                 ArrayRef<ParsedType> ArgTypes,
1557                                 ArrayRef<Expr *> ArgExprs) {
1558   unsigned NumAssocs = ArgTypes.size();
1559   assert(NumAssocs == ArgExprs.size());
1560 
1561   TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1562   for (unsigned i = 0; i < NumAssocs; ++i) {
1563     if (ArgTypes[i])
1564       (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1565     else
1566       Types[i] = nullptr;
1567   }
1568 
1569   ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1570                                              ControllingExpr,
1571                                              llvm::makeArrayRef(Types, NumAssocs),
1572                                              ArgExprs);
1573   delete [] Types;
1574   return ER;
1575 }
1576 
1577 ExprResult
1578 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1579                                  SourceLocation DefaultLoc,
1580                                  SourceLocation RParenLoc,
1581                                  Expr *ControllingExpr,
1582                                  ArrayRef<TypeSourceInfo *> Types,
1583                                  ArrayRef<Expr *> Exprs) {
1584   unsigned NumAssocs = Types.size();
1585   assert(NumAssocs == Exprs.size());
1586 
1587   // Decay and strip qualifiers for the controlling expression type, and handle
1588   // placeholder type replacement. See committee discussion from WG14 DR423.
1589   {
1590     EnterExpressionEvaluationContext Unevaluated(
1591         *this, Sema::ExpressionEvaluationContext::Unevaluated);
1592     ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
1593     if (R.isInvalid())
1594       return ExprError();
1595     ControllingExpr = R.get();
1596   }
1597 
1598   // The controlling expression is an unevaluated operand, so side effects are
1599   // likely unintended.
1600   if (!inTemplateInstantiation() &&
1601       ControllingExpr->HasSideEffects(Context, false))
1602     Diag(ControllingExpr->getExprLoc(),
1603          diag::warn_side_effects_unevaluated_context);
1604 
1605   bool TypeErrorFound = false,
1606        IsResultDependent = ControllingExpr->isTypeDependent(),
1607        ContainsUnexpandedParameterPack
1608          = ControllingExpr->containsUnexpandedParameterPack();
1609 
1610   for (unsigned i = 0; i < NumAssocs; ++i) {
1611     if (Exprs[i]->containsUnexpandedParameterPack())
1612       ContainsUnexpandedParameterPack = true;
1613 
1614     if (Types[i]) {
1615       if (Types[i]->getType()->containsUnexpandedParameterPack())
1616         ContainsUnexpandedParameterPack = true;
1617 
1618       if (Types[i]->getType()->isDependentType()) {
1619         IsResultDependent = true;
1620       } else {
1621         // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1622         // complete object type other than a variably modified type."
1623         unsigned D = 0;
1624         if (Types[i]->getType()->isIncompleteType())
1625           D = diag::err_assoc_type_incomplete;
1626         else if (!Types[i]->getType()->isObjectType())
1627           D = diag::err_assoc_type_nonobject;
1628         else if (Types[i]->getType()->isVariablyModifiedType())
1629           D = diag::err_assoc_type_variably_modified;
1630 
1631         if (D != 0) {
1632           Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1633             << Types[i]->getTypeLoc().getSourceRange()
1634             << Types[i]->getType();
1635           TypeErrorFound = true;
1636         }
1637 
1638         // C11 6.5.1.1p2 "No two generic associations in the same generic
1639         // selection shall specify compatible types."
1640         for (unsigned j = i+1; j < NumAssocs; ++j)
1641           if (Types[j] && !Types[j]->getType()->isDependentType() &&
1642               Context.typesAreCompatible(Types[i]->getType(),
1643                                          Types[j]->getType())) {
1644             Diag(Types[j]->getTypeLoc().getBeginLoc(),
1645                  diag::err_assoc_compatible_types)
1646               << Types[j]->getTypeLoc().getSourceRange()
1647               << Types[j]->getType()
1648               << Types[i]->getType();
1649             Diag(Types[i]->getTypeLoc().getBeginLoc(),
1650                  diag::note_compat_assoc)
1651               << Types[i]->getTypeLoc().getSourceRange()
1652               << Types[i]->getType();
1653             TypeErrorFound = true;
1654           }
1655       }
1656     }
1657   }
1658   if (TypeErrorFound)
1659     return ExprError();
1660 
1661   // If we determined that the generic selection is result-dependent, don't
1662   // try to compute the result expression.
1663   if (IsResultDependent)
1664     return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types,
1665                                         Exprs, DefaultLoc, RParenLoc,
1666                                         ContainsUnexpandedParameterPack);
1667 
1668   SmallVector<unsigned, 1> CompatIndices;
1669   unsigned DefaultIndex = -1U;
1670   for (unsigned i = 0; i < NumAssocs; ++i) {
1671     if (!Types[i])
1672       DefaultIndex = i;
1673     else if (Context.typesAreCompatible(ControllingExpr->getType(),
1674                                         Types[i]->getType()))
1675       CompatIndices.push_back(i);
1676   }
1677 
1678   // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1679   // type compatible with at most one of the types named in its generic
1680   // association list."
1681   if (CompatIndices.size() > 1) {
1682     // We strip parens here because the controlling expression is typically
1683     // parenthesized in macro definitions.
1684     ControllingExpr = ControllingExpr->IgnoreParens();
1685     Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match)
1686         << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1687         << (unsigned)CompatIndices.size();
1688     for (unsigned I : CompatIndices) {
1689       Diag(Types[I]->getTypeLoc().getBeginLoc(),
1690            diag::note_compat_assoc)
1691         << Types[I]->getTypeLoc().getSourceRange()
1692         << Types[I]->getType();
1693     }
1694     return ExprError();
1695   }
1696 
1697   // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1698   // its controlling expression shall have type compatible with exactly one of
1699   // the types named in its generic association list."
1700   if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1701     // We strip parens here because the controlling expression is typically
1702     // parenthesized in macro definitions.
1703     ControllingExpr = ControllingExpr->IgnoreParens();
1704     Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match)
1705         << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1706     return ExprError();
1707   }
1708 
1709   // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1710   // type name that is compatible with the type of the controlling expression,
1711   // then the result expression of the generic selection is the expression
1712   // in that generic association. Otherwise, the result expression of the
1713   // generic selection is the expression in the default generic association."
1714   unsigned ResultIndex =
1715     CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1716 
1717   return GenericSelectionExpr::Create(
1718       Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1719       ContainsUnexpandedParameterPack, ResultIndex);
1720 }
1721 
1722 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1723 /// location of the token and the offset of the ud-suffix within it.
1724 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1725                                      unsigned Offset) {
1726   return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1727                                         S.getLangOpts());
1728 }
1729 
1730 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1731 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
1732 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1733                                                  IdentifierInfo *UDSuffix,
1734                                                  SourceLocation UDSuffixLoc,
1735                                                  ArrayRef<Expr*> Args,
1736                                                  SourceLocation LitEndLoc) {
1737   assert(Args.size() <= 2 && "too many arguments for literal operator");
1738 
1739   QualType ArgTy[2];
1740   for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1741     ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1742     if (ArgTy[ArgIdx]->isArrayType())
1743       ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1744   }
1745 
1746   DeclarationName OpName =
1747     S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1748   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1749   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1750 
1751   LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1752   if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1753                               /*AllowRaw*/ false, /*AllowTemplate*/ false,
1754                               /*AllowStringTemplate*/ false,
1755                               /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
1756     return ExprError();
1757 
1758   return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1759 }
1760 
1761 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1762 /// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
1763 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1764 /// multiple tokens.  However, the common case is that StringToks points to one
1765 /// string.
1766 ///
1767 ExprResult
1768 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
1769   assert(!StringToks.empty() && "Must have at least one string!");
1770 
1771   StringLiteralParser Literal(StringToks, PP);
1772   if (Literal.hadError)
1773     return ExprError();
1774 
1775   SmallVector<SourceLocation, 4> StringTokLocs;
1776   for (const Token &Tok : StringToks)
1777     StringTokLocs.push_back(Tok.getLocation());
1778 
1779   QualType CharTy = Context.CharTy;
1780   StringLiteral::StringKind Kind = StringLiteral::Ascii;
1781   if (Literal.isWide()) {
1782     CharTy = Context.getWideCharType();
1783     Kind = StringLiteral::Wide;
1784   } else if (Literal.isUTF8()) {
1785     if (getLangOpts().Char8)
1786       CharTy = Context.Char8Ty;
1787     Kind = StringLiteral::UTF8;
1788   } else if (Literal.isUTF16()) {
1789     CharTy = Context.Char16Ty;
1790     Kind = StringLiteral::UTF16;
1791   } else if (Literal.isUTF32()) {
1792     CharTy = Context.Char32Ty;
1793     Kind = StringLiteral::UTF32;
1794   } else if (Literal.isPascal()) {
1795     CharTy = Context.UnsignedCharTy;
1796   }
1797 
1798   // Warn on initializing an array of char from a u8 string literal; this
1799   // becomes ill-formed in C++2a.
1800   if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus20 &&
1801       !getLangOpts().Char8 && Kind == StringLiteral::UTF8) {
1802     Diag(StringTokLocs.front(), diag::warn_cxx20_compat_utf8_string);
1803 
1804     // Create removals for all 'u8' prefixes in the string literal(s). This
1805     // ensures C++2a compatibility (but may change the program behavior when
1806     // built by non-Clang compilers for which the execution character set is
1807     // not always UTF-8).
1808     auto RemovalDiag = PDiag(diag::note_cxx20_compat_utf8_string_remove_u8);
1809     SourceLocation RemovalDiagLoc;
1810     for (const Token &Tok : StringToks) {
1811       if (Tok.getKind() == tok::utf8_string_literal) {
1812         if (RemovalDiagLoc.isInvalid())
1813           RemovalDiagLoc = Tok.getLocation();
1814         RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange(
1815             Tok.getLocation(),
1816             Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2,
1817                                            getSourceManager(), getLangOpts())));
1818       }
1819     }
1820     Diag(RemovalDiagLoc, RemovalDiag);
1821   }
1822 
1823   QualType StrTy =
1824       Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars());
1825 
1826   // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1827   StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1828                                              Kind, Literal.Pascal, StrTy,
1829                                              &StringTokLocs[0],
1830                                              StringTokLocs.size());
1831   if (Literal.getUDSuffix().empty())
1832     return Lit;
1833 
1834   // We're building a user-defined literal.
1835   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1836   SourceLocation UDSuffixLoc =
1837     getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1838                    Literal.getUDSuffixOffset());
1839 
1840   // Make sure we're allowed user-defined literals here.
1841   if (!UDLScope)
1842     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1843 
1844   // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1845   //   operator "" X (str, len)
1846   QualType SizeType = Context.getSizeType();
1847 
1848   DeclarationName OpName =
1849     Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1850   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1851   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1852 
1853   QualType ArgTy[] = {
1854     Context.getArrayDecayedType(StrTy), SizeType
1855   };
1856 
1857   LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1858   switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1859                                 /*AllowRaw*/ false, /*AllowTemplate*/ false,
1860                                 /*AllowStringTemplate*/ true,
1861                                 /*DiagnoseMissing*/ true)) {
1862 
1863   case LOLR_Cooked: {
1864     llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1865     IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1866                                                     StringTokLocs[0]);
1867     Expr *Args[] = { Lit, LenArg };
1868 
1869     return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1870   }
1871 
1872   case LOLR_StringTemplate: {
1873     TemplateArgumentListInfo ExplicitArgs;
1874 
1875     unsigned CharBits = Context.getIntWidth(CharTy);
1876     bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1877     llvm::APSInt Value(CharBits, CharIsUnsigned);
1878 
1879     TemplateArgument TypeArg(CharTy);
1880     TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1881     ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1882 
1883     for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1884       Value = Lit->getCodeUnit(I);
1885       TemplateArgument Arg(Context, Value, CharTy);
1886       TemplateArgumentLocInfo ArgInfo;
1887       ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1888     }
1889     return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1890                                     &ExplicitArgs);
1891   }
1892   case LOLR_Raw:
1893   case LOLR_Template:
1894   case LOLR_ErrorNoDiagnostic:
1895     llvm_unreachable("unexpected literal operator lookup result");
1896   case LOLR_Error:
1897     return ExprError();
1898   }
1899   llvm_unreachable("unexpected literal operator lookup result");
1900 }
1901 
1902 DeclRefExpr *
1903 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1904                        SourceLocation Loc,
1905                        const CXXScopeSpec *SS) {
1906   DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1907   return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1908 }
1909 
1910 DeclRefExpr *
1911 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1912                        const DeclarationNameInfo &NameInfo,
1913                        const CXXScopeSpec *SS, NamedDecl *FoundD,
1914                        SourceLocation TemplateKWLoc,
1915                        const TemplateArgumentListInfo *TemplateArgs) {
1916   NestedNameSpecifierLoc NNS =
1917       SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc();
1918   return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc,
1919                           TemplateArgs);
1920 }
1921 
1922 NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) {
1923   // A declaration named in an unevaluated operand never constitutes an odr-use.
1924   if (isUnevaluatedContext())
1925     return NOUR_Unevaluated;
1926 
1927   // C++2a [basic.def.odr]p4:
1928   //   A variable x whose name appears as a potentially-evaluated expression e
1929   //   is odr-used by e unless [...] x is a reference that is usable in
1930   //   constant expressions.
1931   if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
1932     if (VD->getType()->isReferenceType() &&
1933         !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) &&
1934         VD->isUsableInConstantExpressions(Context))
1935       return NOUR_Constant;
1936   }
1937 
1938   // All remaining non-variable cases constitute an odr-use. For variables, we
1939   // need to wait and see how the expression is used.
1940   return NOUR_None;
1941 }
1942 
1943 /// BuildDeclRefExpr - Build an expression that references a
1944 /// declaration that does not require a closure capture.
1945 DeclRefExpr *
1946 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1947                        const DeclarationNameInfo &NameInfo,
1948                        NestedNameSpecifierLoc NNS, NamedDecl *FoundD,
1949                        SourceLocation TemplateKWLoc,
1950                        const TemplateArgumentListInfo *TemplateArgs) {
1951   bool RefersToCapturedVariable =
1952       isa<VarDecl>(D) &&
1953       NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
1954 
1955   DeclRefExpr *E = DeclRefExpr::Create(
1956       Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty,
1957       VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D));
1958   MarkDeclRefReferenced(E);
1959 
1960   // C++ [except.spec]p17:
1961   //   An exception-specification is considered to be needed when:
1962   //   - in an expression, the function is the unique lookup result or
1963   //     the selected member of a set of overloaded functions.
1964   //
1965   // We delay doing this until after we've built the function reference and
1966   // marked it as used so that:
1967   //  a) if the function is defaulted, we get errors from defining it before /
1968   //     instead of errors from computing its exception specification, and
1969   //  b) if the function is a defaulted comparison, we can use the body we
1970   //     build when defining it as input to the exception specification
1971   //     computation rather than computing a new body.
1972   if (auto *FPT = Ty->getAs<FunctionProtoType>()) {
1973     if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
1974       if (auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT))
1975         E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers()));
1976     }
1977   }
1978 
1979   if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
1980       Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() &&
1981       !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc()))
1982     getCurFunction()->recordUseOfWeak(E);
1983 
1984   FieldDecl *FD = dyn_cast<FieldDecl>(D);
1985   if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
1986     FD = IFD->getAnonField();
1987   if (FD) {
1988     UnusedPrivateFields.remove(FD);
1989     // Just in case we're building an illegal pointer-to-member.
1990     if (FD->isBitField())
1991       E->setObjectKind(OK_BitField);
1992   }
1993 
1994   // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
1995   // designates a bit-field.
1996   if (auto *BD = dyn_cast<BindingDecl>(D))
1997     if (auto *BE = BD->getBinding())
1998       E->setObjectKind(BE->getObjectKind());
1999 
2000   return E;
2001 }
2002 
2003 /// Decomposes the given name into a DeclarationNameInfo, its location, and
2004 /// possibly a list of template arguments.
2005 ///
2006 /// If this produces template arguments, it is permitted to call
2007 /// DecomposeTemplateName.
2008 ///
2009 /// This actually loses a lot of source location information for
2010 /// non-standard name kinds; we should consider preserving that in
2011 /// some way.
2012 void
2013 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
2014                              TemplateArgumentListInfo &Buffer,
2015                              DeclarationNameInfo &NameInfo,
2016                              const TemplateArgumentListInfo *&TemplateArgs) {
2017   if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) {
2018     Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
2019     Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
2020 
2021     ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
2022                                        Id.TemplateId->NumArgs);
2023     translateTemplateArguments(TemplateArgsPtr, Buffer);
2024 
2025     TemplateName TName = Id.TemplateId->Template.get();
2026     SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
2027     NameInfo = Context.getNameForTemplate(TName, TNameLoc);
2028     TemplateArgs = &Buffer;
2029   } else {
2030     NameInfo = GetNameFromUnqualifiedId(Id);
2031     TemplateArgs = nullptr;
2032   }
2033 }
2034 
2035 static void emitEmptyLookupTypoDiagnostic(
2036     const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
2037     DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
2038     unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
2039   DeclContext *Ctx =
2040       SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
2041   if (!TC) {
2042     // Emit a special diagnostic for failed member lookups.
2043     // FIXME: computing the declaration context might fail here (?)
2044     if (Ctx)
2045       SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
2046                                                  << SS.getRange();
2047     else
2048       SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
2049     return;
2050   }
2051 
2052   std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
2053   bool DroppedSpecifier =
2054       TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
2055   unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
2056                         ? diag::note_implicit_param_decl
2057                         : diag::note_previous_decl;
2058   if (!Ctx)
2059     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
2060                          SemaRef.PDiag(NoteID));
2061   else
2062     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
2063                                  << Typo << Ctx << DroppedSpecifier
2064                                  << SS.getRange(),
2065                          SemaRef.PDiag(NoteID));
2066 }
2067 
2068 /// Diagnose an empty lookup.
2069 ///
2070 /// \return false if new lookup candidates were found
2071 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
2072                                CorrectionCandidateCallback &CCC,
2073                                TemplateArgumentListInfo *ExplicitTemplateArgs,
2074                                ArrayRef<Expr *> Args, TypoExpr **Out) {
2075   DeclarationName Name = R.getLookupName();
2076 
2077   unsigned diagnostic = diag::err_undeclared_var_use;
2078   unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
2079   if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
2080       Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
2081       Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
2082     diagnostic = diag::err_undeclared_use;
2083     diagnostic_suggest = diag::err_undeclared_use_suggest;
2084   }
2085 
2086   // If the original lookup was an unqualified lookup, fake an
2087   // unqualified lookup.  This is useful when (for example) the
2088   // original lookup would not have found something because it was a
2089   // dependent name.
2090   DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
2091   while (DC) {
2092     if (isa<CXXRecordDecl>(DC)) {
2093       LookupQualifiedName(R, DC);
2094 
2095       if (!R.empty()) {
2096         // Don't give errors about ambiguities in this lookup.
2097         R.suppressDiagnostics();
2098 
2099         // During a default argument instantiation the CurContext points
2100         // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
2101         // function parameter list, hence add an explicit check.
2102         bool isDefaultArgument =
2103             !CodeSynthesisContexts.empty() &&
2104             CodeSynthesisContexts.back().Kind ==
2105                 CodeSynthesisContext::DefaultFunctionArgumentInstantiation;
2106         CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
2107         bool isInstance = CurMethod &&
2108                           CurMethod->isInstance() &&
2109                           DC == CurMethod->getParent() && !isDefaultArgument;
2110 
2111         // Give a code modification hint to insert 'this->'.
2112         // TODO: fixit for inserting 'Base<T>::' in the other cases.
2113         // Actually quite difficult!
2114         if (getLangOpts().MSVCCompat)
2115           diagnostic = diag::ext_found_via_dependent_bases_lookup;
2116         if (isInstance) {
2117           Diag(R.getNameLoc(), diagnostic) << Name
2118             << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
2119           CheckCXXThisCapture(R.getNameLoc());
2120         } else {
2121           Diag(R.getNameLoc(), diagnostic) << Name;
2122         }
2123 
2124         // Do we really want to note all of these?
2125         for (NamedDecl *D : R)
2126           Diag(D->getLocation(), diag::note_dependent_var_use);
2127 
2128         // Return true if we are inside a default argument instantiation
2129         // and the found name refers to an instance member function, otherwise
2130         // the function calling DiagnoseEmptyLookup will try to create an
2131         // implicit member call and this is wrong for default argument.
2132         if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
2133           Diag(R.getNameLoc(), diag::err_member_call_without_object);
2134           return true;
2135         }
2136 
2137         // Tell the callee to try to recover.
2138         return false;
2139       }
2140 
2141       R.clear();
2142     }
2143 
2144     DC = DC->getLookupParent();
2145   }
2146 
2147   // We didn't find anything, so try to correct for a typo.
2148   TypoCorrection Corrected;
2149   if (S && Out) {
2150     SourceLocation TypoLoc = R.getNameLoc();
2151     assert(!ExplicitTemplateArgs &&
2152            "Diagnosing an empty lookup with explicit template args!");
2153     *Out = CorrectTypoDelayed(
2154         R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
2155         [=](const TypoCorrection &TC) {
2156           emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
2157                                         diagnostic, diagnostic_suggest);
2158         },
2159         nullptr, CTK_ErrorRecovery);
2160     if (*Out)
2161       return true;
2162   } else if (S &&
2163              (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
2164                                       S, &SS, CCC, CTK_ErrorRecovery))) {
2165     std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
2166     bool DroppedSpecifier =
2167         Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
2168     R.setLookupName(Corrected.getCorrection());
2169 
2170     bool AcceptableWithRecovery = false;
2171     bool AcceptableWithoutRecovery = false;
2172     NamedDecl *ND = Corrected.getFoundDecl();
2173     if (ND) {
2174       if (Corrected.isOverloaded()) {
2175         OverloadCandidateSet OCS(R.getNameLoc(),
2176                                  OverloadCandidateSet::CSK_Normal);
2177         OverloadCandidateSet::iterator Best;
2178         for (NamedDecl *CD : Corrected) {
2179           if (FunctionTemplateDecl *FTD =
2180                    dyn_cast<FunctionTemplateDecl>(CD))
2181             AddTemplateOverloadCandidate(
2182                 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
2183                 Args, OCS);
2184           else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
2185             if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
2186               AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
2187                                    Args, OCS);
2188         }
2189         switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
2190         case OR_Success:
2191           ND = Best->FoundDecl;
2192           Corrected.setCorrectionDecl(ND);
2193           break;
2194         default:
2195           // FIXME: Arbitrarily pick the first declaration for the note.
2196           Corrected.setCorrectionDecl(ND);
2197           break;
2198         }
2199       }
2200       R.addDecl(ND);
2201       if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2202         CXXRecordDecl *Record = nullptr;
2203         if (Corrected.getCorrectionSpecifier()) {
2204           const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
2205           Record = Ty->getAsCXXRecordDecl();
2206         }
2207         if (!Record)
2208           Record = cast<CXXRecordDecl>(
2209               ND->getDeclContext()->getRedeclContext());
2210         R.setNamingClass(Record);
2211       }
2212 
2213       auto *UnderlyingND = ND->getUnderlyingDecl();
2214       AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2215                                isa<FunctionTemplateDecl>(UnderlyingND);
2216       // FIXME: If we ended up with a typo for a type name or
2217       // Objective-C class name, we're in trouble because the parser
2218       // is in the wrong place to recover. Suggest the typo
2219       // correction, but don't make it a fix-it since we're not going
2220       // to recover well anyway.
2221       AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) ||
2222                                   getAsTypeTemplateDecl(UnderlyingND) ||
2223                                   isa<ObjCInterfaceDecl>(UnderlyingND);
2224     } else {
2225       // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2226       // because we aren't able to recover.
2227       AcceptableWithoutRecovery = true;
2228     }
2229 
2230     if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2231       unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2232                             ? diag::note_implicit_param_decl
2233                             : diag::note_previous_decl;
2234       if (SS.isEmpty())
2235         diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
2236                      PDiag(NoteID), AcceptableWithRecovery);
2237       else
2238         diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
2239                                   << Name << computeDeclContext(SS, false)
2240                                   << DroppedSpecifier << SS.getRange(),
2241                      PDiag(NoteID), AcceptableWithRecovery);
2242 
2243       // Tell the callee whether to try to recover.
2244       return !AcceptableWithRecovery;
2245     }
2246   }
2247   R.clear();
2248 
2249   // Emit a special diagnostic for failed member lookups.
2250   // FIXME: computing the declaration context might fail here (?)
2251   if (!SS.isEmpty()) {
2252     Diag(R.getNameLoc(), diag::err_no_member)
2253       << Name << computeDeclContext(SS, false)
2254       << SS.getRange();
2255     return true;
2256   }
2257 
2258   // Give up, we can't recover.
2259   Diag(R.getNameLoc(), diagnostic) << Name;
2260   return true;
2261 }
2262 
2263 /// In Microsoft mode, if we are inside a template class whose parent class has
2264 /// dependent base classes, and we can't resolve an unqualified identifier, then
2265 /// assume the identifier is a member of a dependent base class.  We can only
2266 /// recover successfully in static methods, instance methods, and other contexts
2267 /// where 'this' is available.  This doesn't precisely match MSVC's
2268 /// instantiation model, but it's close enough.
2269 static Expr *
2270 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
2271                                DeclarationNameInfo &NameInfo,
2272                                SourceLocation TemplateKWLoc,
2273                                const TemplateArgumentListInfo *TemplateArgs) {
2274   // Only try to recover from lookup into dependent bases in static methods or
2275   // contexts where 'this' is available.
2276   QualType ThisType = S.getCurrentThisType();
2277   const CXXRecordDecl *RD = nullptr;
2278   if (!ThisType.isNull())
2279     RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2280   else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2281     RD = MD->getParent();
2282   if (!RD || !RD->hasAnyDependentBases())
2283     return nullptr;
2284 
2285   // Diagnose this as unqualified lookup into a dependent base class.  If 'this'
2286   // is available, suggest inserting 'this->' as a fixit.
2287   SourceLocation Loc = NameInfo.getLoc();
2288   auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2289   DB << NameInfo.getName() << RD;
2290 
2291   if (!ThisType.isNull()) {
2292     DB << FixItHint::CreateInsertion(Loc, "this->");
2293     return CXXDependentScopeMemberExpr::Create(
2294         Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2295         /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2296         /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
2297   }
2298 
2299   // Synthesize a fake NNS that points to the derived class.  This will
2300   // perform name lookup during template instantiation.
2301   CXXScopeSpec SS;
2302   auto *NNS =
2303       NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2304   SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2305   return DependentScopeDeclRefExpr::Create(
2306       Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2307       TemplateArgs);
2308 }
2309 
2310 ExprResult
2311 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2312                         SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2313                         bool HasTrailingLParen, bool IsAddressOfOperand,
2314                         CorrectionCandidateCallback *CCC,
2315                         bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2316   assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2317          "cannot be direct & operand and have a trailing lparen");
2318   if (SS.isInvalid())
2319     return ExprError();
2320 
2321   TemplateArgumentListInfo TemplateArgsBuffer;
2322 
2323   // Decompose the UnqualifiedId into the following data.
2324   DeclarationNameInfo NameInfo;
2325   const TemplateArgumentListInfo *TemplateArgs;
2326   DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2327 
2328   DeclarationName Name = NameInfo.getName();
2329   IdentifierInfo *II = Name.getAsIdentifierInfo();
2330   SourceLocation NameLoc = NameInfo.getLoc();
2331 
2332   if (II && II->isEditorPlaceholder()) {
2333     // FIXME: When typed placeholders are supported we can create a typed
2334     // placeholder expression node.
2335     return ExprError();
2336   }
2337 
2338   // C++ [temp.dep.expr]p3:
2339   //   An id-expression is type-dependent if it contains:
2340   //     -- an identifier that was declared with a dependent type,
2341   //        (note: handled after lookup)
2342   //     -- a template-id that is dependent,
2343   //        (note: handled in BuildTemplateIdExpr)
2344   //     -- a conversion-function-id that specifies a dependent type,
2345   //     -- a nested-name-specifier that contains a class-name that
2346   //        names a dependent type.
2347   // Determine whether this is a member of an unknown specialization;
2348   // we need to handle these differently.
2349   bool DependentID = false;
2350   if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2351       Name.getCXXNameType()->isDependentType()) {
2352     DependentID = true;
2353   } else if (SS.isSet()) {
2354     if (DeclContext *DC = computeDeclContext(SS, false)) {
2355       if (RequireCompleteDeclContext(SS, DC))
2356         return ExprError();
2357     } else {
2358       DependentID = true;
2359     }
2360   }
2361 
2362   if (DependentID)
2363     return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2364                                       IsAddressOfOperand, TemplateArgs);
2365 
2366   // Perform the required lookup.
2367   LookupResult R(*this, NameInfo,
2368                  (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam)
2369                      ? LookupObjCImplicitSelfParam
2370                      : LookupOrdinaryName);
2371   if (TemplateKWLoc.isValid() || TemplateArgs) {
2372     // Lookup the template name again to correctly establish the context in
2373     // which it was found. This is really unfortunate as we already did the
2374     // lookup to determine that it was a template name in the first place. If
2375     // this becomes a performance hit, we can work harder to preserve those
2376     // results until we get here but it's likely not worth it.
2377     bool MemberOfUnknownSpecialization;
2378     AssumedTemplateKind AssumedTemplate;
2379     if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2380                            MemberOfUnknownSpecialization, TemplateKWLoc,
2381                            &AssumedTemplate))
2382       return ExprError();
2383 
2384     if (MemberOfUnknownSpecialization ||
2385         (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2386       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2387                                         IsAddressOfOperand, TemplateArgs);
2388   } else {
2389     bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2390     LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2391 
2392     // If the result might be in a dependent base class, this is a dependent
2393     // id-expression.
2394     if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2395       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2396                                         IsAddressOfOperand, TemplateArgs);
2397 
2398     // If this reference is in an Objective-C method, then we need to do
2399     // some special Objective-C lookup, too.
2400     if (IvarLookupFollowUp) {
2401       ExprResult E(LookupInObjCMethod(R, S, II, true));
2402       if (E.isInvalid())
2403         return ExprError();
2404 
2405       if (Expr *Ex = E.getAs<Expr>())
2406         return Ex;
2407     }
2408   }
2409 
2410   if (R.isAmbiguous())
2411     return ExprError();
2412 
2413   // This could be an implicitly declared function reference (legal in C90,
2414   // extension in C99, forbidden in C++).
2415   if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2416     NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2417     if (D) R.addDecl(D);
2418   }
2419 
2420   // Determine whether this name might be a candidate for
2421   // argument-dependent lookup.
2422   bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2423 
2424   if (R.empty() && !ADL) {
2425     if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2426       if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2427                                                    TemplateKWLoc, TemplateArgs))
2428         return E;
2429     }
2430 
2431     // Don't diagnose an empty lookup for inline assembly.
2432     if (IsInlineAsmIdentifier)
2433       return ExprError();
2434 
2435     // If this name wasn't predeclared and if this is not a function
2436     // call, diagnose the problem.
2437     TypoExpr *TE = nullptr;
2438     DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep()
2439                                                        : nullptr);
2440     DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;
2441     assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2442            "Typo correction callback misconfigured");
2443     if (CCC) {
2444       // Make sure the callback knows what the typo being diagnosed is.
2445       CCC->setTypoName(II);
2446       if (SS.isValid())
2447         CCC->setTypoNNS(SS.getScopeRep());
2448     }
2449     // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2450     // a template name, but we happen to have always already looked up the name
2451     // before we get here if it must be a template name.
2452     if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr,
2453                             None, &TE)) {
2454       if (TE && KeywordReplacement) {
2455         auto &State = getTypoExprState(TE);
2456         auto BestTC = State.Consumer->getNextCorrection();
2457         if (BestTC.isKeyword()) {
2458           auto *II = BestTC.getCorrectionAsIdentifierInfo();
2459           if (State.DiagHandler)
2460             State.DiagHandler(BestTC);
2461           KeywordReplacement->startToken();
2462           KeywordReplacement->setKind(II->getTokenID());
2463           KeywordReplacement->setIdentifierInfo(II);
2464           KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2465           // Clean up the state associated with the TypoExpr, since it has
2466           // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2467           clearDelayedTypo(TE);
2468           // Signal that a correction to a keyword was performed by returning a
2469           // valid-but-null ExprResult.
2470           return (Expr*)nullptr;
2471         }
2472         State.Consumer->resetCorrectionStream();
2473       }
2474       return TE ? TE : ExprError();
2475     }
2476 
2477     assert(!R.empty() &&
2478            "DiagnoseEmptyLookup returned false but added no results");
2479 
2480     // If we found an Objective-C instance variable, let
2481     // LookupInObjCMethod build the appropriate expression to
2482     // reference the ivar.
2483     if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2484       R.clear();
2485       ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2486       // In a hopelessly buggy code, Objective-C instance variable
2487       // lookup fails and no expression will be built to reference it.
2488       if (!E.isInvalid() && !E.get())
2489         return ExprError();
2490       return E;
2491     }
2492   }
2493 
2494   // This is guaranteed from this point on.
2495   assert(!R.empty() || ADL);
2496 
2497   // Check whether this might be a C++ implicit instance member access.
2498   // C++ [class.mfct.non-static]p3:
2499   //   When an id-expression that is not part of a class member access
2500   //   syntax and not used to form a pointer to member is used in the
2501   //   body of a non-static member function of class X, if name lookup
2502   //   resolves the name in the id-expression to a non-static non-type
2503   //   member of some class C, the id-expression is transformed into a
2504   //   class member access expression using (*this) as the
2505   //   postfix-expression to the left of the . operator.
2506   //
2507   // But we don't actually need to do this for '&' operands if R
2508   // resolved to a function or overloaded function set, because the
2509   // expression is ill-formed if it actually works out to be a
2510   // non-static member function:
2511   //
2512   // C++ [expr.ref]p4:
2513   //   Otherwise, if E1.E2 refers to a non-static member function. . .
2514   //   [t]he expression can be used only as the left-hand operand of a
2515   //   member function call.
2516   //
2517   // There are other safeguards against such uses, but it's important
2518   // to get this right here so that we don't end up making a
2519   // spuriously dependent expression if we're inside a dependent
2520   // instance method.
2521   if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2522     bool MightBeImplicitMember;
2523     if (!IsAddressOfOperand)
2524       MightBeImplicitMember = true;
2525     else if (!SS.isEmpty())
2526       MightBeImplicitMember = false;
2527     else if (R.isOverloadedResult())
2528       MightBeImplicitMember = false;
2529     else if (R.isUnresolvableResult())
2530       MightBeImplicitMember = true;
2531     else
2532       MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2533                               isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2534                               isa<MSPropertyDecl>(R.getFoundDecl());
2535 
2536     if (MightBeImplicitMember)
2537       return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2538                                              R, TemplateArgs, S);
2539   }
2540 
2541   if (TemplateArgs || TemplateKWLoc.isValid()) {
2542 
2543     // In C++1y, if this is a variable template id, then check it
2544     // in BuildTemplateIdExpr().
2545     // The single lookup result must be a variable template declaration.
2546     if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId &&
2547         Id.TemplateId->Kind == TNK_Var_template) {
2548       assert(R.getAsSingle<VarTemplateDecl>() &&
2549              "There should only be one declaration found.");
2550     }
2551 
2552     return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2553   }
2554 
2555   return BuildDeclarationNameExpr(SS, R, ADL);
2556 }
2557 
2558 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2559 /// declaration name, generally during template instantiation.
2560 /// There's a large number of things which don't need to be done along
2561 /// this path.
2562 ExprResult Sema::BuildQualifiedDeclarationNameExpr(
2563     CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2564     bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2565   DeclContext *DC = computeDeclContext(SS, false);
2566   if (!DC)
2567     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2568                                      NameInfo, /*TemplateArgs=*/nullptr);
2569 
2570   if (RequireCompleteDeclContext(SS, DC))
2571     return ExprError();
2572 
2573   LookupResult R(*this, NameInfo, LookupOrdinaryName);
2574   LookupQualifiedName(R, DC);
2575 
2576   if (R.isAmbiguous())
2577     return ExprError();
2578 
2579   if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2580     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2581                                      NameInfo, /*TemplateArgs=*/nullptr);
2582 
2583   if (R.empty()) {
2584     Diag(NameInfo.getLoc(), diag::err_no_member)
2585       << NameInfo.getName() << DC << SS.getRange();
2586     return ExprError();
2587   }
2588 
2589   if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2590     // Diagnose a missing typename if this resolved unambiguously to a type in
2591     // a dependent context.  If we can recover with a type, downgrade this to
2592     // a warning in Microsoft compatibility mode.
2593     unsigned DiagID = diag::err_typename_missing;
2594     if (RecoveryTSI && getLangOpts().MSVCCompat)
2595       DiagID = diag::ext_typename_missing;
2596     SourceLocation Loc = SS.getBeginLoc();
2597     auto D = Diag(Loc, DiagID);
2598     D << SS.getScopeRep() << NameInfo.getName().getAsString()
2599       << SourceRange(Loc, NameInfo.getEndLoc());
2600 
2601     // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2602     // context.
2603     if (!RecoveryTSI)
2604       return ExprError();
2605 
2606     // Only issue the fixit if we're prepared to recover.
2607     D << FixItHint::CreateInsertion(Loc, "typename ");
2608 
2609     // Recover by pretending this was an elaborated type.
2610     QualType Ty = Context.getTypeDeclType(TD);
2611     TypeLocBuilder TLB;
2612     TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2613 
2614     QualType ET = getElaboratedType(ETK_None, SS, Ty);
2615     ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2616     QTL.setElaboratedKeywordLoc(SourceLocation());
2617     QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2618 
2619     *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2620 
2621     return ExprEmpty();
2622   }
2623 
2624   // Defend against this resolving to an implicit member access. We usually
2625   // won't get here if this might be a legitimate a class member (we end up in
2626   // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2627   // a pointer-to-member or in an unevaluated context in C++11.
2628   if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2629     return BuildPossibleImplicitMemberExpr(SS,
2630                                            /*TemplateKWLoc=*/SourceLocation(),
2631                                            R, /*TemplateArgs=*/nullptr, S);
2632 
2633   return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2634 }
2635 
2636 /// The parser has read a name in, and Sema has detected that we're currently
2637 /// inside an ObjC method. Perform some additional checks and determine if we
2638 /// should form a reference to an ivar.
2639 ///
2640 /// Ideally, most of this would be done by lookup, but there's
2641 /// actually quite a lot of extra work involved.
2642 DeclResult Sema::LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S,
2643                                         IdentifierInfo *II) {
2644   SourceLocation Loc = Lookup.getNameLoc();
2645   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2646 
2647   // Check for error condition which is already reported.
2648   if (!CurMethod)
2649     return DeclResult(true);
2650 
2651   // There are two cases to handle here.  1) scoped lookup could have failed,
2652   // in which case we should look for an ivar.  2) scoped lookup could have
2653   // found a decl, but that decl is outside the current instance method (i.e.
2654   // a global variable).  In these two cases, we do a lookup for an ivar with
2655   // this name, if the lookup sucedes, we replace it our current decl.
2656 
2657   // If we're in a class method, we don't normally want to look for
2658   // ivars.  But if we don't find anything else, and there's an
2659   // ivar, that's an error.
2660   bool IsClassMethod = CurMethod->isClassMethod();
2661 
2662   bool LookForIvars;
2663   if (Lookup.empty())
2664     LookForIvars = true;
2665   else if (IsClassMethod)
2666     LookForIvars = false;
2667   else
2668     LookForIvars = (Lookup.isSingleResult() &&
2669                     Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2670   ObjCInterfaceDecl *IFace = nullptr;
2671   if (LookForIvars) {
2672     IFace = CurMethod->getClassInterface();
2673     ObjCInterfaceDecl *ClassDeclared;
2674     ObjCIvarDecl *IV = nullptr;
2675     if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2676       // Diagnose using an ivar in a class method.
2677       if (IsClassMethod) {
2678         Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
2679         return DeclResult(true);
2680       }
2681 
2682       // Diagnose the use of an ivar outside of the declaring class.
2683       if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2684           !declaresSameEntity(ClassDeclared, IFace) &&
2685           !getLangOpts().DebuggerSupport)
2686         Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
2687 
2688       // Success.
2689       return IV;
2690     }
2691   } else if (CurMethod->isInstanceMethod()) {
2692     // We should warn if a local variable hides an ivar.
2693     if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2694       ObjCInterfaceDecl *ClassDeclared;
2695       if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2696         if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2697             declaresSameEntity(IFace, ClassDeclared))
2698           Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2699       }
2700     }
2701   } else if (Lookup.isSingleResult() &&
2702              Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2703     // If accessing a stand-alone ivar in a class method, this is an error.
2704     if (const ObjCIvarDecl *IV =
2705             dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) {
2706       Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
2707       return DeclResult(true);
2708     }
2709   }
2710 
2711   // Didn't encounter an error, didn't find an ivar.
2712   return DeclResult(false);
2713 }
2714 
2715 ExprResult Sema::BuildIvarRefExpr(Scope *S, SourceLocation Loc,
2716                                   ObjCIvarDecl *IV) {
2717   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2718   assert(CurMethod && CurMethod->isInstanceMethod() &&
2719          "should not reference ivar from this context");
2720 
2721   ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
2722   assert(IFace && "should not reference ivar from this context");
2723 
2724   // If we're referencing an invalid decl, just return this as a silent
2725   // error node.  The error diagnostic was already emitted on the decl.
2726   if (IV->isInvalidDecl())
2727     return ExprError();
2728 
2729   // Check if referencing a field with __attribute__((deprecated)).
2730   if (DiagnoseUseOfDecl(IV, Loc))
2731     return ExprError();
2732 
2733   // FIXME: This should use a new expr for a direct reference, don't
2734   // turn this into Self->ivar, just return a BareIVarExpr or something.
2735   IdentifierInfo &II = Context.Idents.get("self");
2736   UnqualifiedId SelfName;
2737   SelfName.setIdentifier(&II, SourceLocation());
2738   SelfName.setKind(UnqualifiedIdKind::IK_ImplicitSelfParam);
2739   CXXScopeSpec SelfScopeSpec;
2740   SourceLocation TemplateKWLoc;
2741   ExprResult SelfExpr =
2742       ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName,
2743                         /*HasTrailingLParen=*/false,
2744                         /*IsAddressOfOperand=*/false);
2745   if (SelfExpr.isInvalid())
2746     return ExprError();
2747 
2748   SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2749   if (SelfExpr.isInvalid())
2750     return ExprError();
2751 
2752   MarkAnyDeclReferenced(Loc, IV, true);
2753 
2754   ObjCMethodFamily MF = CurMethod->getMethodFamily();
2755   if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2756       !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2757     Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2758 
2759   ObjCIvarRefExpr *Result = new (Context)
2760       ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2761                       IV->getLocation(), SelfExpr.get(), true, true);
2762 
2763   if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2764     if (!isUnevaluatedContext() &&
2765         !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2766       getCurFunction()->recordUseOfWeak(Result);
2767   }
2768   if (getLangOpts().ObjCAutoRefCount)
2769     if (const BlockDecl *BD = CurContext->getInnermostBlockDecl())
2770       ImplicitlyRetainedSelfLocs.push_back({Loc, BD});
2771 
2772   return Result;
2773 }
2774 
2775 /// The parser has read a name in, and Sema has detected that we're currently
2776 /// inside an ObjC method. Perform some additional checks and determine if we
2777 /// should form a reference to an ivar. If so, build an expression referencing
2778 /// that ivar.
2779 ExprResult
2780 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2781                          IdentifierInfo *II, bool AllowBuiltinCreation) {
2782   // FIXME: Integrate this lookup step into LookupParsedName.
2783   DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II);
2784   if (Ivar.isInvalid())
2785     return ExprError();
2786   if (Ivar.isUsable())
2787     return BuildIvarRefExpr(S, Lookup.getNameLoc(),
2788                             cast<ObjCIvarDecl>(Ivar.get()));
2789 
2790   if (Lookup.empty() && II && AllowBuiltinCreation)
2791     LookupBuiltin(Lookup);
2792 
2793   // Sentinel value saying that we didn't do anything special.
2794   return ExprResult(false);
2795 }
2796 
2797 /// Cast a base object to a member's actual type.
2798 ///
2799 /// Logically this happens in three phases:
2800 ///
2801 /// * First we cast from the base type to the naming class.
2802 ///   The naming class is the class into which we were looking
2803 ///   when we found the member;  it's the qualifier type if a
2804 ///   qualifier was provided, and otherwise it's the base type.
2805 ///
2806 /// * Next we cast from the naming class to the declaring class.
2807 ///   If the member we found was brought into a class's scope by
2808 ///   a using declaration, this is that class;  otherwise it's
2809 ///   the class declaring the member.
2810 ///
2811 /// * Finally we cast from the declaring class to the "true"
2812 ///   declaring class of the member.  This conversion does not
2813 ///   obey access control.
2814 ExprResult
2815 Sema::PerformObjectMemberConversion(Expr *From,
2816                                     NestedNameSpecifier *Qualifier,
2817                                     NamedDecl *FoundDecl,
2818                                     NamedDecl *Member) {
2819   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2820   if (!RD)
2821     return From;
2822 
2823   QualType DestRecordType;
2824   QualType DestType;
2825   QualType FromRecordType;
2826   QualType FromType = From->getType();
2827   bool PointerConversions = false;
2828   if (isa<FieldDecl>(Member)) {
2829     DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2830     auto FromPtrType = FromType->getAs<PointerType>();
2831     DestRecordType = Context.getAddrSpaceQualType(
2832         DestRecordType, FromPtrType
2833                             ? FromType->getPointeeType().getAddressSpace()
2834                             : FromType.getAddressSpace());
2835 
2836     if (FromPtrType) {
2837       DestType = Context.getPointerType(DestRecordType);
2838       FromRecordType = FromPtrType->getPointeeType();
2839       PointerConversions = true;
2840     } else {
2841       DestType = DestRecordType;
2842       FromRecordType = FromType;
2843     }
2844   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2845     if (Method->isStatic())
2846       return From;
2847 
2848     DestType = Method->getThisType();
2849     DestRecordType = DestType->getPointeeType();
2850 
2851     if (FromType->getAs<PointerType>()) {
2852       FromRecordType = FromType->getPointeeType();
2853       PointerConversions = true;
2854     } else {
2855       FromRecordType = FromType;
2856       DestType = DestRecordType;
2857     }
2858 
2859     LangAS FromAS = FromRecordType.getAddressSpace();
2860     LangAS DestAS = DestRecordType.getAddressSpace();
2861     if (FromAS != DestAS) {
2862       QualType FromRecordTypeWithoutAS =
2863           Context.removeAddrSpaceQualType(FromRecordType);
2864       QualType FromTypeWithDestAS =
2865           Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS);
2866       if (PointerConversions)
2867         FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS);
2868       From = ImpCastExprToType(From, FromTypeWithDestAS,
2869                                CK_AddressSpaceConversion, From->getValueKind())
2870                  .get();
2871     }
2872   } else {
2873     // No conversion necessary.
2874     return From;
2875   }
2876 
2877   if (DestType->isDependentType() || FromType->isDependentType())
2878     return From;
2879 
2880   // If the unqualified types are the same, no conversion is necessary.
2881   if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2882     return From;
2883 
2884   SourceRange FromRange = From->getSourceRange();
2885   SourceLocation FromLoc = FromRange.getBegin();
2886 
2887   ExprValueKind VK = From->getValueKind();
2888 
2889   // C++ [class.member.lookup]p8:
2890   //   [...] Ambiguities can often be resolved by qualifying a name with its
2891   //   class name.
2892   //
2893   // If the member was a qualified name and the qualified referred to a
2894   // specific base subobject type, we'll cast to that intermediate type
2895   // first and then to the object in which the member is declared. That allows
2896   // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2897   //
2898   //   class Base { public: int x; };
2899   //   class Derived1 : public Base { };
2900   //   class Derived2 : public Base { };
2901   //   class VeryDerived : public Derived1, public Derived2 { void f(); };
2902   //
2903   //   void VeryDerived::f() {
2904   //     x = 17; // error: ambiguous base subobjects
2905   //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
2906   //   }
2907   if (Qualifier && Qualifier->getAsType()) {
2908     QualType QType = QualType(Qualifier->getAsType(), 0);
2909     assert(QType->isRecordType() && "lookup done with non-record type");
2910 
2911     QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2912 
2913     // In C++98, the qualifier type doesn't actually have to be a base
2914     // type of the object type, in which case we just ignore it.
2915     // Otherwise build the appropriate casts.
2916     if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
2917       CXXCastPath BasePath;
2918       if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2919                                        FromLoc, FromRange, &BasePath))
2920         return ExprError();
2921 
2922       if (PointerConversions)
2923         QType = Context.getPointerType(QType);
2924       From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2925                                VK, &BasePath).get();
2926 
2927       FromType = QType;
2928       FromRecordType = QRecordType;
2929 
2930       // If the qualifier type was the same as the destination type,
2931       // we're done.
2932       if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2933         return From;
2934     }
2935   }
2936 
2937   bool IgnoreAccess = false;
2938 
2939   // If we actually found the member through a using declaration, cast
2940   // down to the using declaration's type.
2941   //
2942   // Pointer equality is fine here because only one declaration of a
2943   // class ever has member declarations.
2944   if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2945     assert(isa<UsingShadowDecl>(FoundDecl));
2946     QualType URecordType = Context.getTypeDeclType(
2947                            cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2948 
2949     // We only need to do this if the naming-class to declaring-class
2950     // conversion is non-trivial.
2951     if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2952       assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType));
2953       CXXCastPath BasePath;
2954       if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2955                                        FromLoc, FromRange, &BasePath))
2956         return ExprError();
2957 
2958       QualType UType = URecordType;
2959       if (PointerConversions)
2960         UType = Context.getPointerType(UType);
2961       From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2962                                VK, &BasePath).get();
2963       FromType = UType;
2964       FromRecordType = URecordType;
2965     }
2966 
2967     // We don't do access control for the conversion from the
2968     // declaring class to the true declaring class.
2969     IgnoreAccess = true;
2970   }
2971 
2972   CXXCastPath BasePath;
2973   if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2974                                    FromLoc, FromRange, &BasePath,
2975                                    IgnoreAccess))
2976     return ExprError();
2977 
2978   return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2979                            VK, &BasePath);
2980 }
2981 
2982 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2983                                       const LookupResult &R,
2984                                       bool HasTrailingLParen) {
2985   // Only when used directly as the postfix-expression of a call.
2986   if (!HasTrailingLParen)
2987     return false;
2988 
2989   // Never if a scope specifier was provided.
2990   if (SS.isSet())
2991     return false;
2992 
2993   // Only in C++ or ObjC++.
2994   if (!getLangOpts().CPlusPlus)
2995     return false;
2996 
2997   // Turn off ADL when we find certain kinds of declarations during
2998   // normal lookup:
2999   for (NamedDecl *D : R) {
3000     // C++0x [basic.lookup.argdep]p3:
3001     //     -- a declaration of a class member
3002     // Since using decls preserve this property, we check this on the
3003     // original decl.
3004     if (D->isCXXClassMember())
3005       return false;
3006 
3007     // C++0x [basic.lookup.argdep]p3:
3008     //     -- a block-scope function declaration that is not a
3009     //        using-declaration
3010     // NOTE: we also trigger this for function templates (in fact, we
3011     // don't check the decl type at all, since all other decl types
3012     // turn off ADL anyway).
3013     if (isa<UsingShadowDecl>(D))
3014       D = cast<UsingShadowDecl>(D)->getTargetDecl();
3015     else if (D->getLexicalDeclContext()->isFunctionOrMethod())
3016       return false;
3017 
3018     // C++0x [basic.lookup.argdep]p3:
3019     //     -- a declaration that is neither a function or a function
3020     //        template
3021     // And also for builtin functions.
3022     if (isa<FunctionDecl>(D)) {
3023       FunctionDecl *FDecl = cast<FunctionDecl>(D);
3024 
3025       // But also builtin functions.
3026       if (FDecl->getBuiltinID() && FDecl->isImplicit())
3027         return false;
3028     } else if (!isa<FunctionTemplateDecl>(D))
3029       return false;
3030   }
3031 
3032   return true;
3033 }
3034 
3035 
3036 /// Diagnoses obvious problems with the use of the given declaration
3037 /// as an expression.  This is only actually called for lookups that
3038 /// were not overloaded, and it doesn't promise that the declaration
3039 /// will in fact be used.
3040 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
3041   if (D->isInvalidDecl())
3042     return true;
3043 
3044   if (isa<TypedefNameDecl>(D)) {
3045     S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
3046     return true;
3047   }
3048 
3049   if (isa<ObjCInterfaceDecl>(D)) {
3050     S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
3051     return true;
3052   }
3053 
3054   if (isa<NamespaceDecl>(D)) {
3055     S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
3056     return true;
3057   }
3058 
3059   return false;
3060 }
3061 
3062 // Certain multiversion types should be treated as overloaded even when there is
3063 // only one result.
3064 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) {
3065   assert(R.isSingleResult() && "Expected only a single result");
3066   const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
3067   return FD &&
3068          (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
3069 }
3070 
3071 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
3072                                           LookupResult &R, bool NeedsADL,
3073                                           bool AcceptInvalidDecl) {
3074   // If this is a single, fully-resolved result and we don't need ADL,
3075   // just build an ordinary singleton decl ref.
3076   if (!NeedsADL && R.isSingleResult() &&
3077       !R.getAsSingle<FunctionTemplateDecl>() &&
3078       !ShouldLookupResultBeMultiVersionOverload(R))
3079     return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
3080                                     R.getRepresentativeDecl(), nullptr,
3081                                     AcceptInvalidDecl);
3082 
3083   // We only need to check the declaration if there's exactly one
3084   // result, because in the overloaded case the results can only be
3085   // functions and function templates.
3086   if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) &&
3087       CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
3088     return ExprError();
3089 
3090   // Otherwise, just build an unresolved lookup expression.  Suppress
3091   // any lookup-related diagnostics; we'll hash these out later, when
3092   // we've picked a target.
3093   R.suppressDiagnostics();
3094 
3095   UnresolvedLookupExpr *ULE
3096     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
3097                                    SS.getWithLocInContext(Context),
3098                                    R.getLookupNameInfo(),
3099                                    NeedsADL, R.isOverloadedResult(),
3100                                    R.begin(), R.end());
3101 
3102   return ULE;
3103 }
3104 
3105 static void
3106 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
3107                                    ValueDecl *var, DeclContext *DC);
3108 
3109 /// Complete semantic analysis for a reference to the given declaration.
3110 ExprResult Sema::BuildDeclarationNameExpr(
3111     const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
3112     NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
3113     bool AcceptInvalidDecl) {
3114   assert(D && "Cannot refer to a NULL declaration");
3115   assert(!isa<FunctionTemplateDecl>(D) &&
3116          "Cannot refer unambiguously to a function template");
3117 
3118   SourceLocation Loc = NameInfo.getLoc();
3119   if (CheckDeclInExpr(*this, Loc, D))
3120     return ExprError();
3121 
3122   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
3123     // Specifically diagnose references to class templates that are missing
3124     // a template argument list.
3125     diagnoseMissingTemplateArguments(TemplateName(Template), Loc);
3126     return ExprError();
3127   }
3128 
3129   // Make sure that we're referring to a value.
3130   ValueDecl *VD = dyn_cast<ValueDecl>(D);
3131   if (!VD) {
3132     Diag(Loc, diag::err_ref_non_value)
3133       << D << SS.getRange();
3134     Diag(D->getLocation(), diag::note_declared_at);
3135     return ExprError();
3136   }
3137 
3138   // Check whether this declaration can be used. Note that we suppress
3139   // this check when we're going to perform argument-dependent lookup
3140   // on this function name, because this might not be the function
3141   // that overload resolution actually selects.
3142   if (DiagnoseUseOfDecl(VD, Loc))
3143     return ExprError();
3144 
3145   // Only create DeclRefExpr's for valid Decl's.
3146   if (VD->isInvalidDecl() && !AcceptInvalidDecl)
3147     return ExprError();
3148 
3149   // Handle members of anonymous structs and unions.  If we got here,
3150   // and the reference is to a class member indirect field, then this
3151   // must be the subject of a pointer-to-member expression.
3152   if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
3153     if (!indirectField->isCXXClassMember())
3154       return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
3155                                                       indirectField);
3156 
3157   {
3158     QualType type = VD->getType();
3159     if (type.isNull())
3160       return ExprError();
3161     ExprValueKind valueKind = VK_RValue;
3162 
3163     // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of
3164     // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value,
3165     // is expanded by some outer '...' in the context of the use.
3166     type = type.getNonPackExpansionType();
3167 
3168     switch (D->getKind()) {
3169     // Ignore all the non-ValueDecl kinds.
3170 #define ABSTRACT_DECL(kind)
3171 #define VALUE(type, base)
3172 #define DECL(type, base) \
3173     case Decl::type:
3174 #include "clang/AST/DeclNodes.inc"
3175       llvm_unreachable("invalid value decl kind");
3176 
3177     // These shouldn't make it here.
3178     case Decl::ObjCAtDefsField:
3179       llvm_unreachable("forming non-member reference to ivar?");
3180 
3181     // Enum constants are always r-values and never references.
3182     // Unresolved using declarations are dependent.
3183     case Decl::EnumConstant:
3184     case Decl::UnresolvedUsingValue:
3185     case Decl::OMPDeclareReduction:
3186     case Decl::OMPDeclareMapper:
3187       valueKind = VK_RValue;
3188       break;
3189 
3190     // Fields and indirect fields that got here must be for
3191     // pointer-to-member expressions; we just call them l-values for
3192     // internal consistency, because this subexpression doesn't really
3193     // exist in the high-level semantics.
3194     case Decl::Field:
3195     case Decl::IndirectField:
3196     case Decl::ObjCIvar:
3197       assert(getLangOpts().CPlusPlus &&
3198              "building reference to field in C?");
3199 
3200       // These can't have reference type in well-formed programs, but
3201       // for internal consistency we do this anyway.
3202       type = type.getNonReferenceType();
3203       valueKind = VK_LValue;
3204       break;
3205 
3206     // Non-type template parameters are either l-values or r-values
3207     // depending on the type.
3208     case Decl::NonTypeTemplateParm: {
3209       if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
3210         type = reftype->getPointeeType();
3211         valueKind = VK_LValue; // even if the parameter is an r-value reference
3212         break;
3213       }
3214 
3215       // For non-references, we need to strip qualifiers just in case
3216       // the template parameter was declared as 'const int' or whatever.
3217       valueKind = VK_RValue;
3218       type = type.getUnqualifiedType();
3219       break;
3220     }
3221 
3222     case Decl::Var:
3223     case Decl::VarTemplateSpecialization:
3224     case Decl::VarTemplatePartialSpecialization:
3225     case Decl::Decomposition:
3226     case Decl::OMPCapturedExpr:
3227       // In C, "extern void blah;" is valid and is an r-value.
3228       if (!getLangOpts().CPlusPlus &&
3229           !type.hasQualifiers() &&
3230           type->isVoidType()) {
3231         valueKind = VK_RValue;
3232         break;
3233       }
3234       LLVM_FALLTHROUGH;
3235 
3236     case Decl::ImplicitParam:
3237     case Decl::ParmVar: {
3238       // These are always l-values.
3239       valueKind = VK_LValue;
3240       type = type.getNonReferenceType();
3241 
3242       // FIXME: Does the addition of const really only apply in
3243       // potentially-evaluated contexts? Since the variable isn't actually
3244       // captured in an unevaluated context, it seems that the answer is no.
3245       if (!isUnevaluatedContext()) {
3246         QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
3247         if (!CapturedType.isNull())
3248           type = CapturedType;
3249       }
3250 
3251       break;
3252     }
3253 
3254     case Decl::Binding: {
3255       // These are always lvalues.
3256       valueKind = VK_LValue;
3257       type = type.getNonReferenceType();
3258       // FIXME: Support lambda-capture of BindingDecls, once CWG actually
3259       // decides how that's supposed to work.
3260       auto *BD = cast<BindingDecl>(VD);
3261       if (BD->getDeclContext() != CurContext) {
3262         auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl());
3263         if (DD && DD->hasLocalStorage())
3264           diagnoseUncapturableValueReference(*this, Loc, BD, CurContext);
3265       }
3266       break;
3267     }
3268 
3269     case Decl::Function: {
3270       if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
3271         if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
3272           type = Context.BuiltinFnTy;
3273           valueKind = VK_RValue;
3274           break;
3275         }
3276       }
3277 
3278       const FunctionType *fty = type->castAs<FunctionType>();
3279 
3280       // If we're referring to a function with an __unknown_anytype
3281       // result type, make the entire expression __unknown_anytype.
3282       if (fty->getReturnType() == Context.UnknownAnyTy) {
3283         type = Context.UnknownAnyTy;
3284         valueKind = VK_RValue;
3285         break;
3286       }
3287 
3288       // Functions are l-values in C++.
3289       if (getLangOpts().CPlusPlus) {
3290         valueKind = VK_LValue;
3291         break;
3292       }
3293 
3294       // C99 DR 316 says that, if a function type comes from a
3295       // function definition (without a prototype), that type is only
3296       // used for checking compatibility. Therefore, when referencing
3297       // the function, we pretend that we don't have the full function
3298       // type.
3299       if (!cast<FunctionDecl>(VD)->hasPrototype() &&
3300           isa<FunctionProtoType>(fty))
3301         type = Context.getFunctionNoProtoType(fty->getReturnType(),
3302                                               fty->getExtInfo());
3303 
3304       // Functions are r-values in C.
3305       valueKind = VK_RValue;
3306       break;
3307     }
3308 
3309     case Decl::CXXDeductionGuide:
3310       llvm_unreachable("building reference to deduction guide");
3311 
3312     case Decl::MSProperty:
3313     case Decl::MSGuid:
3314       // FIXME: Should MSGuidDecl be subject to capture in OpenMP,
3315       // or duplicated between host and device?
3316       valueKind = VK_LValue;
3317       break;
3318 
3319     case Decl::CXXMethod:
3320       // If we're referring to a method with an __unknown_anytype
3321       // result type, make the entire expression __unknown_anytype.
3322       // This should only be possible with a type written directly.
3323       if (const FunctionProtoType *proto
3324             = dyn_cast<FunctionProtoType>(VD->getType()))
3325         if (proto->getReturnType() == Context.UnknownAnyTy) {
3326           type = Context.UnknownAnyTy;
3327           valueKind = VK_RValue;
3328           break;
3329         }
3330 
3331       // C++ methods are l-values if static, r-values if non-static.
3332       if (cast<CXXMethodDecl>(VD)->isStatic()) {
3333         valueKind = VK_LValue;
3334         break;
3335       }
3336       LLVM_FALLTHROUGH;
3337 
3338     case Decl::CXXConversion:
3339     case Decl::CXXDestructor:
3340     case Decl::CXXConstructor:
3341       valueKind = VK_RValue;
3342       break;
3343     }
3344 
3345     return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3346                             /*FIXME: TemplateKWLoc*/ SourceLocation(),
3347                             TemplateArgs);
3348   }
3349 }
3350 
3351 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3352                                     SmallString<32> &Target) {
3353   Target.resize(CharByteWidth * (Source.size() + 1));
3354   char *ResultPtr = &Target[0];
3355   const llvm::UTF8 *ErrorPtr;
3356   bool success =
3357       llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3358   (void)success;
3359   assert(success);
3360   Target.resize(ResultPtr - &Target[0]);
3361 }
3362 
3363 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3364                                      PredefinedExpr::IdentKind IK) {
3365   // Pick the current block, lambda, captured statement or function.
3366   Decl *currentDecl = nullptr;
3367   if (const BlockScopeInfo *BSI = getCurBlock())
3368     currentDecl = BSI->TheDecl;
3369   else if (const LambdaScopeInfo *LSI = getCurLambda())
3370     currentDecl = LSI->CallOperator;
3371   else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3372     currentDecl = CSI->TheCapturedDecl;
3373   else
3374     currentDecl = getCurFunctionOrMethodDecl();
3375 
3376   if (!currentDecl) {
3377     Diag(Loc, diag::ext_predef_outside_function);
3378     currentDecl = Context.getTranslationUnitDecl();
3379   }
3380 
3381   QualType ResTy;
3382   StringLiteral *SL = nullptr;
3383   if (cast<DeclContext>(currentDecl)->isDependentContext())
3384     ResTy = Context.DependentTy;
3385   else {
3386     // Pre-defined identifiers are of type char[x], where x is the length of
3387     // the string.
3388     auto Str = PredefinedExpr::ComputeName(IK, currentDecl);
3389     unsigned Length = Str.length();
3390 
3391     llvm::APInt LengthI(32, Length + 1);
3392     if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) {
3393       ResTy =
3394           Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst());
3395       SmallString<32> RawChars;
3396       ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3397                               Str, RawChars);
3398       ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3399                                            ArrayType::Normal,
3400                                            /*IndexTypeQuals*/ 0);
3401       SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3402                                  /*Pascal*/ false, ResTy, Loc);
3403     } else {
3404       ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
3405       ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3406                                            ArrayType::Normal,
3407                                            /*IndexTypeQuals*/ 0);
3408       SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3409                                  /*Pascal*/ false, ResTy, Loc);
3410     }
3411   }
3412 
3413   return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL);
3414 }
3415 
3416 static std::pair<QualType, StringLiteral *>
3417 GetUniqueStableNameInfo(ASTContext &Context, QualType OpType,
3418                         SourceLocation OpLoc, PredefinedExpr::IdentKind K) {
3419   std::pair<QualType, StringLiteral*> Result{{}, nullptr};
3420 
3421   if (OpType->isDependentType()) {
3422       Result.first = Context.DependentTy;
3423       return Result;
3424   }
3425 
3426   std::string Str = PredefinedExpr::ComputeName(Context, K, OpType);
3427   llvm::APInt Length(32, Str.length() + 1);
3428   Result.first =
3429       Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
3430   Result.first = Context.getConstantArrayType(
3431       Result.first, Length, nullptr, ArrayType::Normal, /*IndexTypeQuals*/ 0);
3432   Result.second = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3433                                         /*Pascal*/ false, Result.first, OpLoc);
3434   return Result;
3435 }
3436 
3437 ExprResult Sema::BuildUniqueStableName(SourceLocation OpLoc,
3438                                        TypeSourceInfo *Operand) {
3439   QualType ResultTy;
3440   StringLiteral *SL;
3441   std::tie(ResultTy, SL) = GetUniqueStableNameInfo(
3442       Context, Operand->getType(), OpLoc, PredefinedExpr::UniqueStableNameType);
3443 
3444   return PredefinedExpr::Create(Context, OpLoc, ResultTy,
3445                                 PredefinedExpr::UniqueStableNameType, SL,
3446                                 Operand);
3447 }
3448 
3449 ExprResult Sema::BuildUniqueStableName(SourceLocation OpLoc,
3450                                        Expr *E) {
3451   QualType ResultTy;
3452   StringLiteral *SL;
3453   std::tie(ResultTy, SL) = GetUniqueStableNameInfo(
3454       Context, E->getType(), OpLoc, PredefinedExpr::UniqueStableNameExpr);
3455 
3456   return PredefinedExpr::Create(Context, OpLoc, ResultTy,
3457                                 PredefinedExpr::UniqueStableNameExpr, SL, E);
3458 }
3459 
3460 ExprResult Sema::ActOnUniqueStableNameExpr(SourceLocation OpLoc,
3461                                            SourceLocation L, SourceLocation R,
3462                                            ParsedType Ty) {
3463   TypeSourceInfo *TInfo = nullptr;
3464   QualType T = GetTypeFromParser(Ty, &TInfo);
3465 
3466   if (T.isNull())
3467     return ExprError();
3468   if (!TInfo)
3469     TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
3470 
3471   return BuildUniqueStableName(OpLoc, TInfo);
3472 }
3473 
3474 ExprResult Sema::ActOnUniqueStableNameExpr(SourceLocation OpLoc,
3475                                            SourceLocation L, SourceLocation R,
3476                                            Expr *E) {
3477   return BuildUniqueStableName(OpLoc, E);
3478 }
3479 
3480 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3481   PredefinedExpr::IdentKind IK;
3482 
3483   switch (Kind) {
3484   default: llvm_unreachable("Unknown simple primary expr!");
3485   case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3486   case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break;
3487   case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS]
3488   case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS]
3489   case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS]
3490   case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS]
3491   case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break;
3492   }
3493 
3494   return BuildPredefinedExpr(Loc, IK);
3495 }
3496 
3497 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3498   SmallString<16> CharBuffer;
3499   bool Invalid = false;
3500   StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3501   if (Invalid)
3502     return ExprError();
3503 
3504   CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3505                             PP, Tok.getKind());
3506   if (Literal.hadError())
3507     return ExprError();
3508 
3509   QualType Ty;
3510   if (Literal.isWide())
3511     Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3512   else if (Literal.isUTF8() && getLangOpts().Char8)
3513     Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3514   else if (Literal.isUTF16())
3515     Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3516   else if (Literal.isUTF32())
3517     Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3518   else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3519     Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
3520   else
3521     Ty = Context.CharTy;  // 'x' -> char in C++
3522 
3523   CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3524   if (Literal.isWide())
3525     Kind = CharacterLiteral::Wide;
3526   else if (Literal.isUTF16())
3527     Kind = CharacterLiteral::UTF16;
3528   else if (Literal.isUTF32())
3529     Kind = CharacterLiteral::UTF32;
3530   else if (Literal.isUTF8())
3531     Kind = CharacterLiteral::UTF8;
3532 
3533   Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3534                                              Tok.getLocation());
3535 
3536   if (Literal.getUDSuffix().empty())
3537     return Lit;
3538 
3539   // We're building a user-defined literal.
3540   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3541   SourceLocation UDSuffixLoc =
3542     getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3543 
3544   // Make sure we're allowed user-defined literals here.
3545   if (!UDLScope)
3546     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3547 
3548   // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3549   //   operator "" X (ch)
3550   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3551                                         Lit, Tok.getLocation());
3552 }
3553 
3554 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3555   unsigned IntSize = Context.getTargetInfo().getIntWidth();
3556   return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3557                                 Context.IntTy, Loc);
3558 }
3559 
3560 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3561                                   QualType Ty, SourceLocation Loc) {
3562   const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3563 
3564   using llvm::APFloat;
3565   APFloat Val(Format);
3566 
3567   APFloat::opStatus result = Literal.GetFloatValue(Val);
3568 
3569   // Overflow is always an error, but underflow is only an error if
3570   // we underflowed to zero (APFloat reports denormals as underflow).
3571   if ((result & APFloat::opOverflow) ||
3572       ((result & APFloat::opUnderflow) && Val.isZero())) {
3573     unsigned diagnostic;
3574     SmallString<20> buffer;
3575     if (result & APFloat::opOverflow) {
3576       diagnostic = diag::warn_float_overflow;
3577       APFloat::getLargest(Format).toString(buffer);
3578     } else {
3579       diagnostic = diag::warn_float_underflow;
3580       APFloat::getSmallest(Format).toString(buffer);
3581     }
3582 
3583     S.Diag(Loc, diagnostic)
3584       << Ty
3585       << StringRef(buffer.data(), buffer.size());
3586   }
3587 
3588   bool isExact = (result == APFloat::opOK);
3589   return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3590 }
3591 
3592 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3593   assert(E && "Invalid expression");
3594 
3595   if (E->isValueDependent())
3596     return false;
3597 
3598   QualType QT = E->getType();
3599   if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3600     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3601     return true;
3602   }
3603 
3604   llvm::APSInt ValueAPS;
3605   ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3606 
3607   if (R.isInvalid())
3608     return true;
3609 
3610   bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3611   if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3612     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3613         << ValueAPS.toString(10) << ValueIsPositive;
3614     return true;
3615   }
3616 
3617   return false;
3618 }
3619 
3620 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3621   // Fast path for a single digit (which is quite common).  A single digit
3622   // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3623   if (Tok.getLength() == 1) {
3624     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3625     return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3626   }
3627 
3628   SmallString<128> SpellingBuffer;
3629   // NumericLiteralParser wants to overread by one character.  Add padding to
3630   // the buffer in case the token is copied to the buffer.  If getSpelling()
3631   // returns a StringRef to the memory buffer, it should have a null char at
3632   // the EOF, so it is also safe.
3633   SpellingBuffer.resize(Tok.getLength() + 1);
3634 
3635   // Get the spelling of the token, which eliminates trigraphs, etc.
3636   bool Invalid = false;
3637   StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3638   if (Invalid)
3639     return ExprError();
3640 
3641   NumericLiteralParser Literal(TokSpelling, Tok.getLocation(),
3642                                PP.getSourceManager(), PP.getLangOpts(),
3643                                PP.getTargetInfo(), PP.getDiagnostics());
3644   if (Literal.hadError)
3645     return ExprError();
3646 
3647   if (Literal.hasUDSuffix()) {
3648     // We're building a user-defined literal.
3649     IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3650     SourceLocation UDSuffixLoc =
3651       getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3652 
3653     // Make sure we're allowed user-defined literals here.
3654     if (!UDLScope)
3655       return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3656 
3657     QualType CookedTy;
3658     if (Literal.isFloatingLiteral()) {
3659       // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3660       // long double, the literal is treated as a call of the form
3661       //   operator "" X (f L)
3662       CookedTy = Context.LongDoubleTy;
3663     } else {
3664       // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3665       // unsigned long long, the literal is treated as a call of the form
3666       //   operator "" X (n ULL)
3667       CookedTy = Context.UnsignedLongLongTy;
3668     }
3669 
3670     DeclarationName OpName =
3671       Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3672     DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3673     OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3674 
3675     SourceLocation TokLoc = Tok.getLocation();
3676 
3677     // Perform literal operator lookup to determine if we're building a raw
3678     // literal or a cooked one.
3679     LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3680     switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3681                                   /*AllowRaw*/ true, /*AllowTemplate*/ true,
3682                                   /*AllowStringTemplate*/ false,
3683                                   /*DiagnoseMissing*/ !Literal.isImaginary)) {
3684     case LOLR_ErrorNoDiagnostic:
3685       // Lookup failure for imaginary constants isn't fatal, there's still the
3686       // GNU extension producing _Complex types.
3687       break;
3688     case LOLR_Error:
3689       return ExprError();
3690     case LOLR_Cooked: {
3691       Expr *Lit;
3692       if (Literal.isFloatingLiteral()) {
3693         Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3694       } else {
3695         llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3696         if (Literal.GetIntegerValue(ResultVal))
3697           Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3698               << /* Unsigned */ 1;
3699         Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3700                                      Tok.getLocation());
3701       }
3702       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3703     }
3704 
3705     case LOLR_Raw: {
3706       // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3707       // literal is treated as a call of the form
3708       //   operator "" X ("n")
3709       unsigned Length = Literal.getUDSuffixOffset();
3710       QualType StrTy = Context.getConstantArrayType(
3711           Context.adjustStringLiteralBaseType(Context.CharTy.withConst()),
3712           llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0);
3713       Expr *Lit = StringLiteral::Create(
3714           Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3715           /*Pascal*/false, StrTy, &TokLoc, 1);
3716       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3717     }
3718 
3719     case LOLR_Template: {
3720       // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3721       // template), L is treated as a call fo the form
3722       //   operator "" X <'c1', 'c2', ... 'ck'>()
3723       // where n is the source character sequence c1 c2 ... ck.
3724       TemplateArgumentListInfo ExplicitArgs;
3725       unsigned CharBits = Context.getIntWidth(Context.CharTy);
3726       bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3727       llvm::APSInt Value(CharBits, CharIsUnsigned);
3728       for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3729         Value = TokSpelling[I];
3730         TemplateArgument Arg(Context, Value, Context.CharTy);
3731         TemplateArgumentLocInfo ArgInfo;
3732         ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3733       }
3734       return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3735                                       &ExplicitArgs);
3736     }
3737     case LOLR_StringTemplate:
3738       llvm_unreachable("unexpected literal operator lookup result");
3739     }
3740   }
3741 
3742   Expr *Res;
3743 
3744   if (Literal.isFixedPointLiteral()) {
3745     QualType Ty;
3746 
3747     if (Literal.isAccum) {
3748       if (Literal.isHalf) {
3749         Ty = Context.ShortAccumTy;
3750       } else if (Literal.isLong) {
3751         Ty = Context.LongAccumTy;
3752       } else {
3753         Ty = Context.AccumTy;
3754       }
3755     } else if (Literal.isFract) {
3756       if (Literal.isHalf) {
3757         Ty = Context.ShortFractTy;
3758       } else if (Literal.isLong) {
3759         Ty = Context.LongFractTy;
3760       } else {
3761         Ty = Context.FractTy;
3762       }
3763     }
3764 
3765     if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
3766 
3767     bool isSigned = !Literal.isUnsigned;
3768     unsigned scale = Context.getFixedPointScale(Ty);
3769     unsigned bit_width = Context.getTypeInfo(Ty).Width;
3770 
3771     llvm::APInt Val(bit_width, 0, isSigned);
3772     bool Overflowed = Literal.GetFixedPointValue(Val, scale);
3773     bool ValIsZero = Val.isNullValue() && !Overflowed;
3774 
3775     auto MaxVal = Context.getFixedPointMax(Ty).getValue();
3776     if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
3777       // Clause 6.4.4 - The value of a constant shall be in the range of
3778       // representable values for its type, with exception for constants of a
3779       // fract type with a value of exactly 1; such a constant shall denote
3780       // the maximal value for the type.
3781       --Val;
3782     else if (Val.ugt(MaxVal) || Overflowed)
3783       Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
3784 
3785     Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty,
3786                                               Tok.getLocation(), scale);
3787   } else if (Literal.isFloatingLiteral()) {
3788     QualType Ty;
3789     if (Literal.isHalf){
3790       if (getOpenCLOptions().isEnabled("cl_khr_fp16"))
3791         Ty = Context.HalfTy;
3792       else {
3793         Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3794         return ExprError();
3795       }
3796     } else if (Literal.isFloat)
3797       Ty = Context.FloatTy;
3798     else if (Literal.isLong)
3799       Ty = Context.LongDoubleTy;
3800     else if (Literal.isFloat16)
3801       Ty = Context.Float16Ty;
3802     else if (Literal.isFloat128)
3803       Ty = Context.Float128Ty;
3804     else
3805       Ty = Context.DoubleTy;
3806 
3807     Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3808 
3809     if (Ty == Context.DoubleTy) {
3810       if (getLangOpts().SinglePrecisionConstants) {
3811         const BuiltinType *BTy = Ty->getAs<BuiltinType>();
3812         if (BTy->getKind() != BuiltinType::Float) {
3813           Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3814         }
3815       } else if (getLangOpts().OpenCL &&
3816                  !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
3817         // Impose single-precision float type when cl_khr_fp64 is not enabled.
3818         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
3819         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3820       }
3821     }
3822   } else if (!Literal.isIntegerLiteral()) {
3823     return ExprError();
3824   } else {
3825     QualType Ty;
3826 
3827     // 'long long' is a C99 or C++11 feature.
3828     if (!getLangOpts().C99 && Literal.isLongLong) {
3829       if (getLangOpts().CPlusPlus)
3830         Diag(Tok.getLocation(),
3831              getLangOpts().CPlusPlus11 ?
3832              diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3833       else
3834         Diag(Tok.getLocation(), diag::ext_c99_longlong);
3835     }
3836 
3837     // Get the value in the widest-possible width.
3838     unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3839     llvm::APInt ResultVal(MaxWidth, 0);
3840 
3841     if (Literal.GetIntegerValue(ResultVal)) {
3842       // If this value didn't fit into uintmax_t, error and force to ull.
3843       Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3844           << /* Unsigned */ 1;
3845       Ty = Context.UnsignedLongLongTy;
3846       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3847              "long long is not intmax_t?");
3848     } else {
3849       // If this value fits into a ULL, try to figure out what else it fits into
3850       // according to the rules of C99 6.4.4.1p5.
3851 
3852       // Octal, Hexadecimal, and integers with a U suffix are allowed to
3853       // be an unsigned int.
3854       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3855 
3856       // Check from smallest to largest, picking the smallest type we can.
3857       unsigned Width = 0;
3858 
3859       // Microsoft specific integer suffixes are explicitly sized.
3860       if (Literal.MicrosoftInteger) {
3861         if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3862           Width = 8;
3863           Ty = Context.CharTy;
3864         } else {
3865           Width = Literal.MicrosoftInteger;
3866           Ty = Context.getIntTypeForBitwidth(Width,
3867                                              /*Signed=*/!Literal.isUnsigned);
3868         }
3869       }
3870 
3871       if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
3872         // Are int/unsigned possibilities?
3873         unsigned IntSize = Context.getTargetInfo().getIntWidth();
3874 
3875         // Does it fit in a unsigned int?
3876         if (ResultVal.isIntN(IntSize)) {
3877           // Does it fit in a signed int?
3878           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3879             Ty = Context.IntTy;
3880           else if (AllowUnsigned)
3881             Ty = Context.UnsignedIntTy;
3882           Width = IntSize;
3883         }
3884       }
3885 
3886       // Are long/unsigned long possibilities?
3887       if (Ty.isNull() && !Literal.isLongLong) {
3888         unsigned LongSize = Context.getTargetInfo().getLongWidth();
3889 
3890         // Does it fit in a unsigned long?
3891         if (ResultVal.isIntN(LongSize)) {
3892           // Does it fit in a signed long?
3893           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3894             Ty = Context.LongTy;
3895           else if (AllowUnsigned)
3896             Ty = Context.UnsignedLongTy;
3897           // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
3898           // is compatible.
3899           else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
3900             const unsigned LongLongSize =
3901                 Context.getTargetInfo().getLongLongWidth();
3902             Diag(Tok.getLocation(),
3903                  getLangOpts().CPlusPlus
3904                      ? Literal.isLong
3905                            ? diag::warn_old_implicitly_unsigned_long_cxx
3906                            : /*C++98 UB*/ diag::
3907                                  ext_old_implicitly_unsigned_long_cxx
3908                      : diag::warn_old_implicitly_unsigned_long)
3909                 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
3910                                             : /*will be ill-formed*/ 1);
3911             Ty = Context.UnsignedLongTy;
3912           }
3913           Width = LongSize;
3914         }
3915       }
3916 
3917       // Check long long if needed.
3918       if (Ty.isNull()) {
3919         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3920 
3921         // Does it fit in a unsigned long long?
3922         if (ResultVal.isIntN(LongLongSize)) {
3923           // Does it fit in a signed long long?
3924           // To be compatible with MSVC, hex integer literals ending with the
3925           // LL or i64 suffix are always signed in Microsoft mode.
3926           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3927               (getLangOpts().MSVCCompat && Literal.isLongLong)))
3928             Ty = Context.LongLongTy;
3929           else if (AllowUnsigned)
3930             Ty = Context.UnsignedLongLongTy;
3931           Width = LongLongSize;
3932         }
3933       }
3934 
3935       // If we still couldn't decide a type, we probably have something that
3936       // does not fit in a signed long long, but has no U suffix.
3937       if (Ty.isNull()) {
3938         Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
3939         Ty = Context.UnsignedLongLongTy;
3940         Width = Context.getTargetInfo().getLongLongWidth();
3941       }
3942 
3943       if (ResultVal.getBitWidth() != Width)
3944         ResultVal = ResultVal.trunc(Width);
3945     }
3946     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3947   }
3948 
3949   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3950   if (Literal.isImaginary) {
3951     Res = new (Context) ImaginaryLiteral(Res,
3952                                         Context.getComplexType(Res->getType()));
3953 
3954     Diag(Tok.getLocation(), diag::ext_imaginary_constant);
3955   }
3956   return Res;
3957 }
3958 
3959 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
3960   assert(E && "ActOnParenExpr() missing expr");
3961   return new (Context) ParenExpr(L, R, E);
3962 }
3963 
3964 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3965                                          SourceLocation Loc,
3966                                          SourceRange ArgRange) {
3967   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3968   // scalar or vector data type argument..."
3969   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3970   // type (C99 6.2.5p18) or void.
3971   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3972     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3973       << T << ArgRange;
3974     return true;
3975   }
3976 
3977   assert((T->isVoidType() || !T->isIncompleteType()) &&
3978          "Scalar types should always be complete");
3979   return false;
3980 }
3981 
3982 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3983                                            SourceLocation Loc,
3984                                            SourceRange ArgRange,
3985                                            UnaryExprOrTypeTrait TraitKind) {
3986   // Invalid types must be hard errors for SFINAE in C++.
3987   if (S.LangOpts.CPlusPlus)
3988     return true;
3989 
3990   // C99 6.5.3.4p1:
3991   if (T->isFunctionType() &&
3992       (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
3993        TraitKind == UETT_PreferredAlignOf)) {
3994     // sizeof(function)/alignof(function) is allowed as an extension.
3995     S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3996         << getTraitSpelling(TraitKind) << ArgRange;
3997     return false;
3998   }
3999 
4000   // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
4001   // this is an error (OpenCL v1.1 s6.3.k)
4002   if (T->isVoidType()) {
4003     unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
4004                                         : diag::ext_sizeof_alignof_void_type;
4005     S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange;
4006     return false;
4007   }
4008 
4009   return true;
4010 }
4011 
4012 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
4013                                              SourceLocation Loc,
4014                                              SourceRange ArgRange,
4015                                              UnaryExprOrTypeTrait TraitKind) {
4016   // Reject sizeof(interface) and sizeof(interface<proto>) if the
4017   // runtime doesn't allow it.
4018   if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
4019     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
4020       << T << (TraitKind == UETT_SizeOf)
4021       << ArgRange;
4022     return true;
4023   }
4024 
4025   return false;
4026 }
4027 
4028 /// Check whether E is a pointer from a decayed array type (the decayed
4029 /// pointer type is equal to T) and emit a warning if it is.
4030 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
4031                                      Expr *E) {
4032   // Don't warn if the operation changed the type.
4033   if (T != E->getType())
4034     return;
4035 
4036   // Now look for array decays.
4037   ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
4038   if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
4039     return;
4040 
4041   S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
4042                                              << ICE->getType()
4043                                              << ICE->getSubExpr()->getType();
4044 }
4045 
4046 /// Check the constraints on expression operands to unary type expression
4047 /// and type traits.
4048 ///
4049 /// Completes any types necessary and validates the constraints on the operand
4050 /// expression. The logic mostly mirrors the type-based overload, but may modify
4051 /// the expression as it completes the type for that expression through template
4052 /// instantiation, etc.
4053 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
4054                                             UnaryExprOrTypeTrait ExprKind) {
4055   QualType ExprTy = E->getType();
4056   assert(!ExprTy->isReferenceType());
4057 
4058   bool IsUnevaluatedOperand =
4059       (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf ||
4060        ExprKind == UETT_PreferredAlignOf);
4061   if (IsUnevaluatedOperand) {
4062     ExprResult Result = CheckUnevaluatedOperand(E);
4063     if (Result.isInvalid())
4064       return true;
4065     E = Result.get();
4066   }
4067 
4068   if (ExprKind == UETT_VecStep)
4069     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
4070                                         E->getSourceRange());
4071 
4072   // Explicitly list some types as extensions.
4073   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
4074                                       E->getSourceRange(), ExprKind))
4075     return false;
4076 
4077   // 'alignof' applied to an expression only requires the base element type of
4078   // the expression to be complete. 'sizeof' requires the expression's type to
4079   // be complete (and will attempt to complete it if it's an array of unknown
4080   // bound).
4081   if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4082     if (RequireCompleteSizedType(
4083             E->getExprLoc(), Context.getBaseElementType(E->getType()),
4084             diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4085             getTraitSpelling(ExprKind), E->getSourceRange()))
4086       return true;
4087   } else {
4088     if (RequireCompleteSizedExprType(
4089             E, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4090             getTraitSpelling(ExprKind), E->getSourceRange()))
4091       return true;
4092   }
4093 
4094   // Completing the expression's type may have changed it.
4095   ExprTy = E->getType();
4096   assert(!ExprTy->isReferenceType());
4097 
4098   if (ExprTy->isFunctionType()) {
4099     Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
4100         << getTraitSpelling(ExprKind) << E->getSourceRange();
4101     return true;
4102   }
4103 
4104   // The operand for sizeof and alignof is in an unevaluated expression context,
4105   // so side effects could result in unintended consequences.
4106   if (IsUnevaluatedOperand && !inTemplateInstantiation() &&
4107       E->HasSideEffects(Context, false))
4108     Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
4109 
4110   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
4111                                        E->getSourceRange(), ExprKind))
4112     return true;
4113 
4114   if (ExprKind == UETT_SizeOf) {
4115     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
4116       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
4117         QualType OType = PVD->getOriginalType();
4118         QualType Type = PVD->getType();
4119         if (Type->isPointerType() && OType->isArrayType()) {
4120           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
4121             << Type << OType;
4122           Diag(PVD->getLocation(), diag::note_declared_at);
4123         }
4124       }
4125     }
4126 
4127     // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
4128     // decays into a pointer and returns an unintended result. This is most
4129     // likely a typo for "sizeof(array) op x".
4130     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
4131       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4132                                BO->getLHS());
4133       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4134                                BO->getRHS());
4135     }
4136   }
4137 
4138   return false;
4139 }
4140 
4141 /// Check the constraints on operands to unary expression and type
4142 /// traits.
4143 ///
4144 /// This will complete any types necessary, and validate the various constraints
4145 /// on those operands.
4146 ///
4147 /// The UsualUnaryConversions() function is *not* called by this routine.
4148 /// C99 6.3.2.1p[2-4] all state:
4149 ///   Except when it is the operand of the sizeof operator ...
4150 ///
4151 /// C++ [expr.sizeof]p4
4152 ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
4153 ///   standard conversions are not applied to the operand of sizeof.
4154 ///
4155 /// This policy is followed for all of the unary trait expressions.
4156 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
4157                                             SourceLocation OpLoc,
4158                                             SourceRange ExprRange,
4159                                             UnaryExprOrTypeTrait ExprKind) {
4160   if (ExprType->isDependentType())
4161     return false;
4162 
4163   // C++ [expr.sizeof]p2:
4164   //     When applied to a reference or a reference type, the result
4165   //     is the size of the referenced type.
4166   // C++11 [expr.alignof]p3:
4167   //     When alignof is applied to a reference type, the result
4168   //     shall be the alignment of the referenced type.
4169   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
4170     ExprType = Ref->getPointeeType();
4171 
4172   // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
4173   //   When alignof or _Alignof is applied to an array type, the result
4174   //   is the alignment of the element type.
4175   if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4176       ExprKind == UETT_OpenMPRequiredSimdAlign)
4177     ExprType = Context.getBaseElementType(ExprType);
4178 
4179   if (ExprKind == UETT_VecStep)
4180     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
4181 
4182   // Explicitly list some types as extensions.
4183   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
4184                                       ExprKind))
4185     return false;
4186 
4187   if (RequireCompleteSizedType(
4188           OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4189           getTraitSpelling(ExprKind), ExprRange))
4190     return true;
4191 
4192   if (ExprType->isFunctionType()) {
4193     Diag(OpLoc, diag::err_sizeof_alignof_function_type)
4194         << getTraitSpelling(ExprKind) << ExprRange;
4195     return true;
4196   }
4197 
4198   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
4199                                        ExprKind))
4200     return true;
4201 
4202   return false;
4203 }
4204 
4205 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
4206   // Cannot know anything else if the expression is dependent.
4207   if (E->isTypeDependent())
4208     return false;
4209 
4210   if (E->getObjectKind() == OK_BitField) {
4211     S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
4212        << 1 << E->getSourceRange();
4213     return true;
4214   }
4215 
4216   ValueDecl *D = nullptr;
4217   Expr *Inner = E->IgnoreParens();
4218   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) {
4219     D = DRE->getDecl();
4220   } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) {
4221     D = ME->getMemberDecl();
4222   }
4223 
4224   // If it's a field, require the containing struct to have a
4225   // complete definition so that we can compute the layout.
4226   //
4227   // This can happen in C++11 onwards, either by naming the member
4228   // in a way that is not transformed into a member access expression
4229   // (in an unevaluated operand, for instance), or by naming the member
4230   // in a trailing-return-type.
4231   //
4232   // For the record, since __alignof__ on expressions is a GCC
4233   // extension, GCC seems to permit this but always gives the
4234   // nonsensical answer 0.
4235   //
4236   // We don't really need the layout here --- we could instead just
4237   // directly check for all the appropriate alignment-lowing
4238   // attributes --- but that would require duplicating a lot of
4239   // logic that just isn't worth duplicating for such a marginal
4240   // use-case.
4241   if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
4242     // Fast path this check, since we at least know the record has a
4243     // definition if we can find a member of it.
4244     if (!FD->getParent()->isCompleteDefinition()) {
4245       S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
4246         << E->getSourceRange();
4247       return true;
4248     }
4249 
4250     // Otherwise, if it's a field, and the field doesn't have
4251     // reference type, then it must have a complete type (or be a
4252     // flexible array member, which we explicitly want to
4253     // white-list anyway), which makes the following checks trivial.
4254     if (!FD->getType()->isReferenceType())
4255       return false;
4256   }
4257 
4258   return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4259 }
4260 
4261 bool Sema::CheckVecStepExpr(Expr *E) {
4262   E = E->IgnoreParens();
4263 
4264   // Cannot know anything else if the expression is dependent.
4265   if (E->isTypeDependent())
4266     return false;
4267 
4268   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
4269 }
4270 
4271 static void captureVariablyModifiedType(ASTContext &Context, QualType T,
4272                                         CapturingScopeInfo *CSI) {
4273   assert(T->isVariablyModifiedType());
4274   assert(CSI != nullptr);
4275 
4276   // We're going to walk down into the type and look for VLA expressions.
4277   do {
4278     const Type *Ty = T.getTypePtr();
4279     switch (Ty->getTypeClass()) {
4280 #define TYPE(Class, Base)
4281 #define ABSTRACT_TYPE(Class, Base)
4282 #define NON_CANONICAL_TYPE(Class, Base)
4283 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
4284 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4285 #include "clang/AST/TypeNodes.inc"
4286       T = QualType();
4287       break;
4288     // These types are never variably-modified.
4289     case Type::Builtin:
4290     case Type::Complex:
4291     case Type::Vector:
4292     case Type::ExtVector:
4293     case Type::ConstantMatrix:
4294     case Type::Record:
4295     case Type::Enum:
4296     case Type::Elaborated:
4297     case Type::TemplateSpecialization:
4298     case Type::ObjCObject:
4299     case Type::ObjCInterface:
4300     case Type::ObjCObjectPointer:
4301     case Type::ObjCTypeParam:
4302     case Type::Pipe:
4303     case Type::ExtInt:
4304       llvm_unreachable("type class is never variably-modified!");
4305     case Type::Adjusted:
4306       T = cast<AdjustedType>(Ty)->getOriginalType();
4307       break;
4308     case Type::Decayed:
4309       T = cast<DecayedType>(Ty)->getPointeeType();
4310       break;
4311     case Type::Pointer:
4312       T = cast<PointerType>(Ty)->getPointeeType();
4313       break;
4314     case Type::BlockPointer:
4315       T = cast<BlockPointerType>(Ty)->getPointeeType();
4316       break;
4317     case Type::LValueReference:
4318     case Type::RValueReference:
4319       T = cast<ReferenceType>(Ty)->getPointeeType();
4320       break;
4321     case Type::MemberPointer:
4322       T = cast<MemberPointerType>(Ty)->getPointeeType();
4323       break;
4324     case Type::ConstantArray:
4325     case Type::IncompleteArray:
4326       // Losing element qualification here is fine.
4327       T = cast<ArrayType>(Ty)->getElementType();
4328       break;
4329     case Type::VariableArray: {
4330       // Losing element qualification here is fine.
4331       const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
4332 
4333       // Unknown size indication requires no size computation.
4334       // Otherwise, evaluate and record it.
4335       auto Size = VAT->getSizeExpr();
4336       if (Size && !CSI->isVLATypeCaptured(VAT) &&
4337           (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI)))
4338         CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType());
4339 
4340       T = VAT->getElementType();
4341       break;
4342     }
4343     case Type::FunctionProto:
4344     case Type::FunctionNoProto:
4345       T = cast<FunctionType>(Ty)->getReturnType();
4346       break;
4347     case Type::Paren:
4348     case Type::TypeOf:
4349     case Type::UnaryTransform:
4350     case Type::Attributed:
4351     case Type::SubstTemplateTypeParm:
4352     case Type::MacroQualified:
4353       // Keep walking after single level desugaring.
4354       T = T.getSingleStepDesugaredType(Context);
4355       break;
4356     case Type::Typedef:
4357       T = cast<TypedefType>(Ty)->desugar();
4358       break;
4359     case Type::Decltype:
4360       T = cast<DecltypeType>(Ty)->desugar();
4361       break;
4362     case Type::Auto:
4363     case Type::DeducedTemplateSpecialization:
4364       T = cast<DeducedType>(Ty)->getDeducedType();
4365       break;
4366     case Type::TypeOfExpr:
4367       T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
4368       break;
4369     case Type::Atomic:
4370       T = cast<AtomicType>(Ty)->getValueType();
4371       break;
4372     }
4373   } while (!T.isNull() && T->isVariablyModifiedType());
4374 }
4375 
4376 /// Build a sizeof or alignof expression given a type operand.
4377 ExprResult
4378 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4379                                      SourceLocation OpLoc,
4380                                      UnaryExprOrTypeTrait ExprKind,
4381                                      SourceRange R) {
4382   if (!TInfo)
4383     return ExprError();
4384 
4385   QualType T = TInfo->getType();
4386 
4387   if (!T->isDependentType() &&
4388       CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
4389     return ExprError();
4390 
4391   if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4392     if (auto *TT = T->getAs<TypedefType>()) {
4393       for (auto I = FunctionScopes.rbegin(),
4394                 E = std::prev(FunctionScopes.rend());
4395            I != E; ++I) {
4396         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4397         if (CSI == nullptr)
4398           break;
4399         DeclContext *DC = nullptr;
4400         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4401           DC = LSI->CallOperator;
4402         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4403           DC = CRSI->TheCapturedDecl;
4404         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4405           DC = BSI->TheDecl;
4406         if (DC) {
4407           if (DC->containsDecl(TT->getDecl()))
4408             break;
4409           captureVariablyModifiedType(Context, T, CSI);
4410         }
4411       }
4412     }
4413   }
4414 
4415   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4416   return new (Context) UnaryExprOrTypeTraitExpr(
4417       ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4418 }
4419 
4420 /// Build a sizeof or alignof expression given an expression
4421 /// operand.
4422 ExprResult
4423 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4424                                      UnaryExprOrTypeTrait ExprKind) {
4425   ExprResult PE = CheckPlaceholderExpr(E);
4426   if (PE.isInvalid())
4427     return ExprError();
4428 
4429   E = PE.get();
4430 
4431   // Verify that the operand is valid.
4432   bool isInvalid = false;
4433   if (E->isTypeDependent()) {
4434     // Delay type-checking for type-dependent expressions.
4435   } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4436     isInvalid = CheckAlignOfExpr(*this, E, ExprKind);
4437   } else if (ExprKind == UETT_VecStep) {
4438     isInvalid = CheckVecStepExpr(E);
4439   } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4440       Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4441       isInvalid = true;
4442   } else if (E->refersToBitField()) {  // C99 6.5.3.4p1.
4443     Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4444     isInvalid = true;
4445   } else {
4446     isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
4447   }
4448 
4449   if (isInvalid)
4450     return ExprError();
4451 
4452   if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4453     PE = TransformToPotentiallyEvaluated(E);
4454     if (PE.isInvalid()) return ExprError();
4455     E = PE.get();
4456   }
4457 
4458   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4459   return new (Context) UnaryExprOrTypeTraitExpr(
4460       ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4461 }
4462 
4463 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4464 /// expr and the same for @c alignof and @c __alignof
4465 /// Note that the ArgRange is invalid if isType is false.
4466 ExprResult
4467 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4468                                     UnaryExprOrTypeTrait ExprKind, bool IsType,
4469                                     void *TyOrEx, SourceRange ArgRange) {
4470   // If error parsing type, ignore.
4471   if (!TyOrEx) return ExprError();
4472 
4473   if (IsType) {
4474     TypeSourceInfo *TInfo;
4475     (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4476     return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4477   }
4478 
4479   Expr *ArgEx = (Expr *)TyOrEx;
4480   ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4481   return Result;
4482 }
4483 
4484 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4485                                      bool IsReal) {
4486   if (V.get()->isTypeDependent())
4487     return S.Context.DependentTy;
4488 
4489   // _Real and _Imag are only l-values for normal l-values.
4490   if (V.get()->getObjectKind() != OK_Ordinary) {
4491     V = S.DefaultLvalueConversion(V.get());
4492     if (V.isInvalid())
4493       return QualType();
4494   }
4495 
4496   // These operators return the element type of a complex type.
4497   if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4498     return CT->getElementType();
4499 
4500   // Otherwise they pass through real integer and floating point types here.
4501   if (V.get()->getType()->isArithmeticType())
4502     return V.get()->getType();
4503 
4504   // Test for placeholders.
4505   ExprResult PR = S.CheckPlaceholderExpr(V.get());
4506   if (PR.isInvalid()) return QualType();
4507   if (PR.get() != V.get()) {
4508     V = PR;
4509     return CheckRealImagOperand(S, V, Loc, IsReal);
4510   }
4511 
4512   // Reject anything else.
4513   S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4514     << (IsReal ? "__real" : "__imag");
4515   return QualType();
4516 }
4517 
4518 
4519 
4520 ExprResult
4521 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4522                           tok::TokenKind Kind, Expr *Input) {
4523   UnaryOperatorKind Opc;
4524   switch (Kind) {
4525   default: llvm_unreachable("Unknown unary op!");
4526   case tok::plusplus:   Opc = UO_PostInc; break;
4527   case tok::minusminus: Opc = UO_PostDec; break;
4528   }
4529 
4530   // Since this might is a postfix expression, get rid of ParenListExprs.
4531   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4532   if (Result.isInvalid()) return ExprError();
4533   Input = Result.get();
4534 
4535   return BuildUnaryOp(S, OpLoc, Opc, Input);
4536 }
4537 
4538 /// Diagnose if arithmetic on the given ObjC pointer is illegal.
4539 ///
4540 /// \return true on error
4541 static bool checkArithmeticOnObjCPointer(Sema &S,
4542                                          SourceLocation opLoc,
4543                                          Expr *op) {
4544   assert(op->getType()->isObjCObjectPointerType());
4545   if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4546       !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4547     return false;
4548 
4549   S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4550     << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4551     << op->getSourceRange();
4552   return true;
4553 }
4554 
4555 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4556   auto *BaseNoParens = Base->IgnoreParens();
4557   if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4558     return MSProp->getPropertyDecl()->getType()->isArrayType();
4559   return isa<MSPropertySubscriptExpr>(BaseNoParens);
4560 }
4561 
4562 ExprResult
4563 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
4564                               Expr *idx, SourceLocation rbLoc) {
4565   if (base && !base->getType().isNull() &&
4566       base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection))
4567     return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
4568                                     SourceLocation(), /*Length*/ nullptr,
4569                                     /*Stride=*/nullptr, rbLoc);
4570 
4571   // Since this might be a postfix expression, get rid of ParenListExprs.
4572   if (isa<ParenListExpr>(base)) {
4573     ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4574     if (result.isInvalid()) return ExprError();
4575     base = result.get();
4576   }
4577 
4578   // Check if base and idx form a MatrixSubscriptExpr.
4579   //
4580   // Helper to check for comma expressions, which are not allowed as indices for
4581   // matrix subscript expressions.
4582   auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) {
4583     if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) {
4584       Diag(E->getExprLoc(), diag::err_matrix_subscript_comma)
4585           << SourceRange(base->getBeginLoc(), rbLoc);
4586       return true;
4587     }
4588     return false;
4589   };
4590   // The matrix subscript operator ([][])is considered a single operator.
4591   // Separating the index expressions by parenthesis is not allowed.
4592   if (base->getType()->isSpecificPlaceholderType(
4593           BuiltinType::IncompleteMatrixIdx) &&
4594       !isa<MatrixSubscriptExpr>(base)) {
4595     Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index)
4596         << SourceRange(base->getBeginLoc(), rbLoc);
4597     return ExprError();
4598   }
4599   // If the base is a MatrixSubscriptExpr, try to create a new
4600   // MatrixSubscriptExpr.
4601   auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base);
4602   if (matSubscriptE) {
4603     if (CheckAndReportCommaError(idx))
4604       return ExprError();
4605 
4606     assert(matSubscriptE->isIncomplete() &&
4607            "base has to be an incomplete matrix subscript");
4608     return CreateBuiltinMatrixSubscriptExpr(
4609         matSubscriptE->getBase(), matSubscriptE->getRowIdx(), idx, 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   bool IsMSPropertySubscript = false;
4618   if (base->getType()->isNonOverloadPlaceholderType()) {
4619     IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4620     if (!IsMSPropertySubscript) {
4621       ExprResult result = CheckPlaceholderExpr(base);
4622       if (result.isInvalid())
4623         return ExprError();
4624       base = result.get();
4625     }
4626   }
4627 
4628   // If the base is a matrix type, try to create a new MatrixSubscriptExpr.
4629   if (base->getType()->isMatrixType()) {
4630     if (CheckAndReportCommaError(idx))
4631       return ExprError();
4632 
4633     return CreateBuiltinMatrixSubscriptExpr(base, idx, nullptr, rbLoc);
4634   }
4635 
4636   // A comma-expression as the index is deprecated in C++2a onwards.
4637   if (getLangOpts().CPlusPlus20 &&
4638       ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) ||
4639        (isa<CXXOperatorCallExpr>(idx) &&
4640         cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma))) {
4641     Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript)
4642         << SourceRange(base->getBeginLoc(), rbLoc);
4643   }
4644 
4645   if (idx->getType()->isNonOverloadPlaceholderType()) {
4646     ExprResult result = CheckPlaceholderExpr(idx);
4647     if (result.isInvalid()) return ExprError();
4648     idx = result.get();
4649   }
4650 
4651   // Build an unanalyzed expression if either operand is type-dependent.
4652   if (getLangOpts().CPlusPlus &&
4653       (base->isTypeDependent() || idx->isTypeDependent())) {
4654     return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
4655                                             VK_LValue, OK_Ordinary, rbLoc);
4656   }
4657 
4658   // MSDN, property (C++)
4659   // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4660   // This attribute can also be used in the declaration of an empty array in a
4661   // class or structure definition. For example:
4662   // __declspec(property(get=GetX, put=PutX)) int x[];
4663   // The above statement indicates that x[] can be used with one or more array
4664   // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4665   // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4666   if (IsMSPropertySubscript) {
4667     // Build MS property subscript expression if base is MS property reference
4668     // or MS property subscript.
4669     return new (Context) MSPropertySubscriptExpr(
4670         base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
4671   }
4672 
4673   // Use C++ overloaded-operator rules if either operand has record
4674   // type.  The spec says to do this if either type is *overloadable*,
4675   // but enum types can't declare subscript operators or conversion
4676   // operators, so there's nothing interesting for overload resolution
4677   // to do if there aren't any record types involved.
4678   //
4679   // ObjC pointers have their own subscripting logic that is not tied
4680   // to overload resolution and so should not take this path.
4681   if (getLangOpts().CPlusPlus &&
4682       (base->getType()->isRecordType() ||
4683        (!base->getType()->isObjCObjectPointerType() &&
4684         idx->getType()->isRecordType()))) {
4685     return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
4686   }
4687 
4688   ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
4689 
4690   if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get()))
4691     CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get()));
4692 
4693   return Res;
4694 }
4695 
4696 ExprResult Sema::tryConvertExprToType(Expr *E, QualType Ty) {
4697   InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty);
4698   InitializationKind Kind =
4699       InitializationKind::CreateCopy(E->getBeginLoc(), SourceLocation());
4700   InitializationSequence InitSeq(*this, Entity, Kind, E);
4701   return InitSeq.Perform(*this, Entity, Kind, E);
4702 }
4703 
4704 ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx,
4705                                                   Expr *ColumnIdx,
4706                                                   SourceLocation RBLoc) {
4707   ExprResult BaseR = CheckPlaceholderExpr(Base);
4708   if (BaseR.isInvalid())
4709     return BaseR;
4710   Base = BaseR.get();
4711 
4712   ExprResult RowR = CheckPlaceholderExpr(RowIdx);
4713   if (RowR.isInvalid())
4714     return RowR;
4715   RowIdx = RowR.get();
4716 
4717   if (!ColumnIdx)
4718     return new (Context) MatrixSubscriptExpr(
4719         Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc);
4720 
4721   // Build an unanalyzed expression if any of the operands is type-dependent.
4722   if (Base->isTypeDependent() || RowIdx->isTypeDependent() ||
4723       ColumnIdx->isTypeDependent())
4724     return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
4725                                              Context.DependentTy, RBLoc);
4726 
4727   ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx);
4728   if (ColumnR.isInvalid())
4729     return ColumnR;
4730   ColumnIdx = ColumnR.get();
4731 
4732   // Check that IndexExpr is an integer expression. If it is a constant
4733   // expression, check that it is less than Dim (= the number of elements in the
4734   // corresponding dimension).
4735   auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim,
4736                           bool IsColumnIdx) -> Expr * {
4737     if (!IndexExpr->getType()->isIntegerType() &&
4738         !IndexExpr->isTypeDependent()) {
4739       Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer)
4740           << IsColumnIdx;
4741       return nullptr;
4742     }
4743 
4744     if (Optional<llvm::APSInt> Idx =
4745             IndexExpr->getIntegerConstantExpr(Context)) {
4746       if ((*Idx < 0 || *Idx >= Dim)) {
4747         Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range)
4748             << IsColumnIdx << Dim;
4749         return nullptr;
4750       }
4751     }
4752 
4753     ExprResult ConvExpr =
4754         tryConvertExprToType(IndexExpr, Context.getSizeType());
4755     assert(!ConvExpr.isInvalid() &&
4756            "should be able to convert any integer type to size type");
4757     return ConvExpr.get();
4758   };
4759 
4760   auto *MTy = Base->getType()->getAs<ConstantMatrixType>();
4761   RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false);
4762   ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true);
4763   if (!RowIdx || !ColumnIdx)
4764     return ExprError();
4765 
4766   return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
4767                                            MTy->getElementType(), RBLoc);
4768 }
4769 
4770 void Sema::CheckAddressOfNoDeref(const Expr *E) {
4771   ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4772   const Expr *StrippedExpr = E->IgnoreParenImpCasts();
4773 
4774   // For expressions like `&(*s).b`, the base is recorded and what should be
4775   // checked.
4776   const MemberExpr *Member = nullptr;
4777   while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow())
4778     StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
4779 
4780   LastRecord.PossibleDerefs.erase(StrippedExpr);
4781 }
4782 
4783 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
4784   QualType ResultTy = E->getType();
4785   ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4786 
4787   // Bail if the element is an array since it is not memory access.
4788   if (isa<ArrayType>(ResultTy))
4789     return;
4790 
4791   if (ResultTy->hasAttr(attr::NoDeref)) {
4792     LastRecord.PossibleDerefs.insert(E);
4793     return;
4794   }
4795 
4796   // Check if the base type is a pointer to a member access of a struct
4797   // marked with noderef.
4798   const Expr *Base = E->getBase();
4799   QualType BaseTy = Base->getType();
4800   if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy)))
4801     // Not a pointer access
4802     return;
4803 
4804   const MemberExpr *Member = nullptr;
4805   while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) &&
4806          Member->isArrow())
4807     Base = Member->getBase();
4808 
4809   if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) {
4810     if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))
4811       LastRecord.PossibleDerefs.insert(E);
4812   }
4813 }
4814 
4815 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4816                                           Expr *LowerBound,
4817                                           SourceLocation ColonLocFirst,
4818                                           SourceLocation ColonLocSecond,
4819                                           Expr *Length, Expr *Stride,
4820                                           SourceLocation RBLoc) {
4821   if (Base->getType()->isPlaceholderType() &&
4822       !Base->getType()->isSpecificPlaceholderType(
4823           BuiltinType::OMPArraySection)) {
4824     ExprResult Result = CheckPlaceholderExpr(Base);
4825     if (Result.isInvalid())
4826       return ExprError();
4827     Base = Result.get();
4828   }
4829   if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
4830     ExprResult Result = CheckPlaceholderExpr(LowerBound);
4831     if (Result.isInvalid())
4832       return ExprError();
4833     Result = DefaultLvalueConversion(Result.get());
4834     if (Result.isInvalid())
4835       return ExprError();
4836     LowerBound = Result.get();
4837   }
4838   if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
4839     ExprResult Result = CheckPlaceholderExpr(Length);
4840     if (Result.isInvalid())
4841       return ExprError();
4842     Result = DefaultLvalueConversion(Result.get());
4843     if (Result.isInvalid())
4844       return ExprError();
4845     Length = Result.get();
4846   }
4847   if (Stride && Stride->getType()->isNonOverloadPlaceholderType()) {
4848     ExprResult Result = CheckPlaceholderExpr(Stride);
4849     if (Result.isInvalid())
4850       return ExprError();
4851     Result = DefaultLvalueConversion(Result.get());
4852     if (Result.isInvalid())
4853       return ExprError();
4854     Stride = Result.get();
4855   }
4856 
4857   // Build an unanalyzed expression if either operand is type-dependent.
4858   if (Base->isTypeDependent() ||
4859       (LowerBound &&
4860        (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
4861       (Length && (Length->isTypeDependent() || Length->isValueDependent())) ||
4862       (Stride && (Stride->isTypeDependent() || Stride->isValueDependent()))) {
4863     return new (Context) OMPArraySectionExpr(
4864         Base, LowerBound, Length, Stride, Context.DependentTy, VK_LValue,
4865         OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc);
4866   }
4867 
4868   // Perform default conversions.
4869   QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
4870   QualType ResultTy;
4871   if (OriginalTy->isAnyPointerType()) {
4872     ResultTy = OriginalTy->getPointeeType();
4873   } else if (OriginalTy->isArrayType()) {
4874     ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
4875   } else {
4876     return ExprError(
4877         Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
4878         << Base->getSourceRange());
4879   }
4880   // C99 6.5.2.1p1
4881   if (LowerBound) {
4882     auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
4883                                                       LowerBound);
4884     if (Res.isInvalid())
4885       return ExprError(Diag(LowerBound->getExprLoc(),
4886                             diag::err_omp_typecheck_section_not_integer)
4887                        << 0 << LowerBound->getSourceRange());
4888     LowerBound = Res.get();
4889 
4890     if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4891         LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4892       Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
4893           << 0 << LowerBound->getSourceRange();
4894   }
4895   if (Length) {
4896     auto Res =
4897         PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
4898     if (Res.isInvalid())
4899       return ExprError(Diag(Length->getExprLoc(),
4900                             diag::err_omp_typecheck_section_not_integer)
4901                        << 1 << Length->getSourceRange());
4902     Length = Res.get();
4903 
4904     if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4905         Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4906       Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
4907           << 1 << Length->getSourceRange();
4908   }
4909   if (Stride) {
4910     ExprResult Res =
4911         PerformOpenMPImplicitIntegerConversion(Stride->getExprLoc(), Stride);
4912     if (Res.isInvalid())
4913       return ExprError(Diag(Stride->getExprLoc(),
4914                             diag::err_omp_typecheck_section_not_integer)
4915                        << 1 << Stride->getSourceRange());
4916     Stride = Res.get();
4917 
4918     if (Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4919         Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4920       Diag(Stride->getExprLoc(), diag::warn_omp_section_is_char)
4921           << 1 << Stride->getSourceRange();
4922   }
4923 
4924   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4925   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4926   // type. Note that functions are not objects, and that (in C99 parlance)
4927   // incomplete types are not object types.
4928   if (ResultTy->isFunctionType()) {
4929     Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
4930         << ResultTy << Base->getSourceRange();
4931     return ExprError();
4932   }
4933 
4934   if (RequireCompleteType(Base->getExprLoc(), ResultTy,
4935                           diag::err_omp_section_incomplete_type, Base))
4936     return ExprError();
4937 
4938   if (LowerBound && !OriginalTy->isAnyPointerType()) {
4939     Expr::EvalResult Result;
4940     if (LowerBound->EvaluateAsInt(Result, Context)) {
4941       // OpenMP 5.0, [2.1.5 Array Sections]
4942       // The array section must be a subset of the original array.
4943       llvm::APSInt LowerBoundValue = Result.Val.getInt();
4944       if (LowerBoundValue.isNegative()) {
4945         Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
4946             << LowerBound->getSourceRange();
4947         return ExprError();
4948       }
4949     }
4950   }
4951 
4952   if (Length) {
4953     Expr::EvalResult Result;
4954     if (Length->EvaluateAsInt(Result, Context)) {
4955       // OpenMP 5.0, [2.1.5 Array Sections]
4956       // The length must evaluate to non-negative integers.
4957       llvm::APSInt LengthValue = Result.Val.getInt();
4958       if (LengthValue.isNegative()) {
4959         Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
4960             << LengthValue.toString(/*Radix=*/10, /*Signed=*/true)
4961             << Length->getSourceRange();
4962         return ExprError();
4963       }
4964     }
4965   } else if (ColonLocFirst.isValid() &&
4966              (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
4967                                       !OriginalTy->isVariableArrayType()))) {
4968     // OpenMP 5.0, [2.1.5 Array Sections]
4969     // When the size of the array dimension is not known, the length must be
4970     // specified explicitly.
4971     Diag(ColonLocFirst, diag::err_omp_section_length_undefined)
4972         << (!OriginalTy.isNull() && OriginalTy->isArrayType());
4973     return ExprError();
4974   }
4975 
4976   if (Stride) {
4977     Expr::EvalResult Result;
4978     if (Stride->EvaluateAsInt(Result, Context)) {
4979       // OpenMP 5.0, [2.1.5 Array Sections]
4980       // The stride must evaluate to a positive integer.
4981       llvm::APSInt StrideValue = Result.Val.getInt();
4982       if (!StrideValue.isStrictlyPositive()) {
4983         Diag(Stride->getExprLoc(), diag::err_omp_section_stride_non_positive)
4984             << StrideValue.toString(/*Radix=*/10, /*Signed=*/true)
4985             << Stride->getSourceRange();
4986         return ExprError();
4987       }
4988     }
4989   }
4990 
4991   if (!Base->getType()->isSpecificPlaceholderType(
4992           BuiltinType::OMPArraySection)) {
4993     ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
4994     if (Result.isInvalid())
4995       return ExprError();
4996     Base = Result.get();
4997   }
4998   return new (Context) OMPArraySectionExpr(
4999       Base, LowerBound, Length, Stride, Context.OMPArraySectionTy, VK_LValue,
5000       OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc);
5001 }
5002 
5003 ExprResult Sema::ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc,
5004                                           SourceLocation RParenLoc,
5005                                           ArrayRef<Expr *> Dims,
5006                                           ArrayRef<SourceRange> Brackets) {
5007   if (Base->getType()->isPlaceholderType()) {
5008     ExprResult Result = CheckPlaceholderExpr(Base);
5009     if (Result.isInvalid())
5010       return ExprError();
5011     Result = DefaultLvalueConversion(Result.get());
5012     if (Result.isInvalid())
5013       return ExprError();
5014     Base = Result.get();
5015   }
5016   QualType BaseTy = Base->getType();
5017   // Delay analysis of the types/expressions if instantiation/specialization is
5018   // required.
5019   if (!BaseTy->isPointerType() && Base->isTypeDependent())
5020     return OMPArrayShapingExpr::Create(Context, Context.DependentTy, Base,
5021                                        LParenLoc, RParenLoc, Dims, Brackets);
5022   if (!BaseTy->isPointerType() ||
5023       (!Base->isTypeDependent() &&
5024        BaseTy->getPointeeType()->isIncompleteType()))
5025     return ExprError(Diag(Base->getExprLoc(),
5026                           diag::err_omp_non_pointer_type_array_shaping_base)
5027                      << Base->getSourceRange());
5028 
5029   SmallVector<Expr *, 4> NewDims;
5030   bool ErrorFound = false;
5031   for (Expr *Dim : Dims) {
5032     if (Dim->getType()->isPlaceholderType()) {
5033       ExprResult Result = CheckPlaceholderExpr(Dim);
5034       if (Result.isInvalid()) {
5035         ErrorFound = true;
5036         continue;
5037       }
5038       Result = DefaultLvalueConversion(Result.get());
5039       if (Result.isInvalid()) {
5040         ErrorFound = true;
5041         continue;
5042       }
5043       Dim = Result.get();
5044     }
5045     if (!Dim->isTypeDependent()) {
5046       ExprResult Result =
5047           PerformOpenMPImplicitIntegerConversion(Dim->getExprLoc(), Dim);
5048       if (Result.isInvalid()) {
5049         ErrorFound = true;
5050         Diag(Dim->getExprLoc(), diag::err_omp_typecheck_shaping_not_integer)
5051             << Dim->getSourceRange();
5052         continue;
5053       }
5054       Dim = Result.get();
5055       Expr::EvalResult EvResult;
5056       if (!Dim->isValueDependent() && Dim->EvaluateAsInt(EvResult, Context)) {
5057         // OpenMP 5.0, [2.1.4 Array Shaping]
5058         // Each si is an integral type expression that must evaluate to a
5059         // positive integer.
5060         llvm::APSInt Value = EvResult.Val.getInt();
5061         if (!Value.isStrictlyPositive()) {
5062           Diag(Dim->getExprLoc(), diag::err_omp_shaping_dimension_not_positive)
5063               << Value.toString(/*Radix=*/10, /*Signed=*/true)
5064               << Dim->getSourceRange();
5065           ErrorFound = true;
5066           continue;
5067         }
5068       }
5069     }
5070     NewDims.push_back(Dim);
5071   }
5072   if (ErrorFound)
5073     return ExprError();
5074   return OMPArrayShapingExpr::Create(Context, Context.OMPArrayShapingTy, Base,
5075                                      LParenLoc, RParenLoc, NewDims, Brackets);
5076 }
5077 
5078 ExprResult Sema::ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc,
5079                                       SourceLocation LLoc, SourceLocation RLoc,
5080                                       ArrayRef<OMPIteratorData> Data) {
5081   SmallVector<OMPIteratorExpr::IteratorDefinition, 4> ID;
5082   bool IsCorrect = true;
5083   for (const OMPIteratorData &D : Data) {
5084     TypeSourceInfo *TInfo = nullptr;
5085     SourceLocation StartLoc;
5086     QualType DeclTy;
5087     if (!D.Type.getAsOpaquePtr()) {
5088       // OpenMP 5.0, 2.1.6 Iterators
5089       // In an iterator-specifier, if the iterator-type is not specified then
5090       // the type of that iterator is of int type.
5091       DeclTy = Context.IntTy;
5092       StartLoc = D.DeclIdentLoc;
5093     } else {
5094       DeclTy = GetTypeFromParser(D.Type, &TInfo);
5095       StartLoc = TInfo->getTypeLoc().getBeginLoc();
5096     }
5097 
5098     bool IsDeclTyDependent = DeclTy->isDependentType() ||
5099                              DeclTy->containsUnexpandedParameterPack() ||
5100                              DeclTy->isInstantiationDependentType();
5101     if (!IsDeclTyDependent) {
5102       if (!DeclTy->isIntegralType(Context) && !DeclTy->isAnyPointerType()) {
5103         // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++
5104         // The iterator-type must be an integral or pointer type.
5105         Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer)
5106             << DeclTy;
5107         IsCorrect = false;
5108         continue;
5109       }
5110       if (DeclTy.isConstant(Context)) {
5111         // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++
5112         // The iterator-type must not be const qualified.
5113         Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer)
5114             << DeclTy;
5115         IsCorrect = false;
5116         continue;
5117       }
5118     }
5119 
5120     // Iterator declaration.
5121     assert(D.DeclIdent && "Identifier expected.");
5122     // Always try to create iterator declarator to avoid extra error messages
5123     // about unknown declarations use.
5124     auto *VD = VarDecl::Create(Context, CurContext, StartLoc, D.DeclIdentLoc,
5125                                D.DeclIdent, DeclTy, TInfo, SC_None);
5126     VD->setImplicit();
5127     if (S) {
5128       // Check for conflicting previous declaration.
5129       DeclarationNameInfo NameInfo(VD->getDeclName(), D.DeclIdentLoc);
5130       LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5131                             ForVisibleRedeclaration);
5132       Previous.suppressDiagnostics();
5133       LookupName(Previous, S);
5134 
5135       FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false,
5136                            /*AllowInlineNamespace=*/false);
5137       if (!Previous.empty()) {
5138         NamedDecl *Old = Previous.getRepresentativeDecl();
5139         Diag(D.DeclIdentLoc, diag::err_redefinition) << VD->getDeclName();
5140         Diag(Old->getLocation(), diag::note_previous_definition);
5141       } else {
5142         PushOnScopeChains(VD, S);
5143       }
5144     } else {
5145       CurContext->addDecl(VD);
5146     }
5147     Expr *Begin = D.Range.Begin;
5148     if (!IsDeclTyDependent && Begin && !Begin->isTypeDependent()) {
5149       ExprResult BeginRes =
5150           PerformImplicitConversion(Begin, DeclTy, AA_Converting);
5151       Begin = BeginRes.get();
5152     }
5153     Expr *End = D.Range.End;
5154     if (!IsDeclTyDependent && End && !End->isTypeDependent()) {
5155       ExprResult EndRes = PerformImplicitConversion(End, DeclTy, AA_Converting);
5156       End = EndRes.get();
5157     }
5158     Expr *Step = D.Range.Step;
5159     if (!IsDeclTyDependent && Step && !Step->isTypeDependent()) {
5160       if (!Step->getType()->isIntegralType(Context)) {
5161         Diag(Step->getExprLoc(), diag::err_omp_iterator_step_not_integral)
5162             << Step << Step->getSourceRange();
5163         IsCorrect = false;
5164         continue;
5165       }
5166       Optional<llvm::APSInt> Result = Step->getIntegerConstantExpr(Context);
5167       // OpenMP 5.0, 2.1.6 Iterators, Restrictions
5168       // If the step expression of a range-specification equals zero, the
5169       // behavior is unspecified.
5170       if (Result && Result->isNullValue()) {
5171         Diag(Step->getExprLoc(), diag::err_omp_iterator_step_constant_zero)
5172             << Step << Step->getSourceRange();
5173         IsCorrect = false;
5174         continue;
5175       }
5176     }
5177     if (!Begin || !End || !IsCorrect) {
5178       IsCorrect = false;
5179       continue;
5180     }
5181     OMPIteratorExpr::IteratorDefinition &IDElem = ID.emplace_back();
5182     IDElem.IteratorDecl = VD;
5183     IDElem.AssignmentLoc = D.AssignLoc;
5184     IDElem.Range.Begin = Begin;
5185     IDElem.Range.End = End;
5186     IDElem.Range.Step = Step;
5187     IDElem.ColonLoc = D.ColonLoc;
5188     IDElem.SecondColonLoc = D.SecColonLoc;
5189   }
5190   if (!IsCorrect) {
5191     // Invalidate all created iterator declarations if error is found.
5192     for (const OMPIteratorExpr::IteratorDefinition &D : ID) {
5193       if (Decl *ID = D.IteratorDecl)
5194         ID->setInvalidDecl();
5195     }
5196     return ExprError();
5197   }
5198   SmallVector<OMPIteratorHelperData, 4> Helpers;
5199   if (!CurContext->isDependentContext()) {
5200     // Build number of ityeration for each iteration range.
5201     // Ni = ((Stepi > 0) ? ((Endi + Stepi -1 - Begini)/Stepi) :
5202     // ((Begini-Stepi-1-Endi) / -Stepi);
5203     for (OMPIteratorExpr::IteratorDefinition &D : ID) {
5204       // (Endi - Begini)
5205       ExprResult Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, D.Range.End,
5206                                           D.Range.Begin);
5207       if(!Res.isUsable()) {
5208         IsCorrect = false;
5209         continue;
5210       }
5211       ExprResult St, St1;
5212       if (D.Range.Step) {
5213         St = D.Range.Step;
5214         // (Endi - Begini) + Stepi
5215         Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res.get(), St.get());
5216         if (!Res.isUsable()) {
5217           IsCorrect = false;
5218           continue;
5219         }
5220         // (Endi - Begini) + Stepi - 1
5221         Res =
5222             CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res.get(),
5223                                ActOnIntegerConstant(D.AssignmentLoc, 1).get());
5224         if (!Res.isUsable()) {
5225           IsCorrect = false;
5226           continue;
5227         }
5228         // ((Endi - Begini) + Stepi - 1) / Stepi
5229         Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res.get(), St.get());
5230         if (!Res.isUsable()) {
5231           IsCorrect = false;
5232           continue;
5233         }
5234         St1 = CreateBuiltinUnaryOp(D.AssignmentLoc, UO_Minus, D.Range.Step);
5235         // (Begini - Endi)
5236         ExprResult Res1 = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub,
5237                                              D.Range.Begin, D.Range.End);
5238         if (!Res1.isUsable()) {
5239           IsCorrect = false;
5240           continue;
5241         }
5242         // (Begini - Endi) - Stepi
5243         Res1 =
5244             CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res1.get(), St1.get());
5245         if (!Res1.isUsable()) {
5246           IsCorrect = false;
5247           continue;
5248         }
5249         // (Begini - Endi) - Stepi - 1
5250         Res1 =
5251             CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res1.get(),
5252                                ActOnIntegerConstant(D.AssignmentLoc, 1).get());
5253         if (!Res1.isUsable()) {
5254           IsCorrect = false;
5255           continue;
5256         }
5257         // ((Begini - Endi) - Stepi - 1) / (-Stepi)
5258         Res1 =
5259             CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res1.get(), St1.get());
5260         if (!Res1.isUsable()) {
5261           IsCorrect = false;
5262           continue;
5263         }
5264         // Stepi > 0.
5265         ExprResult CmpRes =
5266             CreateBuiltinBinOp(D.AssignmentLoc, BO_GT, D.Range.Step,
5267                                ActOnIntegerConstant(D.AssignmentLoc, 0).get());
5268         if (!CmpRes.isUsable()) {
5269           IsCorrect = false;
5270           continue;
5271         }
5272         Res = ActOnConditionalOp(D.AssignmentLoc, D.AssignmentLoc, CmpRes.get(),
5273                                  Res.get(), Res1.get());
5274         if (!Res.isUsable()) {
5275           IsCorrect = false;
5276           continue;
5277         }
5278       }
5279       Res = ActOnFinishFullExpr(Res.get(), /*DiscardedValue=*/false);
5280       if (!Res.isUsable()) {
5281         IsCorrect = false;
5282         continue;
5283       }
5284 
5285       // Build counter update.
5286       // Build counter.
5287       auto *CounterVD =
5288           VarDecl::Create(Context, CurContext, D.IteratorDecl->getBeginLoc(),
5289                           D.IteratorDecl->getBeginLoc(), nullptr,
5290                           Res.get()->getType(), nullptr, SC_None);
5291       CounterVD->setImplicit();
5292       ExprResult RefRes =
5293           BuildDeclRefExpr(CounterVD, CounterVD->getType(), VK_LValue,
5294                            D.IteratorDecl->getBeginLoc());
5295       // Build counter update.
5296       // I = Begini + counter * Stepi;
5297       ExprResult UpdateRes;
5298       if (D.Range.Step) {
5299         UpdateRes = CreateBuiltinBinOp(
5300             D.AssignmentLoc, BO_Mul,
5301             DefaultLvalueConversion(RefRes.get()).get(), St.get());
5302       } else {
5303         UpdateRes = DefaultLvalueConversion(RefRes.get());
5304       }
5305       if (!UpdateRes.isUsable()) {
5306         IsCorrect = false;
5307         continue;
5308       }
5309       UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, D.Range.Begin,
5310                                      UpdateRes.get());
5311       if (!UpdateRes.isUsable()) {
5312         IsCorrect = false;
5313         continue;
5314       }
5315       ExprResult VDRes =
5316           BuildDeclRefExpr(cast<VarDecl>(D.IteratorDecl),
5317                            cast<VarDecl>(D.IteratorDecl)->getType(), VK_LValue,
5318                            D.IteratorDecl->getBeginLoc());
5319       UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Assign, VDRes.get(),
5320                                      UpdateRes.get());
5321       if (!UpdateRes.isUsable()) {
5322         IsCorrect = false;
5323         continue;
5324       }
5325       UpdateRes =
5326           ActOnFinishFullExpr(UpdateRes.get(), /*DiscardedValue=*/true);
5327       if (!UpdateRes.isUsable()) {
5328         IsCorrect = false;
5329         continue;
5330       }
5331       ExprResult CounterUpdateRes =
5332           CreateBuiltinUnaryOp(D.AssignmentLoc, UO_PreInc, RefRes.get());
5333       if (!CounterUpdateRes.isUsable()) {
5334         IsCorrect = false;
5335         continue;
5336       }
5337       CounterUpdateRes =
5338           ActOnFinishFullExpr(CounterUpdateRes.get(), /*DiscardedValue=*/true);
5339       if (!CounterUpdateRes.isUsable()) {
5340         IsCorrect = false;
5341         continue;
5342       }
5343       OMPIteratorHelperData &HD = Helpers.emplace_back();
5344       HD.CounterVD = CounterVD;
5345       HD.Upper = Res.get();
5346       HD.Update = UpdateRes.get();
5347       HD.CounterUpdate = CounterUpdateRes.get();
5348     }
5349   } else {
5350     Helpers.assign(ID.size(), {});
5351   }
5352   if (!IsCorrect) {
5353     // Invalidate all created iterator declarations if error is found.
5354     for (const OMPIteratorExpr::IteratorDefinition &D : ID) {
5355       if (Decl *ID = D.IteratorDecl)
5356         ID->setInvalidDecl();
5357     }
5358     return ExprError();
5359   }
5360   return OMPIteratorExpr::Create(Context, Context.OMPIteratorTy, IteratorKwLoc,
5361                                  LLoc, RLoc, ID, Helpers);
5362 }
5363 
5364 ExprResult
5365 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
5366                                       Expr *Idx, SourceLocation RLoc) {
5367   Expr *LHSExp = Base;
5368   Expr *RHSExp = Idx;
5369 
5370   ExprValueKind VK = VK_LValue;
5371   ExprObjectKind OK = OK_Ordinary;
5372 
5373   // Per C++ core issue 1213, the result is an xvalue if either operand is
5374   // a non-lvalue array, and an lvalue otherwise.
5375   if (getLangOpts().CPlusPlus11) {
5376     for (auto *Op : {LHSExp, RHSExp}) {
5377       Op = Op->IgnoreImplicit();
5378       if (Op->getType()->isArrayType() && !Op->isLValue())
5379         VK = VK_XValue;
5380     }
5381   }
5382 
5383   // Perform default conversions.
5384   if (!LHSExp->getType()->getAs<VectorType>()) {
5385     ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
5386     if (Result.isInvalid())
5387       return ExprError();
5388     LHSExp = Result.get();
5389   }
5390   ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
5391   if (Result.isInvalid())
5392     return ExprError();
5393   RHSExp = Result.get();
5394 
5395   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
5396 
5397   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
5398   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
5399   // in the subscript position. As a result, we need to derive the array base
5400   // and index from the expression types.
5401   Expr *BaseExpr, *IndexExpr;
5402   QualType ResultType;
5403   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
5404     BaseExpr = LHSExp;
5405     IndexExpr = RHSExp;
5406     ResultType = Context.DependentTy;
5407   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
5408     BaseExpr = LHSExp;
5409     IndexExpr = RHSExp;
5410     ResultType = PTy->getPointeeType();
5411   } else if (const ObjCObjectPointerType *PTy =
5412                LHSTy->getAs<ObjCObjectPointerType>()) {
5413     BaseExpr = LHSExp;
5414     IndexExpr = RHSExp;
5415 
5416     // Use custom logic if this should be the pseudo-object subscript
5417     // expression.
5418     if (!LangOpts.isSubscriptPointerArithmetic())
5419       return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
5420                                           nullptr);
5421 
5422     ResultType = PTy->getPointeeType();
5423   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
5424      // Handle the uncommon case of "123[Ptr]".
5425     BaseExpr = RHSExp;
5426     IndexExpr = LHSExp;
5427     ResultType = PTy->getPointeeType();
5428   } else if (const ObjCObjectPointerType *PTy =
5429                RHSTy->getAs<ObjCObjectPointerType>()) {
5430      // Handle the uncommon case of "123[Ptr]".
5431     BaseExpr = RHSExp;
5432     IndexExpr = LHSExp;
5433     ResultType = PTy->getPointeeType();
5434     if (!LangOpts.isSubscriptPointerArithmetic()) {
5435       Diag(LLoc, diag::err_subscript_nonfragile_interface)
5436         << ResultType << BaseExpr->getSourceRange();
5437       return ExprError();
5438     }
5439   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
5440     BaseExpr = LHSExp;    // vectors: V[123]
5441     IndexExpr = RHSExp;
5442     // We apply C++ DR1213 to vector subscripting too.
5443     if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_RValue) {
5444       ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
5445       if (Materialized.isInvalid())
5446         return ExprError();
5447       LHSExp = Materialized.get();
5448     }
5449     VK = LHSExp->getValueKind();
5450     if (VK != VK_RValue)
5451       OK = OK_VectorComponent;
5452 
5453     ResultType = VTy->getElementType();
5454     QualType BaseType = BaseExpr->getType();
5455     Qualifiers BaseQuals = BaseType.getQualifiers();
5456     Qualifiers MemberQuals = ResultType.getQualifiers();
5457     Qualifiers Combined = BaseQuals + MemberQuals;
5458     if (Combined != MemberQuals)
5459       ResultType = Context.getQualifiedType(ResultType, Combined);
5460   } else if (LHSTy->isArrayType()) {
5461     // If we see an array that wasn't promoted by
5462     // DefaultFunctionArrayLvalueConversion, it must be an array that
5463     // wasn't promoted because of the C90 rule that doesn't
5464     // allow promoting non-lvalue arrays.  Warn, then
5465     // force the promotion here.
5466     Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5467         << LHSExp->getSourceRange();
5468     LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
5469                                CK_ArrayToPointerDecay).get();
5470     LHSTy = LHSExp->getType();
5471 
5472     BaseExpr = LHSExp;
5473     IndexExpr = RHSExp;
5474     ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
5475   } else if (RHSTy->isArrayType()) {
5476     // Same as previous, except for 123[f().a] case
5477     Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5478         << RHSExp->getSourceRange();
5479     RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
5480                                CK_ArrayToPointerDecay).get();
5481     RHSTy = RHSExp->getType();
5482 
5483     BaseExpr = RHSExp;
5484     IndexExpr = LHSExp;
5485     ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
5486   } else {
5487     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
5488        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
5489   }
5490   // C99 6.5.2.1p1
5491   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
5492     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
5493                      << IndexExpr->getSourceRange());
5494 
5495   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5496        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5497          && !IndexExpr->isTypeDependent())
5498     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
5499 
5500   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5501   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5502   // type. Note that Functions are not objects, and that (in C99 parlance)
5503   // incomplete types are not object types.
5504   if (ResultType->isFunctionType()) {
5505     Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type)
5506         << ResultType << BaseExpr->getSourceRange();
5507     return ExprError();
5508   }
5509 
5510   if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
5511     // GNU extension: subscripting on pointer to void
5512     Diag(LLoc, diag::ext_gnu_subscript_void_type)
5513       << BaseExpr->getSourceRange();
5514 
5515     // C forbids expressions of unqualified void type from being l-values.
5516     // See IsCForbiddenLValueType.
5517     if (!ResultType.hasQualifiers()) VK = VK_RValue;
5518   } else if (!ResultType->isDependentType() &&
5519              RequireCompleteSizedType(
5520                  LLoc, ResultType,
5521                  diag::err_subscript_incomplete_or_sizeless_type, BaseExpr))
5522     return ExprError();
5523 
5524   assert(VK == VK_RValue || LangOpts.CPlusPlus ||
5525          !ResultType.isCForbiddenLValueType());
5526 
5527   if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() &&
5528       FunctionScopes.size() > 1) {
5529     if (auto *TT =
5530             LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) {
5531       for (auto I = FunctionScopes.rbegin(),
5532                 E = std::prev(FunctionScopes.rend());
5533            I != E; ++I) {
5534         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
5535         if (CSI == nullptr)
5536           break;
5537         DeclContext *DC = nullptr;
5538         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
5539           DC = LSI->CallOperator;
5540         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
5541           DC = CRSI->TheCapturedDecl;
5542         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
5543           DC = BSI->TheDecl;
5544         if (DC) {
5545           if (DC->containsDecl(TT->getDecl()))
5546             break;
5547           captureVariablyModifiedType(
5548               Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI);
5549         }
5550       }
5551     }
5552   }
5553 
5554   return new (Context)
5555       ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
5556 }
5557 
5558 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
5559                                   ParmVarDecl *Param) {
5560   if (Param->hasUnparsedDefaultArg()) {
5561     // If we've already cleared out the location for the default argument,
5562     // that means we're parsing it right now.
5563     if (!UnparsedDefaultArgLocs.count(Param)) {
5564       Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
5565       Diag(CallLoc, diag::note_recursive_default_argument_used_here);
5566       Param->setInvalidDecl();
5567       return true;
5568     }
5569 
5570     Diag(CallLoc, diag::err_use_of_default_argument_to_function_declared_later)
5571         << FD << cast<CXXRecordDecl>(FD->getDeclContext());
5572     Diag(UnparsedDefaultArgLocs[Param],
5573          diag::note_default_argument_declared_here);
5574     return true;
5575   }
5576 
5577   if (Param->hasUninstantiatedDefaultArg() &&
5578       InstantiateDefaultArgument(CallLoc, FD, Param))
5579     return true;
5580 
5581   assert(Param->hasInit() && "default argument but no initializer?");
5582 
5583   // If the default expression creates temporaries, we need to
5584   // push them to the current stack of expression temporaries so they'll
5585   // be properly destroyed.
5586   // FIXME: We should really be rebuilding the default argument with new
5587   // bound temporaries; see the comment in PR5810.
5588   // We don't need to do that with block decls, though, because
5589   // blocks in default argument expression can never capture anything.
5590   if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
5591     // Set the "needs cleanups" bit regardless of whether there are
5592     // any explicit objects.
5593     Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
5594 
5595     // Append all the objects to the cleanup list.  Right now, this
5596     // should always be a no-op, because blocks in default argument
5597     // expressions should never be able to capture anything.
5598     assert(!Init->getNumObjects() &&
5599            "default argument expression has capturing blocks?");
5600   }
5601 
5602   // We already type-checked the argument, so we know it works.
5603   // Just mark all of the declarations in this potentially-evaluated expression
5604   // as being "referenced".
5605   EnterExpressionEvaluationContext EvalContext(
5606       *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
5607   MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
5608                                    /*SkipLocalVariables=*/true);
5609   return false;
5610 }
5611 
5612 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
5613                                         FunctionDecl *FD, ParmVarDecl *Param) {
5614   assert(Param->hasDefaultArg() && "can't build nonexistent default arg");
5615   if (CheckCXXDefaultArgExpr(CallLoc, FD, Param))
5616     return ExprError();
5617   return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext);
5618 }
5619 
5620 Sema::VariadicCallType
5621 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
5622                           Expr *Fn) {
5623   if (Proto && Proto->isVariadic()) {
5624     if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
5625       return VariadicConstructor;
5626     else if (Fn && Fn->getType()->isBlockPointerType())
5627       return VariadicBlock;
5628     else if (FDecl) {
5629       if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5630         if (Method->isInstance())
5631           return VariadicMethod;
5632     } else if (Fn && Fn->getType() == Context.BoundMemberTy)
5633       return VariadicMethod;
5634     return VariadicFunction;
5635   }
5636   return VariadicDoesNotApply;
5637 }
5638 
5639 namespace {
5640 class FunctionCallCCC final : public FunctionCallFilterCCC {
5641 public:
5642   FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
5643                   unsigned NumArgs, MemberExpr *ME)
5644       : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
5645         FunctionName(FuncName) {}
5646 
5647   bool ValidateCandidate(const TypoCorrection &candidate) override {
5648     if (!candidate.getCorrectionSpecifier() ||
5649         candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
5650       return false;
5651     }
5652 
5653     return FunctionCallFilterCCC::ValidateCandidate(candidate);
5654   }
5655 
5656   std::unique_ptr<CorrectionCandidateCallback> clone() override {
5657     return std::make_unique<FunctionCallCCC>(*this);
5658   }
5659 
5660 private:
5661   const IdentifierInfo *const FunctionName;
5662 };
5663 }
5664 
5665 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
5666                                                FunctionDecl *FDecl,
5667                                                ArrayRef<Expr *> Args) {
5668   MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
5669   DeclarationName FuncName = FDecl->getDeclName();
5670   SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
5671 
5672   FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
5673   if (TypoCorrection Corrected = S.CorrectTypo(
5674           DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
5675           S.getScopeForContext(S.CurContext), nullptr, CCC,
5676           Sema::CTK_ErrorRecovery)) {
5677     if (NamedDecl *ND = Corrected.getFoundDecl()) {
5678       if (Corrected.isOverloaded()) {
5679         OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
5680         OverloadCandidateSet::iterator Best;
5681         for (NamedDecl *CD : Corrected) {
5682           if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
5683             S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
5684                                    OCS);
5685         }
5686         switch (OCS.BestViableFunction(S, NameLoc, Best)) {
5687         case OR_Success:
5688           ND = Best->FoundDecl;
5689           Corrected.setCorrectionDecl(ND);
5690           break;
5691         default:
5692           break;
5693         }
5694       }
5695       ND = ND->getUnderlyingDecl();
5696       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
5697         return Corrected;
5698     }
5699   }
5700   return TypoCorrection();
5701 }
5702 
5703 /// ConvertArgumentsForCall - Converts the arguments specified in
5704 /// Args/NumArgs to the parameter types of the function FDecl with
5705 /// function prototype Proto. Call is the call expression itself, and
5706 /// Fn is the function expression. For a C++ member function, this
5707 /// routine does not attempt to convert the object argument. Returns
5708 /// true if the call is ill-formed.
5709 bool
5710 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
5711                               FunctionDecl *FDecl,
5712                               const FunctionProtoType *Proto,
5713                               ArrayRef<Expr *> Args,
5714                               SourceLocation RParenLoc,
5715                               bool IsExecConfig) {
5716   // Bail out early if calling a builtin with custom typechecking.
5717   if (FDecl)
5718     if (unsigned ID = FDecl->getBuiltinID())
5719       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
5720         return false;
5721 
5722   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
5723   // assignment, to the types of the corresponding parameter, ...
5724   unsigned NumParams = Proto->getNumParams();
5725   bool Invalid = false;
5726   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
5727   unsigned FnKind = Fn->getType()->isBlockPointerType()
5728                        ? 1 /* block */
5729                        : (IsExecConfig ? 3 /* kernel function (exec config) */
5730                                        : 0 /* function */);
5731 
5732   // If too few arguments are available (and we don't have default
5733   // arguments for the remaining parameters), don't make the call.
5734   if (Args.size() < NumParams) {
5735     if (Args.size() < MinArgs) {
5736       TypoCorrection TC;
5737       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5738         unsigned diag_id =
5739             MinArgs == NumParams && !Proto->isVariadic()
5740                 ? diag::err_typecheck_call_too_few_args_suggest
5741                 : diag::err_typecheck_call_too_few_args_at_least_suggest;
5742         diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
5743                                         << static_cast<unsigned>(Args.size())
5744                                         << TC.getCorrectionRange());
5745       } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
5746         Diag(RParenLoc,
5747              MinArgs == NumParams && !Proto->isVariadic()
5748                  ? diag::err_typecheck_call_too_few_args_one
5749                  : diag::err_typecheck_call_too_few_args_at_least_one)
5750             << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
5751       else
5752         Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
5753                             ? diag::err_typecheck_call_too_few_args
5754                             : diag::err_typecheck_call_too_few_args_at_least)
5755             << FnKind << MinArgs << static_cast<unsigned>(Args.size())
5756             << Fn->getSourceRange();
5757 
5758       // Emit the location of the prototype.
5759       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5760         Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
5761 
5762       return true;
5763     }
5764     // We reserve space for the default arguments when we create
5765     // the call expression, before calling ConvertArgumentsForCall.
5766     assert((Call->getNumArgs() == NumParams) &&
5767            "We should have reserved space for the default arguments before!");
5768   }
5769 
5770   // If too many are passed and not variadic, error on the extras and drop
5771   // them.
5772   if (Args.size() > NumParams) {
5773     if (!Proto->isVariadic()) {
5774       TypoCorrection TC;
5775       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5776         unsigned diag_id =
5777             MinArgs == NumParams && !Proto->isVariadic()
5778                 ? diag::err_typecheck_call_too_many_args_suggest
5779                 : diag::err_typecheck_call_too_many_args_at_most_suggest;
5780         diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
5781                                         << static_cast<unsigned>(Args.size())
5782                                         << TC.getCorrectionRange());
5783       } else if (NumParams == 1 && FDecl &&
5784                  FDecl->getParamDecl(0)->getDeclName())
5785         Diag(Args[NumParams]->getBeginLoc(),
5786              MinArgs == NumParams
5787                  ? diag::err_typecheck_call_too_many_args_one
5788                  : diag::err_typecheck_call_too_many_args_at_most_one)
5789             << FnKind << FDecl->getParamDecl(0)
5790             << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
5791             << SourceRange(Args[NumParams]->getBeginLoc(),
5792                            Args.back()->getEndLoc());
5793       else
5794         Diag(Args[NumParams]->getBeginLoc(),
5795              MinArgs == NumParams
5796                  ? diag::err_typecheck_call_too_many_args
5797                  : diag::err_typecheck_call_too_many_args_at_most)
5798             << FnKind << NumParams << static_cast<unsigned>(Args.size())
5799             << Fn->getSourceRange()
5800             << SourceRange(Args[NumParams]->getBeginLoc(),
5801                            Args.back()->getEndLoc());
5802 
5803       // Emit the location of the prototype.
5804       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5805         Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
5806 
5807       // This deletes the extra arguments.
5808       Call->shrinkNumArgs(NumParams);
5809       return true;
5810     }
5811   }
5812   SmallVector<Expr *, 8> AllArgs;
5813   VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
5814 
5815   Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args,
5816                                    AllArgs, CallType);
5817   if (Invalid)
5818     return true;
5819   unsigned TotalNumArgs = AllArgs.size();
5820   for (unsigned i = 0; i < TotalNumArgs; ++i)
5821     Call->setArg(i, AllArgs[i]);
5822 
5823   return false;
5824 }
5825 
5826 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
5827                                   const FunctionProtoType *Proto,
5828                                   unsigned FirstParam, ArrayRef<Expr *> Args,
5829                                   SmallVectorImpl<Expr *> &AllArgs,
5830                                   VariadicCallType CallType, bool AllowExplicit,
5831                                   bool IsListInitialization) {
5832   unsigned NumParams = Proto->getNumParams();
5833   bool Invalid = false;
5834   size_t ArgIx = 0;
5835   // Continue to check argument types (even if we have too few/many args).
5836   for (unsigned i = FirstParam; i < NumParams; i++) {
5837     QualType ProtoArgType = Proto->getParamType(i);
5838 
5839     Expr *Arg;
5840     ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
5841     if (ArgIx < Args.size()) {
5842       Arg = Args[ArgIx++];
5843 
5844       if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType,
5845                               diag::err_call_incomplete_argument, Arg))
5846         return true;
5847 
5848       // Strip the unbridged-cast placeholder expression off, if applicable.
5849       bool CFAudited = false;
5850       if (Arg->getType() == Context.ARCUnbridgedCastTy &&
5851           FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5852           (!Param || !Param->hasAttr<CFConsumedAttr>()))
5853         Arg = stripARCUnbridgedCast(Arg);
5854       else if (getLangOpts().ObjCAutoRefCount &&
5855                FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5856                (!Param || !Param->hasAttr<CFConsumedAttr>()))
5857         CFAudited = true;
5858 
5859       if (Proto->getExtParameterInfo(i).isNoEscape())
5860         if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
5861           BE->getBlockDecl()->setDoesNotEscape();
5862 
5863       InitializedEntity Entity =
5864           Param ? InitializedEntity::InitializeParameter(Context, Param,
5865                                                          ProtoArgType)
5866                 : InitializedEntity::InitializeParameter(
5867                       Context, ProtoArgType, Proto->isParamConsumed(i));
5868 
5869       // Remember that parameter belongs to a CF audited API.
5870       if (CFAudited)
5871         Entity.setParameterCFAudited();
5872 
5873       ExprResult ArgE = PerformCopyInitialization(
5874           Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
5875       if (ArgE.isInvalid())
5876         return true;
5877 
5878       Arg = ArgE.getAs<Expr>();
5879     } else {
5880       assert(Param && "can't use default arguments without a known callee");
5881 
5882       ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
5883       if (ArgExpr.isInvalid())
5884         return true;
5885 
5886       Arg = ArgExpr.getAs<Expr>();
5887     }
5888 
5889     // Check for array bounds violations for each argument to the call. This
5890     // check only triggers warnings when the argument isn't a more complex Expr
5891     // with its own checking, such as a BinaryOperator.
5892     CheckArrayAccess(Arg);
5893 
5894     // Check for violations of C99 static array rules (C99 6.7.5.3p7).
5895     CheckStaticArrayArgument(CallLoc, Param, Arg);
5896 
5897     AllArgs.push_back(Arg);
5898   }
5899 
5900   // If this is a variadic call, handle args passed through "...".
5901   if (CallType != VariadicDoesNotApply) {
5902     // Assume that extern "C" functions with variadic arguments that
5903     // return __unknown_anytype aren't *really* variadic.
5904     if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
5905         FDecl->isExternC()) {
5906       for (Expr *A : Args.slice(ArgIx)) {
5907         QualType paramType; // ignored
5908         ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
5909         Invalid |= arg.isInvalid();
5910         AllArgs.push_back(arg.get());
5911       }
5912 
5913     // Otherwise do argument promotion, (C99 6.5.2.2p7).
5914     } else {
5915       for (Expr *A : Args.slice(ArgIx)) {
5916         ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
5917         Invalid |= Arg.isInvalid();
5918         AllArgs.push_back(Arg.get());
5919       }
5920     }
5921 
5922     // Check for array bounds violations.
5923     for (Expr *A : Args.slice(ArgIx))
5924       CheckArrayAccess(A);
5925   }
5926   return Invalid;
5927 }
5928 
5929 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
5930   TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
5931   if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
5932     TL = DTL.getOriginalLoc();
5933   if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
5934     S.Diag(PVD->getLocation(), diag::note_callee_static_array)
5935       << ATL.getLocalSourceRange();
5936 }
5937 
5938 /// CheckStaticArrayArgument - If the given argument corresponds to a static
5939 /// array parameter, check that it is non-null, and that if it is formed by
5940 /// array-to-pointer decay, the underlying array is sufficiently large.
5941 ///
5942 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
5943 /// array type derivation, then for each call to the function, the value of the
5944 /// corresponding actual argument shall provide access to the first element of
5945 /// an array with at least as many elements as specified by the size expression.
5946 void
5947 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
5948                                ParmVarDecl *Param,
5949                                const Expr *ArgExpr) {
5950   // Static array parameters are not supported in C++.
5951   if (!Param || getLangOpts().CPlusPlus)
5952     return;
5953 
5954   QualType OrigTy = Param->getOriginalType();
5955 
5956   const ArrayType *AT = Context.getAsArrayType(OrigTy);
5957   if (!AT || AT->getSizeModifier() != ArrayType::Static)
5958     return;
5959 
5960   if (ArgExpr->isNullPointerConstant(Context,
5961                                      Expr::NPC_NeverValueDependent)) {
5962     Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
5963     DiagnoseCalleeStaticArrayParam(*this, Param);
5964     return;
5965   }
5966 
5967   const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
5968   if (!CAT)
5969     return;
5970 
5971   const ConstantArrayType *ArgCAT =
5972     Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType());
5973   if (!ArgCAT)
5974     return;
5975 
5976   if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(),
5977                                              ArgCAT->getElementType())) {
5978     if (ArgCAT->getSize().ult(CAT->getSize())) {
5979       Diag(CallLoc, diag::warn_static_array_too_small)
5980           << ArgExpr->getSourceRange()
5981           << (unsigned)ArgCAT->getSize().getZExtValue()
5982           << (unsigned)CAT->getSize().getZExtValue() << 0;
5983       DiagnoseCalleeStaticArrayParam(*this, Param);
5984     }
5985     return;
5986   }
5987 
5988   Optional<CharUnits> ArgSize =
5989       getASTContext().getTypeSizeInCharsIfKnown(ArgCAT);
5990   Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT);
5991   if (ArgSize && ParmSize && *ArgSize < *ParmSize) {
5992     Diag(CallLoc, diag::warn_static_array_too_small)
5993         << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()
5994         << (unsigned)ParmSize->getQuantity() << 1;
5995     DiagnoseCalleeStaticArrayParam(*this, Param);
5996   }
5997 }
5998 
5999 /// Given a function expression of unknown-any type, try to rebuild it
6000 /// to have a function type.
6001 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
6002 
6003 /// Is the given type a placeholder that we need to lower out
6004 /// immediately during argument processing?
6005 static bool isPlaceholderToRemoveAsArg(QualType type) {
6006   // Placeholders are never sugared.
6007   const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
6008   if (!placeholder) return false;
6009 
6010   switch (placeholder->getKind()) {
6011   // Ignore all the non-placeholder types.
6012 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6013   case BuiltinType::Id:
6014 #include "clang/Basic/OpenCLImageTypes.def"
6015 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6016   case BuiltinType::Id:
6017 #include "clang/Basic/OpenCLExtensionTypes.def"
6018   // In practice we'll never use this, since all SVE types are sugared
6019   // via TypedefTypes rather than exposed directly as BuiltinTypes.
6020 #define SVE_TYPE(Name, Id, SingletonId) \
6021   case BuiltinType::Id:
6022 #include "clang/Basic/AArch64SVEACLETypes.def"
6023 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
6024 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
6025 #include "clang/AST/BuiltinTypes.def"
6026     return false;
6027 
6028   // We cannot lower out overload sets; they might validly be resolved
6029   // by the call machinery.
6030   case BuiltinType::Overload:
6031     return false;
6032 
6033   // Unbridged casts in ARC can be handled in some call positions and
6034   // should be left in place.
6035   case BuiltinType::ARCUnbridgedCast:
6036     return false;
6037 
6038   // Pseudo-objects should be converted as soon as possible.
6039   case BuiltinType::PseudoObject:
6040     return true;
6041 
6042   // The debugger mode could theoretically but currently does not try
6043   // to resolve unknown-typed arguments based on known parameter types.
6044   case BuiltinType::UnknownAny:
6045     return true;
6046 
6047   // These are always invalid as call arguments and should be reported.
6048   case BuiltinType::BoundMember:
6049   case BuiltinType::BuiltinFn:
6050   case BuiltinType::IncompleteMatrixIdx:
6051   case BuiltinType::OMPArraySection:
6052   case BuiltinType::OMPArrayShaping:
6053   case BuiltinType::OMPIterator:
6054     return true;
6055 
6056   }
6057   llvm_unreachable("bad builtin type kind");
6058 }
6059 
6060 /// Check an argument list for placeholders that we won't try to
6061 /// handle later.
6062 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
6063   // Apply this processing to all the arguments at once instead of
6064   // dying at the first failure.
6065   bool hasInvalid = false;
6066   for (size_t i = 0, e = args.size(); i != e; i++) {
6067     if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
6068       ExprResult result = S.CheckPlaceholderExpr(args[i]);
6069       if (result.isInvalid()) hasInvalid = true;
6070       else args[i] = result.get();
6071     }
6072   }
6073   return hasInvalid;
6074 }
6075 
6076 /// If a builtin function has a pointer argument with no explicit address
6077 /// space, then it should be able to accept a pointer to any address
6078 /// space as input.  In order to do this, we need to replace the
6079 /// standard builtin declaration with one that uses the same address space
6080 /// as the call.
6081 ///
6082 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
6083 ///                  it does not contain any pointer arguments without
6084 ///                  an address space qualifer.  Otherwise the rewritten
6085 ///                  FunctionDecl is returned.
6086 /// TODO: Handle pointer return types.
6087 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
6088                                                 FunctionDecl *FDecl,
6089                                                 MultiExprArg ArgExprs) {
6090 
6091   QualType DeclType = FDecl->getType();
6092   const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
6093 
6094   if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT ||
6095       ArgExprs.size() < FT->getNumParams())
6096     return nullptr;
6097 
6098   bool NeedsNewDecl = false;
6099   unsigned i = 0;
6100   SmallVector<QualType, 8> OverloadParams;
6101 
6102   for (QualType ParamType : FT->param_types()) {
6103 
6104     // Convert array arguments to pointer to simplify type lookup.
6105     ExprResult ArgRes =
6106         Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
6107     if (ArgRes.isInvalid())
6108       return nullptr;
6109     Expr *Arg = ArgRes.get();
6110     QualType ArgType = Arg->getType();
6111     if (!ParamType->isPointerType() ||
6112         ParamType.hasAddressSpace() ||
6113         !ArgType->isPointerType() ||
6114         !ArgType->getPointeeType().hasAddressSpace()) {
6115       OverloadParams.push_back(ParamType);
6116       continue;
6117     }
6118 
6119     QualType PointeeType = ParamType->getPointeeType();
6120     if (PointeeType.hasAddressSpace())
6121       continue;
6122 
6123     NeedsNewDecl = true;
6124     LangAS AS = ArgType->getPointeeType().getAddressSpace();
6125 
6126     PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
6127     OverloadParams.push_back(Context.getPointerType(PointeeType));
6128   }
6129 
6130   if (!NeedsNewDecl)
6131     return nullptr;
6132 
6133   FunctionProtoType::ExtProtoInfo EPI;
6134   EPI.Variadic = FT->isVariadic();
6135   QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
6136                                                 OverloadParams, EPI);
6137   DeclContext *Parent = FDecl->getParent();
6138   FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
6139                                                     FDecl->getLocation(),
6140                                                     FDecl->getLocation(),
6141                                                     FDecl->getIdentifier(),
6142                                                     OverloadTy,
6143                                                     /*TInfo=*/nullptr,
6144                                                     SC_Extern, false,
6145                                                     /*hasPrototype=*/true);
6146   SmallVector<ParmVarDecl*, 16> Params;
6147   FT = cast<FunctionProtoType>(OverloadTy);
6148   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
6149     QualType ParamType = FT->getParamType(i);
6150     ParmVarDecl *Parm =
6151         ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
6152                                 SourceLocation(), nullptr, ParamType,
6153                                 /*TInfo=*/nullptr, SC_None, nullptr);
6154     Parm->setScopeInfo(0, i);
6155     Params.push_back(Parm);
6156   }
6157   OverloadDecl->setParams(Params);
6158   Sema->mergeDeclAttributes(OverloadDecl, FDecl);
6159   return OverloadDecl;
6160 }
6161 
6162 static void checkDirectCallValidity(Sema &S, const Expr *Fn,
6163                                     FunctionDecl *Callee,
6164                                     MultiExprArg ArgExprs) {
6165   // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
6166   // similar attributes) really don't like it when functions are called with an
6167   // invalid number of args.
6168   if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
6169                          /*PartialOverloading=*/false) &&
6170       !Callee->isVariadic())
6171     return;
6172   if (Callee->getMinRequiredArguments() > ArgExprs.size())
6173     return;
6174 
6175   if (const EnableIfAttr *Attr =
6176           S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) {
6177     S.Diag(Fn->getBeginLoc(),
6178            isa<CXXMethodDecl>(Callee)
6179                ? diag::err_ovl_no_viable_member_function_in_call
6180                : diag::err_ovl_no_viable_function_in_call)
6181         << Callee << Callee->getSourceRange();
6182     S.Diag(Callee->getLocation(),
6183            diag::note_ovl_candidate_disabled_by_function_cond_attr)
6184         << Attr->getCond()->getSourceRange() << Attr->getMessage();
6185     return;
6186   }
6187 }
6188 
6189 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(
6190     const UnresolvedMemberExpr *const UME, Sema &S) {
6191 
6192   const auto GetFunctionLevelDCIfCXXClass =
6193       [](Sema &S) -> const CXXRecordDecl * {
6194     const DeclContext *const DC = S.getFunctionLevelDeclContext();
6195     if (!DC || !DC->getParent())
6196       return nullptr;
6197 
6198     // If the call to some member function was made from within a member
6199     // function body 'M' return return 'M's parent.
6200     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
6201       return MD->getParent()->getCanonicalDecl();
6202     // else the call was made from within a default member initializer of a
6203     // class, so return the class.
6204     if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
6205       return RD->getCanonicalDecl();
6206     return nullptr;
6207   };
6208   // If our DeclContext is neither a member function nor a class (in the
6209   // case of a lambda in a default member initializer), we can't have an
6210   // enclosing 'this'.
6211 
6212   const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
6213   if (!CurParentClass)
6214     return false;
6215 
6216   // The naming class for implicit member functions call is the class in which
6217   // name lookup starts.
6218   const CXXRecordDecl *const NamingClass =
6219       UME->getNamingClass()->getCanonicalDecl();
6220   assert(NamingClass && "Must have naming class even for implicit access");
6221 
6222   // If the unresolved member functions were found in a 'naming class' that is
6223   // related (either the same or derived from) to the class that contains the
6224   // member function that itself contained the implicit member access.
6225 
6226   return CurParentClass == NamingClass ||
6227          CurParentClass->isDerivedFrom(NamingClass);
6228 }
6229 
6230 static void
6231 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
6232     Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
6233 
6234   if (!UME)
6235     return;
6236 
6237   LambdaScopeInfo *const CurLSI = S.getCurLambda();
6238   // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
6239   // already been captured, or if this is an implicit member function call (if
6240   // it isn't, an attempt to capture 'this' should already have been made).
6241   if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
6242       !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
6243     return;
6244 
6245   // Check if the naming class in which the unresolved members were found is
6246   // related (same as or is a base of) to the enclosing class.
6247 
6248   if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S))
6249     return;
6250 
6251 
6252   DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
6253   // If the enclosing function is not dependent, then this lambda is
6254   // capture ready, so if we can capture this, do so.
6255   if (!EnclosingFunctionCtx->isDependentContext()) {
6256     // If the current lambda and all enclosing lambdas can capture 'this' -
6257     // then go ahead and capture 'this' (since our unresolved overload set
6258     // contains at least one non-static member function).
6259     if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
6260       S.CheckCXXThisCapture(CallLoc);
6261   } else if (S.CurContext->isDependentContext()) {
6262     // ... since this is an implicit member reference, that might potentially
6263     // involve a 'this' capture, mark 'this' for potential capture in
6264     // enclosing lambdas.
6265     if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
6266       CurLSI->addPotentialThisCapture(CallLoc);
6267   }
6268 }
6269 
6270 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
6271                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
6272                                Expr *ExecConfig) {
6273   ExprResult Call =
6274       BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig);
6275   if (Call.isInvalid())
6276     return Call;
6277 
6278   // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier
6279   // language modes.
6280   if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) {
6281     if (ULE->hasExplicitTemplateArgs() &&
6282         ULE->decls_begin() == ULE->decls_end()) {
6283       Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus20
6284                                  ? diag::warn_cxx17_compat_adl_only_template_id
6285                                  : diag::ext_adl_only_template_id)
6286           << ULE->getName();
6287     }
6288   }
6289 
6290   if (LangOpts.OpenMP)
6291     Call = ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc,
6292                            ExecConfig);
6293 
6294   return Call;
6295 }
6296 
6297 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments.
6298 /// This provides the location of the left/right parens and a list of comma
6299 /// locations.
6300 ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
6301                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
6302                                Expr *ExecConfig, bool IsExecConfig) {
6303   // Since this might be a postfix expression, get rid of ParenListExprs.
6304   ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
6305   if (Result.isInvalid()) return ExprError();
6306   Fn = Result.get();
6307 
6308   if (checkArgsForPlaceholders(*this, ArgExprs))
6309     return ExprError();
6310 
6311   if (getLangOpts().CPlusPlus) {
6312     // If this is a pseudo-destructor expression, build the call immediately.
6313     if (isa<CXXPseudoDestructorExpr>(Fn)) {
6314       if (!ArgExprs.empty()) {
6315         // Pseudo-destructor calls should not have any arguments.
6316         Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args)
6317             << FixItHint::CreateRemoval(
6318                    SourceRange(ArgExprs.front()->getBeginLoc(),
6319                                ArgExprs.back()->getEndLoc()));
6320       }
6321 
6322       return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy,
6323                               VK_RValue, RParenLoc, CurFPFeatureOverrides());
6324     }
6325     if (Fn->getType() == Context.PseudoObjectTy) {
6326       ExprResult result = CheckPlaceholderExpr(Fn);
6327       if (result.isInvalid()) return ExprError();
6328       Fn = result.get();
6329     }
6330 
6331     // Determine whether this is a dependent call inside a C++ template,
6332     // in which case we won't do any semantic analysis now.
6333     if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) {
6334       if (ExecConfig) {
6335         return CUDAKernelCallExpr::Create(
6336             Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
6337             Context.DependentTy, VK_RValue, RParenLoc, CurFPFeatureOverrides());
6338       } else {
6339 
6340         tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
6341             *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
6342             Fn->getBeginLoc());
6343 
6344         return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6345                                 VK_RValue, RParenLoc, CurFPFeatureOverrides());
6346       }
6347     }
6348 
6349     // Determine whether this is a call to an object (C++ [over.call.object]).
6350     if (Fn->getType()->isRecordType())
6351       return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
6352                                           RParenLoc);
6353 
6354     if (Fn->getType() == Context.UnknownAnyTy) {
6355       ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6356       if (result.isInvalid()) return ExprError();
6357       Fn = result.get();
6358     }
6359 
6360     if (Fn->getType() == Context.BoundMemberTy) {
6361       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6362                                        RParenLoc);
6363     }
6364   }
6365 
6366   // Check for overloaded calls.  This can happen even in C due to extensions.
6367   if (Fn->getType() == Context.OverloadTy) {
6368     OverloadExpr::FindResult find = OverloadExpr::find(Fn);
6369 
6370     // We aren't supposed to apply this logic if there's an '&' involved.
6371     if (!find.HasFormOfMemberPointer) {
6372       if (Expr::hasAnyTypeDependentArguments(ArgExprs))
6373         return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6374                                 VK_RValue, RParenLoc, CurFPFeatureOverrides());
6375       OverloadExpr *ovl = find.Expression;
6376       if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
6377         return BuildOverloadedCallExpr(
6378             Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6379             /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
6380       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6381                                        RParenLoc);
6382     }
6383   }
6384 
6385   // If we're directly calling a function, get the appropriate declaration.
6386   if (Fn->getType() == Context.UnknownAnyTy) {
6387     ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6388     if (result.isInvalid()) return ExprError();
6389     Fn = result.get();
6390   }
6391 
6392   Expr *NakedFn = Fn->IgnoreParens();
6393 
6394   bool CallingNDeclIndirectly = false;
6395   NamedDecl *NDecl = nullptr;
6396   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
6397     if (UnOp->getOpcode() == UO_AddrOf) {
6398       CallingNDeclIndirectly = true;
6399       NakedFn = UnOp->getSubExpr()->IgnoreParens();
6400     }
6401   }
6402 
6403   if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
6404     NDecl = DRE->getDecl();
6405 
6406     FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
6407     if (FDecl && FDecl->getBuiltinID()) {
6408       // Rewrite the function decl for this builtin by replacing parameters
6409       // with no explicit address space with the address space of the arguments
6410       // in ArgExprs.
6411       if ((FDecl =
6412                rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
6413         NDecl = FDecl;
6414         Fn = DeclRefExpr::Create(
6415             Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
6416             SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl,
6417             nullptr, DRE->isNonOdrUse());
6418       }
6419     }
6420   } else if (isa<MemberExpr>(NakedFn))
6421     NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
6422 
6423   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
6424     if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
6425                                       FD, /*Complain=*/true, Fn->getBeginLoc()))
6426       return ExprError();
6427 
6428     if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn))
6429       return ExprError();
6430 
6431     checkDirectCallValidity(*this, Fn, FD, ArgExprs);
6432   }
6433 
6434   return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
6435                                ExecConfig, IsExecConfig);
6436 }
6437 
6438 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
6439 ///
6440 /// __builtin_astype( value, dst type )
6441 ///
6442 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
6443                                  SourceLocation BuiltinLoc,
6444                                  SourceLocation RParenLoc) {
6445   ExprValueKind VK = VK_RValue;
6446   ExprObjectKind OK = OK_Ordinary;
6447   QualType DstTy = GetTypeFromParser(ParsedDestTy);
6448   QualType SrcTy = E->getType();
6449   if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
6450     return ExprError(Diag(BuiltinLoc,
6451                           diag::err_invalid_astype_of_different_size)
6452                      << DstTy
6453                      << SrcTy
6454                      << E->getSourceRange());
6455   return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
6456 }
6457 
6458 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
6459 /// provided arguments.
6460 ///
6461 /// __builtin_convertvector( value, dst type )
6462 ///
6463 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
6464                                         SourceLocation BuiltinLoc,
6465                                         SourceLocation RParenLoc) {
6466   TypeSourceInfo *TInfo;
6467   GetTypeFromParser(ParsedDestTy, &TInfo);
6468   return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
6469 }
6470 
6471 /// BuildResolvedCallExpr - Build a call to a resolved expression,
6472 /// i.e. an expression not of \p OverloadTy.  The expression should
6473 /// unary-convert to an expression of function-pointer or
6474 /// block-pointer type.
6475 ///
6476 /// \param NDecl the declaration being called, if available
6477 ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
6478                                        SourceLocation LParenLoc,
6479                                        ArrayRef<Expr *> Args,
6480                                        SourceLocation RParenLoc, Expr *Config,
6481                                        bool IsExecConfig, ADLCallKind UsesADL) {
6482   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
6483   unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
6484 
6485   // Functions with 'interrupt' attribute cannot be called directly.
6486   if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
6487     Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
6488     return ExprError();
6489   }
6490 
6491   // Interrupt handlers don't save off the VFP regs automatically on ARM,
6492   // so there's some risk when calling out to non-interrupt handler functions
6493   // that the callee might not preserve them. This is easy to diagnose here,
6494   // but can be very challenging to debug.
6495   if (auto *Caller = getCurFunctionDecl())
6496     if (Caller->hasAttr<ARMInterruptAttr>()) {
6497       bool VFP = Context.getTargetInfo().hasFeature("vfp");
6498       if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>()))
6499         Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention);
6500     }
6501 
6502   // Promote the function operand.
6503   // We special-case function promotion here because we only allow promoting
6504   // builtin functions to function pointers in the callee of a call.
6505   ExprResult Result;
6506   QualType ResultTy;
6507   if (BuiltinID &&
6508       Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
6509     // Extract the return type from the (builtin) function pointer type.
6510     // FIXME Several builtins still have setType in
6511     // Sema::CheckBuiltinFunctionCall. One should review their definitions in
6512     // Builtins.def to ensure they are correct before removing setType calls.
6513     QualType FnPtrTy = Context.getPointerType(FDecl->getType());
6514     Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get();
6515     ResultTy = FDecl->getCallResultType();
6516   } else {
6517     Result = CallExprUnaryConversions(Fn);
6518     ResultTy = Context.BoolTy;
6519   }
6520   if (Result.isInvalid())
6521     return ExprError();
6522   Fn = Result.get();
6523 
6524   // Check for a valid function type, but only if it is not a builtin which
6525   // requires custom type checking. These will be handled by
6526   // CheckBuiltinFunctionCall below just after creation of the call expression.
6527   const FunctionType *FuncT = nullptr;
6528   if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
6529   retry:
6530     if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
6531       // C99 6.5.2.2p1 - "The expression that denotes the called function shall
6532       // have type pointer to function".
6533       FuncT = PT->getPointeeType()->getAs<FunctionType>();
6534       if (!FuncT)
6535         return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
6536                          << Fn->getType() << Fn->getSourceRange());
6537     } else if (const BlockPointerType *BPT =
6538                    Fn->getType()->getAs<BlockPointerType>()) {
6539       FuncT = BPT->getPointeeType()->castAs<FunctionType>();
6540     } else {
6541       // Handle calls to expressions of unknown-any type.
6542       if (Fn->getType() == Context.UnknownAnyTy) {
6543         ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
6544         if (rewrite.isInvalid())
6545           return ExprError();
6546         Fn = rewrite.get();
6547         goto retry;
6548       }
6549 
6550       return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
6551                        << Fn->getType() << Fn->getSourceRange());
6552     }
6553   }
6554 
6555   // Get the number of parameters in the function prototype, if any.
6556   // We will allocate space for max(Args.size(), NumParams) arguments
6557   // in the call expression.
6558   const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT);
6559   unsigned NumParams = Proto ? Proto->getNumParams() : 0;
6560 
6561   CallExpr *TheCall;
6562   if (Config) {
6563     assert(UsesADL == ADLCallKind::NotADL &&
6564            "CUDAKernelCallExpr should not use ADL");
6565     TheCall = CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config),
6566                                          Args, ResultTy, VK_RValue, RParenLoc,
6567                                          CurFPFeatureOverrides(), NumParams);
6568   } else {
6569     TheCall =
6570         CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue, RParenLoc,
6571                          CurFPFeatureOverrides(), NumParams, UsesADL);
6572   }
6573 
6574   if (!getLangOpts().CPlusPlus) {
6575     // Forget about the nulled arguments since typo correction
6576     // do not handle them well.
6577     TheCall->shrinkNumArgs(Args.size());
6578     // C cannot always handle TypoExpr nodes in builtin calls and direct
6579     // function calls as their argument checking don't necessarily handle
6580     // dependent types properly, so make sure any TypoExprs have been
6581     // dealt with.
6582     ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
6583     if (!Result.isUsable()) return ExprError();
6584     CallExpr *TheOldCall = TheCall;
6585     TheCall = dyn_cast<CallExpr>(Result.get());
6586     bool CorrectedTypos = TheCall != TheOldCall;
6587     if (!TheCall) return Result;
6588     Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
6589 
6590     // A new call expression node was created if some typos were corrected.
6591     // However it may not have been constructed with enough storage. In this
6592     // case, rebuild the node with enough storage. The waste of space is
6593     // immaterial since this only happens when some typos were corrected.
6594     if (CorrectedTypos && Args.size() < NumParams) {
6595       if (Config)
6596         TheCall = CUDAKernelCallExpr::Create(
6597             Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_RValue,
6598             RParenLoc, CurFPFeatureOverrides(), NumParams);
6599       else
6600         TheCall =
6601             CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue, RParenLoc,
6602                              CurFPFeatureOverrides(), NumParams, UsesADL);
6603     }
6604     // We can now handle the nulled arguments for the default arguments.
6605     TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams));
6606   }
6607 
6608   // Bail out early if calling a builtin with custom type checking.
6609   if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
6610     return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
6611 
6612   if (getLangOpts().CUDA) {
6613     if (Config) {
6614       // CUDA: Kernel calls must be to global functions
6615       if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
6616         return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
6617             << FDecl << Fn->getSourceRange());
6618 
6619       // CUDA: Kernel function must have 'void' return type
6620       if (!FuncT->getReturnType()->isVoidType() &&
6621           !FuncT->getReturnType()->getAs<AutoType>() &&
6622           !FuncT->getReturnType()->isInstantiationDependentType())
6623         return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
6624             << Fn->getType() << Fn->getSourceRange());
6625     } else {
6626       // CUDA: Calls to global functions must be configured
6627       if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
6628         return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
6629             << FDecl << Fn->getSourceRange());
6630     }
6631   }
6632 
6633   // Check for a valid return type
6634   if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall,
6635                           FDecl))
6636     return ExprError();
6637 
6638   // We know the result type of the call, set it.
6639   TheCall->setType(FuncT->getCallResultType(Context));
6640   TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
6641 
6642   if (Proto) {
6643     if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
6644                                 IsExecConfig))
6645       return ExprError();
6646   } else {
6647     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
6648 
6649     if (FDecl) {
6650       // Check if we have too few/too many template arguments, based
6651       // on our knowledge of the function definition.
6652       const FunctionDecl *Def = nullptr;
6653       if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
6654         Proto = Def->getType()->getAs<FunctionProtoType>();
6655        if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
6656           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
6657           << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
6658       }
6659 
6660       // If the function we're calling isn't a function prototype, but we have
6661       // a function prototype from a prior declaratiom, use that prototype.
6662       if (!FDecl->hasPrototype())
6663         Proto = FDecl->getType()->getAs<FunctionProtoType>();
6664     }
6665 
6666     // Promote the arguments (C99 6.5.2.2p6).
6667     for (unsigned i = 0, e = Args.size(); i != e; i++) {
6668       Expr *Arg = Args[i];
6669 
6670       if (Proto && i < Proto->getNumParams()) {
6671         InitializedEntity Entity = InitializedEntity::InitializeParameter(
6672             Context, Proto->getParamType(i), Proto->isParamConsumed(i));
6673         ExprResult ArgE =
6674             PerformCopyInitialization(Entity, SourceLocation(), Arg);
6675         if (ArgE.isInvalid())
6676           return true;
6677 
6678         Arg = ArgE.getAs<Expr>();
6679 
6680       } else {
6681         ExprResult ArgE = DefaultArgumentPromotion(Arg);
6682 
6683         if (ArgE.isInvalid())
6684           return true;
6685 
6686         Arg = ArgE.getAs<Expr>();
6687       }
6688 
6689       if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(),
6690                               diag::err_call_incomplete_argument, Arg))
6691         return ExprError();
6692 
6693       TheCall->setArg(i, Arg);
6694     }
6695   }
6696 
6697   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
6698     if (!Method->isStatic())
6699       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
6700         << Fn->getSourceRange());
6701 
6702   // Check for sentinels
6703   if (NDecl)
6704     DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
6705 
6706   // Warn for unions passing across security boundary (CMSE).
6707   if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) {
6708     for (unsigned i = 0, e = Args.size(); i != e; i++) {
6709       if (const auto *RT =
6710               dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) {
6711         if (RT->getDecl()->isOrContainsUnion())
6712           Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union)
6713               << 0 << i;
6714       }
6715     }
6716   }
6717 
6718   // Do special checking on direct calls to functions.
6719   if (FDecl) {
6720     if (CheckFunctionCall(FDecl, TheCall, Proto))
6721       return ExprError();
6722 
6723     checkFortifiedBuiltinMemoryFunction(FDecl, TheCall);
6724 
6725     if (BuiltinID)
6726       return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
6727   } else if (NDecl) {
6728     if (CheckPointerCall(NDecl, TheCall, Proto))
6729       return ExprError();
6730   } else {
6731     if (CheckOtherCall(TheCall, Proto))
6732       return ExprError();
6733   }
6734 
6735   return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl);
6736 }
6737 
6738 ExprResult
6739 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
6740                            SourceLocation RParenLoc, Expr *InitExpr) {
6741   assert(Ty && "ActOnCompoundLiteral(): missing type");
6742   assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
6743 
6744   TypeSourceInfo *TInfo;
6745   QualType literalType = GetTypeFromParser(Ty, &TInfo);
6746   if (!TInfo)
6747     TInfo = Context.getTrivialTypeSourceInfo(literalType);
6748 
6749   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
6750 }
6751 
6752 ExprResult
6753 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
6754                                SourceLocation RParenLoc, Expr *LiteralExpr) {
6755   QualType literalType = TInfo->getType();
6756 
6757   if (literalType->isArrayType()) {
6758     if (RequireCompleteSizedType(
6759             LParenLoc, Context.getBaseElementType(literalType),
6760             diag::err_array_incomplete_or_sizeless_type,
6761             SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
6762       return ExprError();
6763     if (literalType->isVariableArrayType())
6764       return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
6765         << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
6766   } else if (!literalType->isDependentType() &&
6767              RequireCompleteType(LParenLoc, literalType,
6768                diag::err_typecheck_decl_incomplete_type,
6769                SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
6770     return ExprError();
6771 
6772   InitializedEntity Entity
6773     = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
6774   InitializationKind Kind
6775     = InitializationKind::CreateCStyleCast(LParenLoc,
6776                                            SourceRange(LParenLoc, RParenLoc),
6777                                            /*InitList=*/true);
6778   InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
6779   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
6780                                       &literalType);
6781   if (Result.isInvalid())
6782     return ExprError();
6783   LiteralExpr = Result.get();
6784 
6785   bool isFileScope = !CurContext->isFunctionOrMethod();
6786 
6787   // In C, compound literals are l-values for some reason.
6788   // For GCC compatibility, in C++, file-scope array compound literals with
6789   // constant initializers are also l-values, and compound literals are
6790   // otherwise prvalues.
6791   //
6792   // (GCC also treats C++ list-initialized file-scope array prvalues with
6793   // constant initializers as l-values, but that's non-conforming, so we don't
6794   // follow it there.)
6795   //
6796   // FIXME: It would be better to handle the lvalue cases as materializing and
6797   // lifetime-extending a temporary object, but our materialized temporaries
6798   // representation only supports lifetime extension from a variable, not "out
6799   // of thin air".
6800   // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
6801   // is bound to the result of applying array-to-pointer decay to the compound
6802   // literal.
6803   // FIXME: GCC supports compound literals of reference type, which should
6804   // obviously have a value kind derived from the kind of reference involved.
6805   ExprValueKind VK =
6806       (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
6807           ? VK_RValue
6808           : VK_LValue;
6809 
6810   if (isFileScope)
6811     if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr))
6812       for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {
6813         Expr *Init = ILE->getInit(i);
6814         ILE->setInit(i, ConstantExpr::Create(Context, Init));
6815       }
6816 
6817   auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
6818                                               VK, LiteralExpr, isFileScope);
6819   if (isFileScope) {
6820     if (!LiteralExpr->isTypeDependent() &&
6821         !LiteralExpr->isValueDependent() &&
6822         !literalType->isDependentType()) // C99 6.5.2.5p3
6823       if (CheckForConstantInitializer(LiteralExpr, literalType))
6824         return ExprError();
6825   } else if (literalType.getAddressSpace() != LangAS::opencl_private &&
6826              literalType.getAddressSpace() != LangAS::Default) {
6827     // Embedded-C extensions to C99 6.5.2.5:
6828     //   "If the compound literal occurs inside the body of a function, the
6829     //   type name shall not be qualified by an address-space qualifier."
6830     Diag(LParenLoc, diag::err_compound_literal_with_address_space)
6831       << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
6832     return ExprError();
6833   }
6834 
6835   if (!isFileScope && !getLangOpts().CPlusPlus) {
6836     // Compound literals that have automatic storage duration are destroyed at
6837     // the end of the scope in C; in C++, they're just temporaries.
6838 
6839     // Emit diagnostics if it is or contains a C union type that is non-trivial
6840     // to destruct.
6841     if (E->getType().hasNonTrivialToPrimitiveDestructCUnion())
6842       checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
6843                             NTCUC_CompoundLiteral, NTCUK_Destruct);
6844 
6845     // Diagnose jumps that enter or exit the lifetime of the compound literal.
6846     if (literalType.isDestructedType()) {
6847       Cleanup.setExprNeedsCleanups(true);
6848       ExprCleanupObjects.push_back(E);
6849       getCurFunction()->setHasBranchProtectedScope();
6850     }
6851   }
6852 
6853   if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
6854       E->getType().hasNonTrivialToPrimitiveCopyCUnion())
6855     checkNonTrivialCUnionInInitializer(E->getInitializer(),
6856                                        E->getInitializer()->getExprLoc());
6857 
6858   return MaybeBindToTemporary(E);
6859 }
6860 
6861 ExprResult
6862 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
6863                     SourceLocation RBraceLoc) {
6864   // Only produce each kind of designated initialization diagnostic once.
6865   SourceLocation FirstDesignator;
6866   bool DiagnosedArrayDesignator = false;
6867   bool DiagnosedNestedDesignator = false;
6868   bool DiagnosedMixedDesignator = false;
6869 
6870   // Check that any designated initializers are syntactically valid in the
6871   // current language mode.
6872   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
6873     if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) {
6874       if (FirstDesignator.isInvalid())
6875         FirstDesignator = DIE->getBeginLoc();
6876 
6877       if (!getLangOpts().CPlusPlus)
6878         break;
6879 
6880       if (!DiagnosedNestedDesignator && DIE->size() > 1) {
6881         DiagnosedNestedDesignator = true;
6882         Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested)
6883           << DIE->getDesignatorsSourceRange();
6884       }
6885 
6886       for (auto &Desig : DIE->designators()) {
6887         if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) {
6888           DiagnosedArrayDesignator = true;
6889           Diag(Desig.getBeginLoc(), diag::ext_designated_init_array)
6890             << Desig.getSourceRange();
6891         }
6892       }
6893 
6894       if (!DiagnosedMixedDesignator &&
6895           !isa<DesignatedInitExpr>(InitArgList[0])) {
6896         DiagnosedMixedDesignator = true;
6897         Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
6898           << DIE->getSourceRange();
6899         Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed)
6900           << InitArgList[0]->getSourceRange();
6901       }
6902     } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator &&
6903                isa<DesignatedInitExpr>(InitArgList[0])) {
6904       DiagnosedMixedDesignator = true;
6905       auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]);
6906       Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
6907         << DIE->getSourceRange();
6908       Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed)
6909         << InitArgList[I]->getSourceRange();
6910     }
6911   }
6912 
6913   if (FirstDesignator.isValid()) {
6914     // Only diagnose designated initiaization as a C++20 extension if we didn't
6915     // already diagnose use of (non-C++20) C99 designator syntax.
6916     if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator &&
6917         !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) {
6918       Diag(FirstDesignator, getLangOpts().CPlusPlus20
6919                                 ? diag::warn_cxx17_compat_designated_init
6920                                 : diag::ext_cxx_designated_init);
6921     } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) {
6922       Diag(FirstDesignator, diag::ext_designated_init);
6923     }
6924   }
6925 
6926   return BuildInitList(LBraceLoc, InitArgList, RBraceLoc);
6927 }
6928 
6929 ExprResult
6930 Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
6931                     SourceLocation RBraceLoc) {
6932   // Semantic analysis for initializers is done by ActOnDeclarator() and
6933   // CheckInitializer() - it requires knowledge of the object being initialized.
6934 
6935   // Immediately handle non-overload placeholders.  Overloads can be
6936   // resolved contextually, but everything else here can't.
6937   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
6938     if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
6939       ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
6940 
6941       // Ignore failures; dropping the entire initializer list because
6942       // of one failure would be terrible for indexing/etc.
6943       if (result.isInvalid()) continue;
6944 
6945       InitArgList[I] = result.get();
6946     }
6947   }
6948 
6949   InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
6950                                                RBraceLoc);
6951   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
6952   return E;
6953 }
6954 
6955 /// Do an explicit extend of the given block pointer if we're in ARC.
6956 void Sema::maybeExtendBlockObject(ExprResult &E) {
6957   assert(E.get()->getType()->isBlockPointerType());
6958   assert(E.get()->isRValue());
6959 
6960   // Only do this in an r-value context.
6961   if (!getLangOpts().ObjCAutoRefCount) return;
6962 
6963   E = ImplicitCastExpr::Create(
6964       Context, E.get()->getType(), CK_ARCExtendBlockObject, E.get(),
6965       /*base path*/ nullptr, VK_RValue, FPOptionsOverride());
6966   Cleanup.setExprNeedsCleanups(true);
6967 }
6968 
6969 /// Prepare a conversion of the given expression to an ObjC object
6970 /// pointer type.
6971 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
6972   QualType type = E.get()->getType();
6973   if (type->isObjCObjectPointerType()) {
6974     return CK_BitCast;
6975   } else if (type->isBlockPointerType()) {
6976     maybeExtendBlockObject(E);
6977     return CK_BlockPointerToObjCPointerCast;
6978   } else {
6979     assert(type->isPointerType());
6980     return CK_CPointerToObjCPointerCast;
6981   }
6982 }
6983 
6984 /// Prepares for a scalar cast, performing all the necessary stages
6985 /// except the final cast and returning the kind required.
6986 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
6987   // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
6988   // Also, callers should have filtered out the invalid cases with
6989   // pointers.  Everything else should be possible.
6990 
6991   QualType SrcTy = Src.get()->getType();
6992   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
6993     return CK_NoOp;
6994 
6995   switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
6996   case Type::STK_MemberPointer:
6997     llvm_unreachable("member pointer type in C");
6998 
6999   case Type::STK_CPointer:
7000   case Type::STK_BlockPointer:
7001   case Type::STK_ObjCObjectPointer:
7002     switch (DestTy->getScalarTypeKind()) {
7003     case Type::STK_CPointer: {
7004       LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
7005       LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
7006       if (SrcAS != DestAS)
7007         return CK_AddressSpaceConversion;
7008       if (Context.hasCvrSimilarType(SrcTy, DestTy))
7009         return CK_NoOp;
7010       return CK_BitCast;
7011     }
7012     case Type::STK_BlockPointer:
7013       return (SrcKind == Type::STK_BlockPointer
7014                 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
7015     case Type::STK_ObjCObjectPointer:
7016       if (SrcKind == Type::STK_ObjCObjectPointer)
7017         return CK_BitCast;
7018       if (SrcKind == Type::STK_CPointer)
7019         return CK_CPointerToObjCPointerCast;
7020       maybeExtendBlockObject(Src);
7021       return CK_BlockPointerToObjCPointerCast;
7022     case Type::STK_Bool:
7023       return CK_PointerToBoolean;
7024     case Type::STK_Integral:
7025       return CK_PointerToIntegral;
7026     case Type::STK_Floating:
7027     case Type::STK_FloatingComplex:
7028     case Type::STK_IntegralComplex:
7029     case Type::STK_MemberPointer:
7030     case Type::STK_FixedPoint:
7031       llvm_unreachable("illegal cast from pointer");
7032     }
7033     llvm_unreachable("Should have returned before this");
7034 
7035   case Type::STK_FixedPoint:
7036     switch (DestTy->getScalarTypeKind()) {
7037     case Type::STK_FixedPoint:
7038       return CK_FixedPointCast;
7039     case Type::STK_Bool:
7040       return CK_FixedPointToBoolean;
7041     case Type::STK_Integral:
7042       return CK_FixedPointToIntegral;
7043     case Type::STK_Floating:
7044     case Type::STK_IntegralComplex:
7045     case Type::STK_FloatingComplex:
7046       Diag(Src.get()->getExprLoc(),
7047            diag::err_unimplemented_conversion_with_fixed_point_type)
7048           << DestTy;
7049       return CK_IntegralCast;
7050     case Type::STK_CPointer:
7051     case Type::STK_ObjCObjectPointer:
7052     case Type::STK_BlockPointer:
7053     case Type::STK_MemberPointer:
7054       llvm_unreachable("illegal cast to pointer type");
7055     }
7056     llvm_unreachable("Should have returned before this");
7057 
7058   case Type::STK_Bool: // casting from bool is like casting from an integer
7059   case Type::STK_Integral:
7060     switch (DestTy->getScalarTypeKind()) {
7061     case Type::STK_CPointer:
7062     case Type::STK_ObjCObjectPointer:
7063     case Type::STK_BlockPointer:
7064       if (Src.get()->isNullPointerConstant(Context,
7065                                            Expr::NPC_ValueDependentIsNull))
7066         return CK_NullToPointer;
7067       return CK_IntegralToPointer;
7068     case Type::STK_Bool:
7069       return CK_IntegralToBoolean;
7070     case Type::STK_Integral:
7071       return CK_IntegralCast;
7072     case Type::STK_Floating:
7073       return CK_IntegralToFloating;
7074     case Type::STK_IntegralComplex:
7075       Src = ImpCastExprToType(Src.get(),
7076                       DestTy->castAs<ComplexType>()->getElementType(),
7077                       CK_IntegralCast);
7078       return CK_IntegralRealToComplex;
7079     case Type::STK_FloatingComplex:
7080       Src = ImpCastExprToType(Src.get(),
7081                       DestTy->castAs<ComplexType>()->getElementType(),
7082                       CK_IntegralToFloating);
7083       return CK_FloatingRealToComplex;
7084     case Type::STK_MemberPointer:
7085       llvm_unreachable("member pointer type in C");
7086     case Type::STK_FixedPoint:
7087       return CK_IntegralToFixedPoint;
7088     }
7089     llvm_unreachable("Should have returned before this");
7090 
7091   case Type::STK_Floating:
7092     switch (DestTy->getScalarTypeKind()) {
7093     case Type::STK_Floating:
7094       return CK_FloatingCast;
7095     case Type::STK_Bool:
7096       return CK_FloatingToBoolean;
7097     case Type::STK_Integral:
7098       return CK_FloatingToIntegral;
7099     case Type::STK_FloatingComplex:
7100       Src = ImpCastExprToType(Src.get(),
7101                               DestTy->castAs<ComplexType>()->getElementType(),
7102                               CK_FloatingCast);
7103       return CK_FloatingRealToComplex;
7104     case Type::STK_IntegralComplex:
7105       Src = ImpCastExprToType(Src.get(),
7106                               DestTy->castAs<ComplexType>()->getElementType(),
7107                               CK_FloatingToIntegral);
7108       return CK_IntegralRealToComplex;
7109     case Type::STK_CPointer:
7110     case Type::STK_ObjCObjectPointer:
7111     case Type::STK_BlockPointer:
7112       llvm_unreachable("valid float->pointer cast?");
7113     case Type::STK_MemberPointer:
7114       llvm_unreachable("member pointer type in C");
7115     case Type::STK_FixedPoint:
7116       Diag(Src.get()->getExprLoc(),
7117            diag::err_unimplemented_conversion_with_fixed_point_type)
7118           << SrcTy;
7119       return CK_IntegralCast;
7120     }
7121     llvm_unreachable("Should have returned before this");
7122 
7123   case Type::STK_FloatingComplex:
7124     switch (DestTy->getScalarTypeKind()) {
7125     case Type::STK_FloatingComplex:
7126       return CK_FloatingComplexCast;
7127     case Type::STK_IntegralComplex:
7128       return CK_FloatingComplexToIntegralComplex;
7129     case Type::STK_Floating: {
7130       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7131       if (Context.hasSameType(ET, DestTy))
7132         return CK_FloatingComplexToReal;
7133       Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
7134       return CK_FloatingCast;
7135     }
7136     case Type::STK_Bool:
7137       return CK_FloatingComplexToBoolean;
7138     case Type::STK_Integral:
7139       Src = ImpCastExprToType(Src.get(),
7140                               SrcTy->castAs<ComplexType>()->getElementType(),
7141                               CK_FloatingComplexToReal);
7142       return CK_FloatingToIntegral;
7143     case Type::STK_CPointer:
7144     case Type::STK_ObjCObjectPointer:
7145     case Type::STK_BlockPointer:
7146       llvm_unreachable("valid complex float->pointer cast?");
7147     case Type::STK_MemberPointer:
7148       llvm_unreachable("member pointer type in C");
7149     case Type::STK_FixedPoint:
7150       Diag(Src.get()->getExprLoc(),
7151            diag::err_unimplemented_conversion_with_fixed_point_type)
7152           << SrcTy;
7153       return CK_IntegralCast;
7154     }
7155     llvm_unreachable("Should have returned before this");
7156 
7157   case Type::STK_IntegralComplex:
7158     switch (DestTy->getScalarTypeKind()) {
7159     case Type::STK_FloatingComplex:
7160       return CK_IntegralComplexToFloatingComplex;
7161     case Type::STK_IntegralComplex:
7162       return CK_IntegralComplexCast;
7163     case Type::STK_Integral: {
7164       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7165       if (Context.hasSameType(ET, DestTy))
7166         return CK_IntegralComplexToReal;
7167       Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
7168       return CK_IntegralCast;
7169     }
7170     case Type::STK_Bool:
7171       return CK_IntegralComplexToBoolean;
7172     case Type::STK_Floating:
7173       Src = ImpCastExprToType(Src.get(),
7174                               SrcTy->castAs<ComplexType>()->getElementType(),
7175                               CK_IntegralComplexToReal);
7176       return CK_IntegralToFloating;
7177     case Type::STK_CPointer:
7178     case Type::STK_ObjCObjectPointer:
7179     case Type::STK_BlockPointer:
7180       llvm_unreachable("valid complex int->pointer cast?");
7181     case Type::STK_MemberPointer:
7182       llvm_unreachable("member pointer type in C");
7183     case Type::STK_FixedPoint:
7184       Diag(Src.get()->getExprLoc(),
7185            diag::err_unimplemented_conversion_with_fixed_point_type)
7186           << SrcTy;
7187       return CK_IntegralCast;
7188     }
7189     llvm_unreachable("Should have returned before this");
7190   }
7191 
7192   llvm_unreachable("Unhandled scalar cast");
7193 }
7194 
7195 static bool breakDownVectorType(QualType type, uint64_t &len,
7196                                 QualType &eltType) {
7197   // Vectors are simple.
7198   if (const VectorType *vecType = type->getAs<VectorType>()) {
7199     len = vecType->getNumElements();
7200     eltType = vecType->getElementType();
7201     assert(eltType->isScalarType());
7202     return true;
7203   }
7204 
7205   // We allow lax conversion to and from non-vector types, but only if
7206   // they're real types (i.e. non-complex, non-pointer scalar types).
7207   if (!type->isRealType()) return false;
7208 
7209   len = 1;
7210   eltType = type;
7211   return true;
7212 }
7213 
7214 /// Are the two types lax-compatible vector types?  That is, given
7215 /// that one of them is a vector, do they have equal storage sizes,
7216 /// where the storage size is the number of elements times the element
7217 /// size?
7218 ///
7219 /// This will also return false if either of the types is neither a
7220 /// vector nor a real type.
7221 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
7222   assert(destTy->isVectorType() || srcTy->isVectorType());
7223 
7224   // Disallow lax conversions between scalars and ExtVectors (these
7225   // conversions are allowed for other vector types because common headers
7226   // depend on them).  Most scalar OP ExtVector cases are handled by the
7227   // splat path anyway, which does what we want (convert, not bitcast).
7228   // What this rules out for ExtVectors is crazy things like char4*float.
7229   if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
7230   if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
7231 
7232   uint64_t srcLen, destLen;
7233   QualType srcEltTy, destEltTy;
7234   if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false;
7235   if (!breakDownVectorType(destTy, destLen, destEltTy)) return false;
7236 
7237   // ASTContext::getTypeSize will return the size rounded up to a
7238   // power of 2, so instead of using that, we need to use the raw
7239   // element size multiplied by the element count.
7240   uint64_t srcEltSize = Context.getTypeSize(srcEltTy);
7241   uint64_t destEltSize = Context.getTypeSize(destEltTy);
7242 
7243   return (srcLen * srcEltSize == destLen * destEltSize);
7244 }
7245 
7246 /// Is this a legal conversion between two types, one of which is
7247 /// known to be a vector type?
7248 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
7249   assert(destTy->isVectorType() || srcTy->isVectorType());
7250 
7251   switch (Context.getLangOpts().getLaxVectorConversions()) {
7252   case LangOptions::LaxVectorConversionKind::None:
7253     return false;
7254 
7255   case LangOptions::LaxVectorConversionKind::Integer:
7256     if (!srcTy->isIntegralOrEnumerationType()) {
7257       auto *Vec = srcTy->getAs<VectorType>();
7258       if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7259         return false;
7260     }
7261     if (!destTy->isIntegralOrEnumerationType()) {
7262       auto *Vec = destTy->getAs<VectorType>();
7263       if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7264         return false;
7265     }
7266     // OK, integer (vector) -> integer (vector) bitcast.
7267     break;
7268 
7269     case LangOptions::LaxVectorConversionKind::All:
7270     break;
7271   }
7272 
7273   return areLaxCompatibleVectorTypes(srcTy, destTy);
7274 }
7275 
7276 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
7277                            CastKind &Kind) {
7278   assert(VectorTy->isVectorType() && "Not a vector type!");
7279 
7280   if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
7281     if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
7282       return Diag(R.getBegin(),
7283                   Ty->isVectorType() ?
7284                   diag::err_invalid_conversion_between_vectors :
7285                   diag::err_invalid_conversion_between_vector_and_integer)
7286         << VectorTy << Ty << R;
7287   } else
7288     return Diag(R.getBegin(),
7289                 diag::err_invalid_conversion_between_vector_and_scalar)
7290       << VectorTy << Ty << R;
7291 
7292   Kind = CK_BitCast;
7293   return false;
7294 }
7295 
7296 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
7297   QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
7298 
7299   if (DestElemTy == SplattedExpr->getType())
7300     return SplattedExpr;
7301 
7302   assert(DestElemTy->isFloatingType() ||
7303          DestElemTy->isIntegralOrEnumerationType());
7304 
7305   CastKind CK;
7306   if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
7307     // OpenCL requires that we convert `true` boolean expressions to -1, but
7308     // only when splatting vectors.
7309     if (DestElemTy->isFloatingType()) {
7310       // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
7311       // in two steps: boolean to signed integral, then to floating.
7312       ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
7313                                                  CK_BooleanToSignedIntegral);
7314       SplattedExpr = CastExprRes.get();
7315       CK = CK_IntegralToFloating;
7316     } else {
7317       CK = CK_BooleanToSignedIntegral;
7318     }
7319   } else {
7320     ExprResult CastExprRes = SplattedExpr;
7321     CK = PrepareScalarCast(CastExprRes, DestElemTy);
7322     if (CastExprRes.isInvalid())
7323       return ExprError();
7324     SplattedExpr = CastExprRes.get();
7325   }
7326   return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
7327 }
7328 
7329 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
7330                                     Expr *CastExpr, CastKind &Kind) {
7331   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
7332 
7333   QualType SrcTy = CastExpr->getType();
7334 
7335   // If SrcTy is a VectorType, the total size must match to explicitly cast to
7336   // an ExtVectorType.
7337   // In OpenCL, casts between vectors of different types are not allowed.
7338   // (See OpenCL 6.2).
7339   if (SrcTy->isVectorType()) {
7340     if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
7341         (getLangOpts().OpenCL &&
7342          !Context.hasSameUnqualifiedType(DestTy, SrcTy))) {
7343       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
7344         << DestTy << SrcTy << R;
7345       return ExprError();
7346     }
7347     Kind = CK_BitCast;
7348     return CastExpr;
7349   }
7350 
7351   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
7352   // conversion will take place first from scalar to elt type, and then
7353   // splat from elt type to vector.
7354   if (SrcTy->isPointerType())
7355     return Diag(R.getBegin(),
7356                 diag::err_invalid_conversion_between_vector_and_scalar)
7357       << DestTy << SrcTy << R;
7358 
7359   Kind = CK_VectorSplat;
7360   return prepareVectorSplat(DestTy, CastExpr);
7361 }
7362 
7363 ExprResult
7364 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
7365                     Declarator &D, ParsedType &Ty,
7366                     SourceLocation RParenLoc, Expr *CastExpr) {
7367   assert(!D.isInvalidType() && (CastExpr != nullptr) &&
7368          "ActOnCastExpr(): missing type or expr");
7369 
7370   TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
7371   if (D.isInvalidType())
7372     return ExprError();
7373 
7374   if (getLangOpts().CPlusPlus) {
7375     // Check that there are no default arguments (C++ only).
7376     CheckExtraCXXDefaultArguments(D);
7377   } else {
7378     // Make sure any TypoExprs have been dealt with.
7379     ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
7380     if (!Res.isUsable())
7381       return ExprError();
7382     CastExpr = Res.get();
7383   }
7384 
7385   checkUnusedDeclAttributes(D);
7386 
7387   QualType castType = castTInfo->getType();
7388   Ty = CreateParsedType(castType, castTInfo);
7389 
7390   bool isVectorLiteral = false;
7391 
7392   // Check for an altivec or OpenCL literal,
7393   // i.e. all the elements are integer constants.
7394   ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
7395   ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
7396   if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
7397        && castType->isVectorType() && (PE || PLE)) {
7398     if (PLE && PLE->getNumExprs() == 0) {
7399       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
7400       return ExprError();
7401     }
7402     if (PE || PLE->getNumExprs() == 1) {
7403       Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
7404       if (!E->getType()->isVectorType())
7405         isVectorLiteral = true;
7406     }
7407     else
7408       isVectorLiteral = true;
7409   }
7410 
7411   // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
7412   // then handle it as such.
7413   if (isVectorLiteral)
7414     return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
7415 
7416   // If the Expr being casted is a ParenListExpr, handle it specially.
7417   // This is not an AltiVec-style cast, so turn the ParenListExpr into a
7418   // sequence of BinOp comma operators.
7419   if (isa<ParenListExpr>(CastExpr)) {
7420     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
7421     if (Result.isInvalid()) return ExprError();
7422     CastExpr = Result.get();
7423   }
7424 
7425   if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
7426       !getSourceManager().isInSystemMacro(LParenLoc))
7427     Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
7428 
7429   CheckTollFreeBridgeCast(castType, CastExpr);
7430 
7431   CheckObjCBridgeRelatedCast(castType, CastExpr);
7432 
7433   DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
7434 
7435   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
7436 }
7437 
7438 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
7439                                     SourceLocation RParenLoc, Expr *E,
7440                                     TypeSourceInfo *TInfo) {
7441   assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
7442          "Expected paren or paren list expression");
7443 
7444   Expr **exprs;
7445   unsigned numExprs;
7446   Expr *subExpr;
7447   SourceLocation LiteralLParenLoc, LiteralRParenLoc;
7448   if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
7449     LiteralLParenLoc = PE->getLParenLoc();
7450     LiteralRParenLoc = PE->getRParenLoc();
7451     exprs = PE->getExprs();
7452     numExprs = PE->getNumExprs();
7453   } else { // isa<ParenExpr> by assertion at function entrance
7454     LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
7455     LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
7456     subExpr = cast<ParenExpr>(E)->getSubExpr();
7457     exprs = &subExpr;
7458     numExprs = 1;
7459   }
7460 
7461   QualType Ty = TInfo->getType();
7462   assert(Ty->isVectorType() && "Expected vector type");
7463 
7464   SmallVector<Expr *, 8> initExprs;
7465   const VectorType *VTy = Ty->castAs<VectorType>();
7466   unsigned numElems = VTy->getNumElements();
7467 
7468   // '(...)' form of vector initialization in AltiVec: the number of
7469   // initializers must be one or must match the size of the vector.
7470   // If a single value is specified in the initializer then it will be
7471   // replicated to all the components of the vector
7472   if (VTy->getVectorKind() == VectorType::AltiVecVector) {
7473     // The number of initializers must be one or must match the size of the
7474     // vector. If a single value is specified in the initializer then it will
7475     // be replicated to all the components of the vector
7476     if (numExprs == 1) {
7477       QualType ElemTy = VTy->getElementType();
7478       ExprResult Literal = DefaultLvalueConversion(exprs[0]);
7479       if (Literal.isInvalid())
7480         return ExprError();
7481       Literal = ImpCastExprToType(Literal.get(), ElemTy,
7482                                   PrepareScalarCast(Literal, ElemTy));
7483       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
7484     }
7485     else if (numExprs < numElems) {
7486       Diag(E->getExprLoc(),
7487            diag::err_incorrect_number_of_vector_initializers);
7488       return ExprError();
7489     }
7490     else
7491       initExprs.append(exprs, exprs + numExprs);
7492   }
7493   else {
7494     // For OpenCL, when the number of initializers is a single value,
7495     // it will be replicated to all components of the vector.
7496     if (getLangOpts().OpenCL &&
7497         VTy->getVectorKind() == VectorType::GenericVector &&
7498         numExprs == 1) {
7499         QualType ElemTy = VTy->getElementType();
7500         ExprResult Literal = DefaultLvalueConversion(exprs[0]);
7501         if (Literal.isInvalid())
7502           return ExprError();
7503         Literal = ImpCastExprToType(Literal.get(), ElemTy,
7504                                     PrepareScalarCast(Literal, ElemTy));
7505         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
7506     }
7507 
7508     initExprs.append(exprs, exprs + numExprs);
7509   }
7510   // FIXME: This means that pretty-printing the final AST will produce curly
7511   // braces instead of the original commas.
7512   InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
7513                                                    initExprs, LiteralRParenLoc);
7514   initE->setType(Ty);
7515   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
7516 }
7517 
7518 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
7519 /// the ParenListExpr into a sequence of comma binary operators.
7520 ExprResult
7521 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
7522   ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
7523   if (!E)
7524     return OrigExpr;
7525 
7526   ExprResult Result(E->getExpr(0));
7527 
7528   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
7529     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
7530                         E->getExpr(i));
7531 
7532   if (Result.isInvalid()) return ExprError();
7533 
7534   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
7535 }
7536 
7537 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
7538                                     SourceLocation R,
7539                                     MultiExprArg Val) {
7540   return ParenListExpr::Create(Context, L, Val, R);
7541 }
7542 
7543 /// Emit a specialized diagnostic when one expression is a null pointer
7544 /// constant and the other is not a pointer.  Returns true if a diagnostic is
7545 /// emitted.
7546 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
7547                                       SourceLocation QuestionLoc) {
7548   Expr *NullExpr = LHSExpr;
7549   Expr *NonPointerExpr = RHSExpr;
7550   Expr::NullPointerConstantKind NullKind =
7551       NullExpr->isNullPointerConstant(Context,
7552                                       Expr::NPC_ValueDependentIsNotNull);
7553 
7554   if (NullKind == Expr::NPCK_NotNull) {
7555     NullExpr = RHSExpr;
7556     NonPointerExpr = LHSExpr;
7557     NullKind =
7558         NullExpr->isNullPointerConstant(Context,
7559                                         Expr::NPC_ValueDependentIsNotNull);
7560   }
7561 
7562   if (NullKind == Expr::NPCK_NotNull)
7563     return false;
7564 
7565   if (NullKind == Expr::NPCK_ZeroExpression)
7566     return false;
7567 
7568   if (NullKind == Expr::NPCK_ZeroLiteral) {
7569     // In this case, check to make sure that we got here from a "NULL"
7570     // string in the source code.
7571     NullExpr = NullExpr->IgnoreParenImpCasts();
7572     SourceLocation loc = NullExpr->getExprLoc();
7573     if (!findMacroSpelling(loc, "NULL"))
7574       return false;
7575   }
7576 
7577   int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
7578   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
7579       << NonPointerExpr->getType() << DiagType
7580       << NonPointerExpr->getSourceRange();
7581   return true;
7582 }
7583 
7584 /// Return false if the condition expression is valid, true otherwise.
7585 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
7586   QualType CondTy = Cond->getType();
7587 
7588   // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
7589   if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
7590     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
7591       << CondTy << Cond->getSourceRange();
7592     return true;
7593   }
7594 
7595   // C99 6.5.15p2
7596   if (CondTy->isScalarType()) return false;
7597 
7598   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
7599     << CondTy << Cond->getSourceRange();
7600   return true;
7601 }
7602 
7603 /// Handle when one or both operands are void type.
7604 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
7605                                          ExprResult &RHS) {
7606     Expr *LHSExpr = LHS.get();
7607     Expr *RHSExpr = RHS.get();
7608 
7609     if (!LHSExpr->getType()->isVoidType())
7610       S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
7611           << RHSExpr->getSourceRange();
7612     if (!RHSExpr->getType()->isVoidType())
7613       S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
7614           << LHSExpr->getSourceRange();
7615     LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
7616     RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
7617     return S.Context.VoidTy;
7618 }
7619 
7620 /// Return false if the NullExpr can be promoted to PointerTy,
7621 /// true otherwise.
7622 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
7623                                         QualType PointerTy) {
7624   if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
7625       !NullExpr.get()->isNullPointerConstant(S.Context,
7626                                             Expr::NPC_ValueDependentIsNull))
7627     return true;
7628 
7629   NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
7630   return false;
7631 }
7632 
7633 /// Checks compatibility between two pointers and return the resulting
7634 /// type.
7635 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
7636                                                      ExprResult &RHS,
7637                                                      SourceLocation Loc) {
7638   QualType LHSTy = LHS.get()->getType();
7639   QualType RHSTy = RHS.get()->getType();
7640 
7641   if (S.Context.hasSameType(LHSTy, RHSTy)) {
7642     // Two identical pointers types are always compatible.
7643     return LHSTy;
7644   }
7645 
7646   QualType lhptee, rhptee;
7647 
7648   // Get the pointee types.
7649   bool IsBlockPointer = false;
7650   if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
7651     lhptee = LHSBTy->getPointeeType();
7652     rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
7653     IsBlockPointer = true;
7654   } else {
7655     lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
7656     rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
7657   }
7658 
7659   // C99 6.5.15p6: If both operands are pointers to compatible types or to
7660   // differently qualified versions of compatible types, the result type is
7661   // a pointer to an appropriately qualified version of the composite
7662   // type.
7663 
7664   // Only CVR-qualifiers exist in the standard, and the differently-qualified
7665   // clause doesn't make sense for our extensions. E.g. address space 2 should
7666   // be incompatible with address space 3: they may live on different devices or
7667   // anything.
7668   Qualifiers lhQual = lhptee.getQualifiers();
7669   Qualifiers rhQual = rhptee.getQualifiers();
7670 
7671   LangAS ResultAddrSpace = LangAS::Default;
7672   LangAS LAddrSpace = lhQual.getAddressSpace();
7673   LangAS RAddrSpace = rhQual.getAddressSpace();
7674 
7675   // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
7676   // spaces is disallowed.
7677   if (lhQual.isAddressSpaceSupersetOf(rhQual))
7678     ResultAddrSpace = LAddrSpace;
7679   else if (rhQual.isAddressSpaceSupersetOf(lhQual))
7680     ResultAddrSpace = RAddrSpace;
7681   else {
7682     S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
7683         << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
7684         << RHS.get()->getSourceRange();
7685     return QualType();
7686   }
7687 
7688   unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
7689   auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
7690   lhQual.removeCVRQualifiers();
7691   rhQual.removeCVRQualifiers();
7692 
7693   // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
7694   // (C99 6.7.3) for address spaces. We assume that the check should behave in
7695   // the same manner as it's defined for CVR qualifiers, so for OpenCL two
7696   // qual types are compatible iff
7697   //  * corresponded types are compatible
7698   //  * CVR qualifiers are equal
7699   //  * address spaces are equal
7700   // Thus for conditional operator we merge CVR and address space unqualified
7701   // pointees and if there is a composite type we return a pointer to it with
7702   // merged qualifiers.
7703   LHSCastKind =
7704       LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
7705   RHSCastKind =
7706       RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
7707   lhQual.removeAddressSpace();
7708   rhQual.removeAddressSpace();
7709 
7710   lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
7711   rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
7712 
7713   QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
7714 
7715   if (CompositeTy.isNull()) {
7716     // In this situation, we assume void* type. No especially good
7717     // reason, but this is what gcc does, and we do have to pick
7718     // to get a consistent AST.
7719     QualType incompatTy;
7720     incompatTy = S.Context.getPointerType(
7721         S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
7722     LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
7723     RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
7724 
7725     // FIXME: For OpenCL the warning emission and cast to void* leaves a room
7726     // for casts between types with incompatible address space qualifiers.
7727     // For the following code the compiler produces casts between global and
7728     // local address spaces of the corresponded innermost pointees:
7729     // local int *global *a;
7730     // global int *global *b;
7731     // a = (0 ? a : b); // see C99 6.5.16.1.p1.
7732     S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
7733         << LHSTy << RHSTy << LHS.get()->getSourceRange()
7734         << RHS.get()->getSourceRange();
7735 
7736     return incompatTy;
7737   }
7738 
7739   // The pointer types are compatible.
7740   // In case of OpenCL ResultTy should have the address space qualifier
7741   // which is a superset of address spaces of both the 2nd and the 3rd
7742   // operands of the conditional operator.
7743   QualType ResultTy = [&, ResultAddrSpace]() {
7744     if (S.getLangOpts().OpenCL) {
7745       Qualifiers CompositeQuals = CompositeTy.getQualifiers();
7746       CompositeQuals.setAddressSpace(ResultAddrSpace);
7747       return S.Context
7748           .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
7749           .withCVRQualifiers(MergedCVRQual);
7750     }
7751     return CompositeTy.withCVRQualifiers(MergedCVRQual);
7752   }();
7753   if (IsBlockPointer)
7754     ResultTy = S.Context.getBlockPointerType(ResultTy);
7755   else
7756     ResultTy = S.Context.getPointerType(ResultTy);
7757 
7758   LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
7759   RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
7760   return ResultTy;
7761 }
7762 
7763 /// Return the resulting type when the operands are both block pointers.
7764 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
7765                                                           ExprResult &LHS,
7766                                                           ExprResult &RHS,
7767                                                           SourceLocation Loc) {
7768   QualType LHSTy = LHS.get()->getType();
7769   QualType RHSTy = RHS.get()->getType();
7770 
7771   if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
7772     if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
7773       QualType destType = S.Context.getPointerType(S.Context.VoidTy);
7774       LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
7775       RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
7776       return destType;
7777     }
7778     S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
7779       << LHSTy << RHSTy << LHS.get()->getSourceRange()
7780       << RHS.get()->getSourceRange();
7781     return QualType();
7782   }
7783 
7784   // We have 2 block pointer types.
7785   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
7786 }
7787 
7788 /// Return the resulting type when the operands are both pointers.
7789 static QualType
7790 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
7791                                             ExprResult &RHS,
7792                                             SourceLocation Loc) {
7793   // get the pointer types
7794   QualType LHSTy = LHS.get()->getType();
7795   QualType RHSTy = RHS.get()->getType();
7796 
7797   // get the "pointed to" types
7798   QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
7799   QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
7800 
7801   // ignore qualifiers on void (C99 6.5.15p3, clause 6)
7802   if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
7803     // Figure out necessary qualifiers (C99 6.5.15p6)
7804     QualType destPointee
7805       = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
7806     QualType destType = S.Context.getPointerType(destPointee);
7807     // Add qualifiers if necessary.
7808     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
7809     // Promote to void*.
7810     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
7811     return destType;
7812   }
7813   if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
7814     QualType destPointee
7815       = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
7816     QualType destType = S.Context.getPointerType(destPointee);
7817     // Add qualifiers if necessary.
7818     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
7819     // Promote to void*.
7820     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
7821     return destType;
7822   }
7823 
7824   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
7825 }
7826 
7827 /// Return false if the first expression is not an integer and the second
7828 /// expression is not a pointer, true otherwise.
7829 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
7830                                         Expr* PointerExpr, SourceLocation Loc,
7831                                         bool IsIntFirstExpr) {
7832   if (!PointerExpr->getType()->isPointerType() ||
7833       !Int.get()->getType()->isIntegerType())
7834     return false;
7835 
7836   Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
7837   Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
7838 
7839   S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
7840     << Expr1->getType() << Expr2->getType()
7841     << Expr1->getSourceRange() << Expr2->getSourceRange();
7842   Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
7843                             CK_IntegralToPointer);
7844   return true;
7845 }
7846 
7847 /// Simple conversion between integer and floating point types.
7848 ///
7849 /// Used when handling the OpenCL conditional operator where the
7850 /// condition is a vector while the other operands are scalar.
7851 ///
7852 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
7853 /// types are either integer or floating type. Between the two
7854 /// operands, the type with the higher rank is defined as the "result
7855 /// type". The other operand needs to be promoted to the same type. No
7856 /// other type promotion is allowed. We cannot use
7857 /// UsualArithmeticConversions() for this purpose, since it always
7858 /// promotes promotable types.
7859 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
7860                                             ExprResult &RHS,
7861                                             SourceLocation QuestionLoc) {
7862   LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
7863   if (LHS.isInvalid())
7864     return QualType();
7865   RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
7866   if (RHS.isInvalid())
7867     return QualType();
7868 
7869   // For conversion purposes, we ignore any qualifiers.
7870   // For example, "const float" and "float" are equivalent.
7871   QualType LHSType =
7872     S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
7873   QualType RHSType =
7874     S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
7875 
7876   if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
7877     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
7878       << LHSType << LHS.get()->getSourceRange();
7879     return QualType();
7880   }
7881 
7882   if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
7883     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
7884       << RHSType << RHS.get()->getSourceRange();
7885     return QualType();
7886   }
7887 
7888   // If both types are identical, no conversion is needed.
7889   if (LHSType == RHSType)
7890     return LHSType;
7891 
7892   // Now handle "real" floating types (i.e. float, double, long double).
7893   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
7894     return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
7895                                  /*IsCompAssign = */ false);
7896 
7897   // Finally, we have two differing integer types.
7898   return handleIntegerConversion<doIntegralCast, doIntegralCast>
7899   (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
7900 }
7901 
7902 /// Convert scalar operands to a vector that matches the
7903 ///        condition in length.
7904 ///
7905 /// Used when handling the OpenCL conditional operator where the
7906 /// condition is a vector while the other operands are scalar.
7907 ///
7908 /// We first compute the "result type" for the scalar operands
7909 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
7910 /// into a vector of that type where the length matches the condition
7911 /// vector type. s6.11.6 requires that the element types of the result
7912 /// and the condition must have the same number of bits.
7913 static QualType
7914 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
7915                               QualType CondTy, SourceLocation QuestionLoc) {
7916   QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
7917   if (ResTy.isNull()) return QualType();
7918 
7919   const VectorType *CV = CondTy->getAs<VectorType>();
7920   assert(CV);
7921 
7922   // Determine the vector result type
7923   unsigned NumElements = CV->getNumElements();
7924   QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
7925 
7926   // Ensure that all types have the same number of bits
7927   if (S.Context.getTypeSize(CV->getElementType())
7928       != S.Context.getTypeSize(ResTy)) {
7929     // Since VectorTy is created internally, it does not pretty print
7930     // with an OpenCL name. Instead, we just print a description.
7931     std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
7932     SmallString<64> Str;
7933     llvm::raw_svector_ostream OS(Str);
7934     OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
7935     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
7936       << CondTy << OS.str();
7937     return QualType();
7938   }
7939 
7940   // Convert operands to the vector result type
7941   LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
7942   RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
7943 
7944   return VectorTy;
7945 }
7946 
7947 /// Return false if this is a valid OpenCL condition vector
7948 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
7949                                        SourceLocation QuestionLoc) {
7950   // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
7951   // integral type.
7952   const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
7953   assert(CondTy);
7954   QualType EleTy = CondTy->getElementType();
7955   if (EleTy->isIntegerType()) return false;
7956 
7957   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
7958     << Cond->getType() << Cond->getSourceRange();
7959   return true;
7960 }
7961 
7962 /// Return false if the vector condition type and the vector
7963 ///        result type are compatible.
7964 ///
7965 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
7966 /// number of elements, and their element types have the same number
7967 /// of bits.
7968 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
7969                               SourceLocation QuestionLoc) {
7970   const VectorType *CV = CondTy->getAs<VectorType>();
7971   const VectorType *RV = VecResTy->getAs<VectorType>();
7972   assert(CV && RV);
7973 
7974   if (CV->getNumElements() != RV->getNumElements()) {
7975     S.Diag(QuestionLoc, diag::err_conditional_vector_size)
7976       << CondTy << VecResTy;
7977     return true;
7978   }
7979 
7980   QualType CVE = CV->getElementType();
7981   QualType RVE = RV->getElementType();
7982 
7983   if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
7984     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
7985       << CondTy << VecResTy;
7986     return true;
7987   }
7988 
7989   return false;
7990 }
7991 
7992 /// Return the resulting type for the conditional operator in
7993 ///        OpenCL (aka "ternary selection operator", OpenCL v1.1
7994 ///        s6.3.i) when the condition is a vector type.
7995 static QualType
7996 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
7997                              ExprResult &LHS, ExprResult &RHS,
7998                              SourceLocation QuestionLoc) {
7999   Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
8000   if (Cond.isInvalid())
8001     return QualType();
8002   QualType CondTy = Cond.get()->getType();
8003 
8004   if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
8005     return QualType();
8006 
8007   // If either operand is a vector then find the vector type of the
8008   // result as specified in OpenCL v1.1 s6.3.i.
8009   if (LHS.get()->getType()->isVectorType() ||
8010       RHS.get()->getType()->isVectorType()) {
8011     QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
8012                                               /*isCompAssign*/false,
8013                                               /*AllowBothBool*/true,
8014                                               /*AllowBoolConversions*/false);
8015     if (VecResTy.isNull()) return QualType();
8016     // The result type must match the condition type as specified in
8017     // OpenCL v1.1 s6.11.6.
8018     if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
8019       return QualType();
8020     return VecResTy;
8021   }
8022 
8023   // Both operands are scalar.
8024   return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
8025 }
8026 
8027 /// Return true if the Expr is block type
8028 static bool checkBlockType(Sema &S, const Expr *E) {
8029   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
8030     QualType Ty = CE->getCallee()->getType();
8031     if (Ty->isBlockPointerType()) {
8032       S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
8033       return true;
8034     }
8035   }
8036   return false;
8037 }
8038 
8039 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
8040 /// In that case, LHS = cond.
8041 /// C99 6.5.15
8042 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
8043                                         ExprResult &RHS, ExprValueKind &VK,
8044                                         ExprObjectKind &OK,
8045                                         SourceLocation QuestionLoc) {
8046 
8047   ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
8048   if (!LHSResult.isUsable()) return QualType();
8049   LHS = LHSResult;
8050 
8051   ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
8052   if (!RHSResult.isUsable()) return QualType();
8053   RHS = RHSResult;
8054 
8055   // C++ is sufficiently different to merit its own checker.
8056   if (getLangOpts().CPlusPlus)
8057     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
8058 
8059   VK = VK_RValue;
8060   OK = OK_Ordinary;
8061 
8062   // The OpenCL operator with a vector condition is sufficiently
8063   // different to merit its own checker.
8064   if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) ||
8065       Cond.get()->getType()->isExtVectorType())
8066     return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
8067 
8068   // First, check the condition.
8069   Cond = UsualUnaryConversions(Cond.get());
8070   if (Cond.isInvalid())
8071     return QualType();
8072   if (checkCondition(*this, Cond.get(), QuestionLoc))
8073     return QualType();
8074 
8075   // Now check the two expressions.
8076   if (LHS.get()->getType()->isVectorType() ||
8077       RHS.get()->getType()->isVectorType())
8078     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
8079                                /*AllowBothBool*/true,
8080                                /*AllowBoolConversions*/false);
8081 
8082   QualType ResTy =
8083       UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional);
8084   if (LHS.isInvalid() || RHS.isInvalid())
8085     return QualType();
8086 
8087   QualType LHSTy = LHS.get()->getType();
8088   QualType RHSTy = RHS.get()->getType();
8089 
8090   // Diagnose attempts to convert between __float128 and long double where
8091   // such conversions currently can't be handled.
8092   if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
8093     Diag(QuestionLoc,
8094          diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
8095       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8096     return QualType();
8097   }
8098 
8099   // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
8100   // selection operator (?:).
8101   if (getLangOpts().OpenCL &&
8102       (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) {
8103     return QualType();
8104   }
8105 
8106   // If both operands have arithmetic type, do the usual arithmetic conversions
8107   // to find a common type: C99 6.5.15p3,5.
8108   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
8109     // Disallow invalid arithmetic conversions, such as those between ExtInts of
8110     // different sizes, or between ExtInts and other types.
8111     if (ResTy.isNull() && (LHSTy->isExtIntType() || RHSTy->isExtIntType())) {
8112       Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
8113           << LHSTy << RHSTy << LHS.get()->getSourceRange()
8114           << RHS.get()->getSourceRange();
8115       return QualType();
8116     }
8117 
8118     LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
8119     RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
8120 
8121     return ResTy;
8122   }
8123 
8124   // And if they're both bfloat (which isn't arithmetic), that's fine too.
8125   if (LHSTy->isBFloat16Type() && RHSTy->isBFloat16Type()) {
8126     return LHSTy;
8127   }
8128 
8129   // If both operands are the same structure or union type, the result is that
8130   // type.
8131   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
8132     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
8133       if (LHSRT->getDecl() == RHSRT->getDecl())
8134         // "If both the operands have structure or union type, the result has
8135         // that type."  This implies that CV qualifiers are dropped.
8136         return LHSTy.getUnqualifiedType();
8137     // FIXME: Type of conditional expression must be complete in C mode.
8138   }
8139 
8140   // C99 6.5.15p5: "If both operands have void type, the result has void type."
8141   // The following || allows only one side to be void (a GCC-ism).
8142   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
8143     return checkConditionalVoidType(*this, LHS, RHS);
8144   }
8145 
8146   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
8147   // the type of the other operand."
8148   if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
8149   if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
8150 
8151   // All objective-c pointer type analysis is done here.
8152   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
8153                                                         QuestionLoc);
8154   if (LHS.isInvalid() || RHS.isInvalid())
8155     return QualType();
8156   if (!compositeType.isNull())
8157     return compositeType;
8158 
8159 
8160   // Handle block pointer types.
8161   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
8162     return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
8163                                                      QuestionLoc);
8164 
8165   // Check constraints for C object pointers types (C99 6.5.15p3,6).
8166   if (LHSTy->isPointerType() && RHSTy->isPointerType())
8167     return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
8168                                                        QuestionLoc);
8169 
8170   // GCC compatibility: soften pointer/integer mismatch.  Note that
8171   // null pointers have been filtered out by this point.
8172   if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
8173       /*IsIntFirstExpr=*/true))
8174     return RHSTy;
8175   if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
8176       /*IsIntFirstExpr=*/false))
8177     return LHSTy;
8178 
8179   // Allow ?: operations in which both operands have the same
8180   // built-in sizeless type.
8181   if (LHSTy->isSizelessBuiltinType() && LHSTy == RHSTy)
8182     return LHSTy;
8183 
8184   // Emit a better diagnostic if one of the expressions is a null pointer
8185   // constant and the other is not a pointer type. In this case, the user most
8186   // likely forgot to take the address of the other expression.
8187   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
8188     return QualType();
8189 
8190   // Otherwise, the operands are not compatible.
8191   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
8192     << LHSTy << RHSTy << LHS.get()->getSourceRange()
8193     << RHS.get()->getSourceRange();
8194   return QualType();
8195 }
8196 
8197 /// FindCompositeObjCPointerType - Helper method to find composite type of
8198 /// two objective-c pointer types of the two input expressions.
8199 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
8200                                             SourceLocation QuestionLoc) {
8201   QualType LHSTy = LHS.get()->getType();
8202   QualType RHSTy = RHS.get()->getType();
8203 
8204   // Handle things like Class and struct objc_class*.  Here we case the result
8205   // to the pseudo-builtin, because that will be implicitly cast back to the
8206   // redefinition type if an attempt is made to access its fields.
8207   if (LHSTy->isObjCClassType() &&
8208       (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
8209     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
8210     return LHSTy;
8211   }
8212   if (RHSTy->isObjCClassType() &&
8213       (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
8214     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
8215     return RHSTy;
8216   }
8217   // And the same for struct objc_object* / id
8218   if (LHSTy->isObjCIdType() &&
8219       (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
8220     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
8221     return LHSTy;
8222   }
8223   if (RHSTy->isObjCIdType() &&
8224       (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
8225     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
8226     return RHSTy;
8227   }
8228   // And the same for struct objc_selector* / SEL
8229   if (Context.isObjCSelType(LHSTy) &&
8230       (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
8231     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
8232     return LHSTy;
8233   }
8234   if (Context.isObjCSelType(RHSTy) &&
8235       (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
8236     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
8237     return RHSTy;
8238   }
8239   // Check constraints for Objective-C object pointers types.
8240   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
8241 
8242     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
8243       // Two identical object pointer types are always compatible.
8244       return LHSTy;
8245     }
8246     const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
8247     const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
8248     QualType compositeType = LHSTy;
8249 
8250     // If both operands are interfaces and either operand can be
8251     // assigned to the other, use that type as the composite
8252     // type. This allows
8253     //   xxx ? (A*) a : (B*) b
8254     // where B is a subclass of A.
8255     //
8256     // Additionally, as for assignment, if either type is 'id'
8257     // allow silent coercion. Finally, if the types are
8258     // incompatible then make sure to use 'id' as the composite
8259     // type so the result is acceptable for sending messages to.
8260 
8261     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
8262     // It could return the composite type.
8263     if (!(compositeType =
8264           Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
8265       // Nothing more to do.
8266     } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
8267       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
8268     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
8269       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
8270     } else if ((LHSOPT->isObjCQualifiedIdType() ||
8271                 RHSOPT->isObjCQualifiedIdType()) &&
8272                Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT,
8273                                                          true)) {
8274       // Need to handle "id<xx>" explicitly.
8275       // GCC allows qualified id and any Objective-C type to devolve to
8276       // id. Currently localizing to here until clear this should be
8277       // part of ObjCQualifiedIdTypesAreCompatible.
8278       compositeType = Context.getObjCIdType();
8279     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
8280       compositeType = Context.getObjCIdType();
8281     } else {
8282       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
8283       << LHSTy << RHSTy
8284       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8285       QualType incompatTy = Context.getObjCIdType();
8286       LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
8287       RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
8288       return incompatTy;
8289     }
8290     // The object pointer types are compatible.
8291     LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
8292     RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
8293     return compositeType;
8294   }
8295   // Check Objective-C object pointer types and 'void *'
8296   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
8297     if (getLangOpts().ObjCAutoRefCount) {
8298       // ARC forbids the implicit conversion of object pointers to 'void *',
8299       // so these types are not compatible.
8300       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
8301           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8302       LHS = RHS = true;
8303       return QualType();
8304     }
8305     QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8306     QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
8307     QualType destPointee
8308     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
8309     QualType destType = Context.getPointerType(destPointee);
8310     // Add qualifiers if necessary.
8311     LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
8312     // Promote to void*.
8313     RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8314     return destType;
8315   }
8316   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
8317     if (getLangOpts().ObjCAutoRefCount) {
8318       // ARC forbids the implicit conversion of object pointers to 'void *',
8319       // so these types are not compatible.
8320       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
8321           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8322       LHS = RHS = true;
8323       return QualType();
8324     }
8325     QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
8326     QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8327     QualType destPointee
8328     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
8329     QualType destType = Context.getPointerType(destPointee);
8330     // Add qualifiers if necessary.
8331     RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
8332     // Promote to void*.
8333     LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8334     return destType;
8335   }
8336   return QualType();
8337 }
8338 
8339 /// SuggestParentheses - Emit a note with a fixit hint that wraps
8340 /// ParenRange in parentheses.
8341 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
8342                                const PartialDiagnostic &Note,
8343                                SourceRange ParenRange) {
8344   SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
8345   if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
8346       EndLoc.isValid()) {
8347     Self.Diag(Loc, Note)
8348       << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
8349       << FixItHint::CreateInsertion(EndLoc, ")");
8350   } else {
8351     // We can't display the parentheses, so just show the bare note.
8352     Self.Diag(Loc, Note) << ParenRange;
8353   }
8354 }
8355 
8356 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
8357   return BinaryOperator::isAdditiveOp(Opc) ||
8358          BinaryOperator::isMultiplicativeOp(Opc) ||
8359          BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or;
8360   // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and
8361   // not any of the logical operators.  Bitwise-xor is commonly used as a
8362   // logical-xor because there is no logical-xor operator.  The logical
8363   // operators, including uses of xor, have a high false positive rate for
8364   // precedence warnings.
8365 }
8366 
8367 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
8368 /// expression, either using a built-in or overloaded operator,
8369 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
8370 /// expression.
8371 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
8372                                    Expr **RHSExprs) {
8373   // Don't strip parenthesis: we should not warn if E is in parenthesis.
8374   E = E->IgnoreImpCasts();
8375   E = E->IgnoreConversionOperatorSingleStep();
8376   E = E->IgnoreImpCasts();
8377   if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
8378     E = MTE->getSubExpr();
8379     E = E->IgnoreImpCasts();
8380   }
8381 
8382   // Built-in binary operator.
8383   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
8384     if (IsArithmeticOp(OP->getOpcode())) {
8385       *Opcode = OP->getOpcode();
8386       *RHSExprs = OP->getRHS();
8387       return true;
8388     }
8389   }
8390 
8391   // Overloaded operator.
8392   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
8393     if (Call->getNumArgs() != 2)
8394       return false;
8395 
8396     // Make sure this is really a binary operator that is safe to pass into
8397     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
8398     OverloadedOperatorKind OO = Call->getOperator();
8399     if (OO < OO_Plus || OO > OO_Arrow ||
8400         OO == OO_PlusPlus || OO == OO_MinusMinus)
8401       return false;
8402 
8403     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
8404     if (IsArithmeticOp(OpKind)) {
8405       *Opcode = OpKind;
8406       *RHSExprs = Call->getArg(1);
8407       return true;
8408     }
8409   }
8410 
8411   return false;
8412 }
8413 
8414 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
8415 /// or is a logical expression such as (x==y) which has int type, but is
8416 /// commonly interpreted as boolean.
8417 static bool ExprLooksBoolean(Expr *E) {
8418   E = E->IgnoreParenImpCasts();
8419 
8420   if (E->getType()->isBooleanType())
8421     return true;
8422   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
8423     return OP->isComparisonOp() || OP->isLogicalOp();
8424   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
8425     return OP->getOpcode() == UO_LNot;
8426   if (E->getType()->isPointerType())
8427     return true;
8428   // FIXME: What about overloaded operator calls returning "unspecified boolean
8429   // type"s (commonly pointer-to-members)?
8430 
8431   return false;
8432 }
8433 
8434 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
8435 /// and binary operator are mixed in a way that suggests the programmer assumed
8436 /// the conditional operator has higher precedence, for example:
8437 /// "int x = a + someBinaryCondition ? 1 : 2".
8438 static void DiagnoseConditionalPrecedence(Sema &Self,
8439                                           SourceLocation OpLoc,
8440                                           Expr *Condition,
8441                                           Expr *LHSExpr,
8442                                           Expr *RHSExpr) {
8443   BinaryOperatorKind CondOpcode;
8444   Expr *CondRHS;
8445 
8446   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
8447     return;
8448   if (!ExprLooksBoolean(CondRHS))
8449     return;
8450 
8451   // The condition is an arithmetic binary expression, with a right-
8452   // hand side that looks boolean, so warn.
8453 
8454   unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode)
8455                         ? diag::warn_precedence_bitwise_conditional
8456                         : diag::warn_precedence_conditional;
8457 
8458   Self.Diag(OpLoc, DiagID)
8459       << Condition->getSourceRange()
8460       << BinaryOperator::getOpcodeStr(CondOpcode);
8461 
8462   SuggestParentheses(
8463       Self, OpLoc,
8464       Self.PDiag(diag::note_precedence_silence)
8465           << BinaryOperator::getOpcodeStr(CondOpcode),
8466       SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
8467 
8468   SuggestParentheses(Self, OpLoc,
8469                      Self.PDiag(diag::note_precedence_conditional_first),
8470                      SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
8471 }
8472 
8473 /// Compute the nullability of a conditional expression.
8474 static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
8475                                               QualType LHSTy, QualType RHSTy,
8476                                               ASTContext &Ctx) {
8477   if (!ResTy->isAnyPointerType())
8478     return ResTy;
8479 
8480   auto GetNullability = [&Ctx](QualType Ty) {
8481     Optional<NullabilityKind> Kind = Ty->getNullability(Ctx);
8482     if (Kind)
8483       return *Kind;
8484     return NullabilityKind::Unspecified;
8485   };
8486 
8487   auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
8488   NullabilityKind MergedKind;
8489 
8490   // Compute nullability of a binary conditional expression.
8491   if (IsBin) {
8492     if (LHSKind == NullabilityKind::NonNull)
8493       MergedKind = NullabilityKind::NonNull;
8494     else
8495       MergedKind = RHSKind;
8496   // Compute nullability of a normal conditional expression.
8497   } else {
8498     if (LHSKind == NullabilityKind::Nullable ||
8499         RHSKind == NullabilityKind::Nullable)
8500       MergedKind = NullabilityKind::Nullable;
8501     else if (LHSKind == NullabilityKind::NonNull)
8502       MergedKind = RHSKind;
8503     else if (RHSKind == NullabilityKind::NonNull)
8504       MergedKind = LHSKind;
8505     else
8506       MergedKind = NullabilityKind::Unspecified;
8507   }
8508 
8509   // Return if ResTy already has the correct nullability.
8510   if (GetNullability(ResTy) == MergedKind)
8511     return ResTy;
8512 
8513   // Strip all nullability from ResTy.
8514   while (ResTy->getNullability(Ctx))
8515     ResTy = ResTy.getSingleStepDesugaredType(Ctx);
8516 
8517   // Create a new AttributedType with the new nullability kind.
8518   auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
8519   return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
8520 }
8521 
8522 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
8523 /// in the case of a the GNU conditional expr extension.
8524 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
8525                                     SourceLocation ColonLoc,
8526                                     Expr *CondExpr, Expr *LHSExpr,
8527                                     Expr *RHSExpr) {
8528   if (!getLangOpts().CPlusPlus) {
8529     // C cannot handle TypoExpr nodes in the condition because it
8530     // doesn't handle dependent types properly, so make sure any TypoExprs have
8531     // been dealt with before checking the operands.
8532     ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
8533     ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
8534     ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
8535 
8536     if (!CondResult.isUsable())
8537       return ExprError();
8538 
8539     if (LHSExpr) {
8540       if (!LHSResult.isUsable())
8541         return ExprError();
8542     }
8543 
8544     if (!RHSResult.isUsable())
8545       return ExprError();
8546 
8547     CondExpr = CondResult.get();
8548     LHSExpr = LHSResult.get();
8549     RHSExpr = RHSResult.get();
8550   }
8551 
8552   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
8553   // was the condition.
8554   OpaqueValueExpr *opaqueValue = nullptr;
8555   Expr *commonExpr = nullptr;
8556   if (!LHSExpr) {
8557     commonExpr = CondExpr;
8558     // Lower out placeholder types first.  This is important so that we don't
8559     // try to capture a placeholder. This happens in few cases in C++; such
8560     // as Objective-C++'s dictionary subscripting syntax.
8561     if (commonExpr->hasPlaceholderType()) {
8562       ExprResult result = CheckPlaceholderExpr(commonExpr);
8563       if (!result.isUsable()) return ExprError();
8564       commonExpr = result.get();
8565     }
8566     // We usually want to apply unary conversions *before* saving, except
8567     // in the special case of a C++ l-value conditional.
8568     if (!(getLangOpts().CPlusPlus
8569           && !commonExpr->isTypeDependent()
8570           && commonExpr->getValueKind() == RHSExpr->getValueKind()
8571           && commonExpr->isGLValue()
8572           && commonExpr->isOrdinaryOrBitFieldObject()
8573           && RHSExpr->isOrdinaryOrBitFieldObject()
8574           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
8575       ExprResult commonRes = UsualUnaryConversions(commonExpr);
8576       if (commonRes.isInvalid())
8577         return ExprError();
8578       commonExpr = commonRes.get();
8579     }
8580 
8581     // If the common expression is a class or array prvalue, materialize it
8582     // so that we can safely refer to it multiple times.
8583     if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() ||
8584                                    commonExpr->getType()->isArrayType())) {
8585       ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
8586       if (MatExpr.isInvalid())
8587         return ExprError();
8588       commonExpr = MatExpr.get();
8589     }
8590 
8591     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
8592                                                 commonExpr->getType(),
8593                                                 commonExpr->getValueKind(),
8594                                                 commonExpr->getObjectKind(),
8595                                                 commonExpr);
8596     LHSExpr = CondExpr = opaqueValue;
8597   }
8598 
8599   QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
8600   ExprValueKind VK = VK_RValue;
8601   ExprObjectKind OK = OK_Ordinary;
8602   ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
8603   QualType result = CheckConditionalOperands(Cond, LHS, RHS,
8604                                              VK, OK, QuestionLoc);
8605   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
8606       RHS.isInvalid())
8607     return ExprError();
8608 
8609   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
8610                                 RHS.get());
8611 
8612   CheckBoolLikeConversion(Cond.get(), QuestionLoc);
8613 
8614   result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
8615                                          Context);
8616 
8617   if (!commonExpr)
8618     return new (Context)
8619         ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
8620                             RHS.get(), result, VK, OK);
8621 
8622   return new (Context) BinaryConditionalOperator(
8623       commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
8624       ColonLoc, result, VK, OK);
8625 }
8626 
8627 // Check if we have a conversion between incompatible cmse function pointer
8628 // types, that is, a conversion between a function pointer with the
8629 // cmse_nonsecure_call attribute and one without.
8630 static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType,
8631                                           QualType ToType) {
8632   if (const auto *ToFn =
8633           dyn_cast<FunctionType>(S.Context.getCanonicalType(ToType))) {
8634     if (const auto *FromFn =
8635             dyn_cast<FunctionType>(S.Context.getCanonicalType(FromType))) {
8636       FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
8637       FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
8638 
8639       return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall();
8640     }
8641   }
8642   return false;
8643 }
8644 
8645 // checkPointerTypesForAssignment - This is a very tricky routine (despite
8646 // being closely modeled after the C99 spec:-). The odd characteristic of this
8647 // routine is it effectively iqnores the qualifiers on the top level pointee.
8648 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
8649 // FIXME: add a couple examples in this comment.
8650 static Sema::AssignConvertType
8651 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
8652   assert(LHSType.isCanonical() && "LHS not canonicalized!");
8653   assert(RHSType.isCanonical() && "RHS not canonicalized!");
8654 
8655   // get the "pointed to" type (ignoring qualifiers at the top level)
8656   const Type *lhptee, *rhptee;
8657   Qualifiers lhq, rhq;
8658   std::tie(lhptee, lhq) =
8659       cast<PointerType>(LHSType)->getPointeeType().split().asPair();
8660   std::tie(rhptee, rhq) =
8661       cast<PointerType>(RHSType)->getPointeeType().split().asPair();
8662 
8663   Sema::AssignConvertType ConvTy = Sema::Compatible;
8664 
8665   // C99 6.5.16.1p1: This following citation is common to constraints
8666   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
8667   // qualifiers of the type *pointed to* by the right;
8668 
8669   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
8670   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
8671       lhq.compatiblyIncludesObjCLifetime(rhq)) {
8672     // Ignore lifetime for further calculation.
8673     lhq.removeObjCLifetime();
8674     rhq.removeObjCLifetime();
8675   }
8676 
8677   if (!lhq.compatiblyIncludes(rhq)) {
8678     // Treat address-space mismatches as fatal.
8679     if (!lhq.isAddressSpaceSupersetOf(rhq))
8680       return Sema::IncompatiblePointerDiscardsQualifiers;
8681 
8682     // It's okay to add or remove GC or lifetime qualifiers when converting to
8683     // and from void*.
8684     else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
8685                         .compatiblyIncludes(
8686                                 rhq.withoutObjCGCAttr().withoutObjCLifetime())
8687              && (lhptee->isVoidType() || rhptee->isVoidType()))
8688       ; // keep old
8689 
8690     // Treat lifetime mismatches as fatal.
8691     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
8692       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
8693 
8694     // For GCC/MS compatibility, other qualifier mismatches are treated
8695     // as still compatible in C.
8696     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
8697   }
8698 
8699   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
8700   // incomplete type and the other is a pointer to a qualified or unqualified
8701   // version of void...
8702   if (lhptee->isVoidType()) {
8703     if (rhptee->isIncompleteOrObjectType())
8704       return ConvTy;
8705 
8706     // As an extension, we allow cast to/from void* to function pointer.
8707     assert(rhptee->isFunctionType());
8708     return Sema::FunctionVoidPointer;
8709   }
8710 
8711   if (rhptee->isVoidType()) {
8712     if (lhptee->isIncompleteOrObjectType())
8713       return ConvTy;
8714 
8715     // As an extension, we allow cast to/from void* to function pointer.
8716     assert(lhptee->isFunctionType());
8717     return Sema::FunctionVoidPointer;
8718   }
8719 
8720   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
8721   // unqualified versions of compatible types, ...
8722   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
8723   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
8724     // Check if the pointee types are compatible ignoring the sign.
8725     // We explicitly check for char so that we catch "char" vs
8726     // "unsigned char" on systems where "char" is unsigned.
8727     if (lhptee->isCharType())
8728       ltrans = S.Context.UnsignedCharTy;
8729     else if (lhptee->hasSignedIntegerRepresentation())
8730       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
8731 
8732     if (rhptee->isCharType())
8733       rtrans = S.Context.UnsignedCharTy;
8734     else if (rhptee->hasSignedIntegerRepresentation())
8735       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
8736 
8737     if (ltrans == rtrans) {
8738       // Types are compatible ignoring the sign. Qualifier incompatibility
8739       // takes priority over sign incompatibility because the sign
8740       // warning can be disabled.
8741       if (ConvTy != Sema::Compatible)
8742         return ConvTy;
8743 
8744       return Sema::IncompatiblePointerSign;
8745     }
8746 
8747     // If we are a multi-level pointer, it's possible that our issue is simply
8748     // one of qualification - e.g. char ** -> const char ** is not allowed. If
8749     // the eventual target type is the same and the pointers have the same
8750     // level of indirection, this must be the issue.
8751     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
8752       do {
8753         std::tie(lhptee, lhq) =
8754           cast<PointerType>(lhptee)->getPointeeType().split().asPair();
8755         std::tie(rhptee, rhq) =
8756           cast<PointerType>(rhptee)->getPointeeType().split().asPair();
8757 
8758         // Inconsistent address spaces at this point is invalid, even if the
8759         // address spaces would be compatible.
8760         // FIXME: This doesn't catch address space mismatches for pointers of
8761         // different nesting levels, like:
8762         //   __local int *** a;
8763         //   int ** b = a;
8764         // It's not clear how to actually determine when such pointers are
8765         // invalidly incompatible.
8766         if (lhq.getAddressSpace() != rhq.getAddressSpace())
8767           return Sema::IncompatibleNestedPointerAddressSpaceMismatch;
8768 
8769       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
8770 
8771       if (lhptee == rhptee)
8772         return Sema::IncompatibleNestedPointerQualifiers;
8773     }
8774 
8775     // General pointer incompatibility takes priority over qualifiers.
8776     if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType())
8777       return Sema::IncompatibleFunctionPointer;
8778     return Sema::IncompatiblePointer;
8779   }
8780   if (!S.getLangOpts().CPlusPlus &&
8781       S.IsFunctionConversion(ltrans, rtrans, ltrans))
8782     return Sema::IncompatibleFunctionPointer;
8783   if (IsInvalidCmseNSCallConversion(S, ltrans, rtrans))
8784     return Sema::IncompatibleFunctionPointer;
8785   return ConvTy;
8786 }
8787 
8788 /// checkBlockPointerTypesForAssignment - This routine determines whether two
8789 /// block pointer types are compatible or whether a block and normal pointer
8790 /// are compatible. It is more restrict than comparing two function pointer
8791 // types.
8792 static Sema::AssignConvertType
8793 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
8794                                     QualType RHSType) {
8795   assert(LHSType.isCanonical() && "LHS not canonicalized!");
8796   assert(RHSType.isCanonical() && "RHS not canonicalized!");
8797 
8798   QualType lhptee, rhptee;
8799 
8800   // get the "pointed to" type (ignoring qualifiers at the top level)
8801   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
8802   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
8803 
8804   // In C++, the types have to match exactly.
8805   if (S.getLangOpts().CPlusPlus)
8806     return Sema::IncompatibleBlockPointer;
8807 
8808   Sema::AssignConvertType ConvTy = Sema::Compatible;
8809 
8810   // For blocks we enforce that qualifiers are identical.
8811   Qualifiers LQuals = lhptee.getLocalQualifiers();
8812   Qualifiers RQuals = rhptee.getLocalQualifiers();
8813   if (S.getLangOpts().OpenCL) {
8814     LQuals.removeAddressSpace();
8815     RQuals.removeAddressSpace();
8816   }
8817   if (LQuals != RQuals)
8818     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
8819 
8820   // FIXME: OpenCL doesn't define the exact compile time semantics for a block
8821   // assignment.
8822   // The current behavior is similar to C++ lambdas. A block might be
8823   // assigned to a variable iff its return type and parameters are compatible
8824   // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
8825   // an assignment. Presumably it should behave in way that a function pointer
8826   // assignment does in C, so for each parameter and return type:
8827   //  * CVR and address space of LHS should be a superset of CVR and address
8828   //  space of RHS.
8829   //  * unqualified types should be compatible.
8830   if (S.getLangOpts().OpenCL) {
8831     if (!S.Context.typesAreBlockPointerCompatible(
8832             S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
8833             S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
8834       return Sema::IncompatibleBlockPointer;
8835   } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
8836     return Sema::IncompatibleBlockPointer;
8837 
8838   return ConvTy;
8839 }
8840 
8841 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
8842 /// for assignment compatibility.
8843 static Sema::AssignConvertType
8844 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
8845                                    QualType RHSType) {
8846   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
8847   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
8848 
8849   if (LHSType->isObjCBuiltinType()) {
8850     // Class is not compatible with ObjC object pointers.
8851     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
8852         !RHSType->isObjCQualifiedClassType())
8853       return Sema::IncompatiblePointer;
8854     return Sema::Compatible;
8855   }
8856   if (RHSType->isObjCBuiltinType()) {
8857     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
8858         !LHSType->isObjCQualifiedClassType())
8859       return Sema::IncompatiblePointer;
8860     return Sema::Compatible;
8861   }
8862   QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
8863   QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
8864 
8865   if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
8866       // make an exception for id<P>
8867       !LHSType->isObjCQualifiedIdType())
8868     return Sema::CompatiblePointerDiscardsQualifiers;
8869 
8870   if (S.Context.typesAreCompatible(LHSType, RHSType))
8871     return Sema::Compatible;
8872   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
8873     return Sema::IncompatibleObjCQualifiedId;
8874   return Sema::IncompatiblePointer;
8875 }
8876 
8877 Sema::AssignConvertType
8878 Sema::CheckAssignmentConstraints(SourceLocation Loc,
8879                                  QualType LHSType, QualType RHSType) {
8880   // Fake up an opaque expression.  We don't actually care about what
8881   // cast operations are required, so if CheckAssignmentConstraints
8882   // adds casts to this they'll be wasted, but fortunately that doesn't
8883   // usually happen on valid code.
8884   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
8885   ExprResult RHSPtr = &RHSExpr;
8886   CastKind K;
8887 
8888   return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
8889 }
8890 
8891 /// This helper function returns true if QT is a vector type that has element
8892 /// type ElementType.
8893 static bool isVector(QualType QT, QualType ElementType) {
8894   if (const VectorType *VT = QT->getAs<VectorType>())
8895     return VT->getElementType().getCanonicalType() == ElementType;
8896   return false;
8897 }
8898 
8899 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
8900 /// has code to accommodate several GCC extensions when type checking
8901 /// pointers. Here are some objectionable examples that GCC considers warnings:
8902 ///
8903 ///  int a, *pint;
8904 ///  short *pshort;
8905 ///  struct foo *pfoo;
8906 ///
8907 ///  pint = pshort; // warning: assignment from incompatible pointer type
8908 ///  a = pint; // warning: assignment makes integer from pointer without a cast
8909 ///  pint = a; // warning: assignment makes pointer from integer without a cast
8910 ///  pint = pfoo; // warning: assignment from incompatible pointer type
8911 ///
8912 /// As a result, the code for dealing with pointers is more complex than the
8913 /// C99 spec dictates.
8914 ///
8915 /// Sets 'Kind' for any result kind except Incompatible.
8916 Sema::AssignConvertType
8917 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
8918                                  CastKind &Kind, bool ConvertRHS) {
8919   QualType RHSType = RHS.get()->getType();
8920   QualType OrigLHSType = LHSType;
8921 
8922   // Get canonical types.  We're not formatting these types, just comparing
8923   // them.
8924   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
8925   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
8926 
8927   // Common case: no conversion required.
8928   if (LHSType == RHSType) {
8929     Kind = CK_NoOp;
8930     return Compatible;
8931   }
8932 
8933   // If we have an atomic type, try a non-atomic assignment, then just add an
8934   // atomic qualification step.
8935   if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
8936     Sema::AssignConvertType result =
8937       CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
8938     if (result != Compatible)
8939       return result;
8940     if (Kind != CK_NoOp && ConvertRHS)
8941       RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
8942     Kind = CK_NonAtomicToAtomic;
8943     return Compatible;
8944   }
8945 
8946   // If the left-hand side is a reference type, then we are in a
8947   // (rare!) case where we've allowed the use of references in C,
8948   // e.g., as a parameter type in a built-in function. In this case,
8949   // just make sure that the type referenced is compatible with the
8950   // right-hand side type. The caller is responsible for adjusting
8951   // LHSType so that the resulting expression does not have reference
8952   // type.
8953   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
8954     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
8955       Kind = CK_LValueBitCast;
8956       return Compatible;
8957     }
8958     return Incompatible;
8959   }
8960 
8961   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
8962   // to the same ExtVector type.
8963   if (LHSType->isExtVectorType()) {
8964     if (RHSType->isExtVectorType())
8965       return Incompatible;
8966     if (RHSType->isArithmeticType()) {
8967       // CK_VectorSplat does T -> vector T, so first cast to the element type.
8968       if (ConvertRHS)
8969         RHS = prepareVectorSplat(LHSType, RHS.get());
8970       Kind = CK_VectorSplat;
8971       return Compatible;
8972     }
8973   }
8974 
8975   // Conversions to or from vector type.
8976   if (LHSType->isVectorType() || RHSType->isVectorType()) {
8977     if (LHSType->isVectorType() && RHSType->isVectorType()) {
8978       // Allow assignments of an AltiVec vector type to an equivalent GCC
8979       // vector type and vice versa
8980       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
8981         Kind = CK_BitCast;
8982         return Compatible;
8983       }
8984 
8985       // If we are allowing lax vector conversions, and LHS and RHS are both
8986       // vectors, the total size only needs to be the same. This is a bitcast;
8987       // no bits are changed but the result type is different.
8988       if (isLaxVectorConversion(RHSType, LHSType)) {
8989         Kind = CK_BitCast;
8990         return IncompatibleVectors;
8991       }
8992     }
8993 
8994     // When the RHS comes from another lax conversion (e.g. binops between
8995     // scalars and vectors) the result is canonicalized as a vector. When the
8996     // LHS is also a vector, the lax is allowed by the condition above. Handle
8997     // the case where LHS is a scalar.
8998     if (LHSType->isScalarType()) {
8999       const VectorType *VecType = RHSType->getAs<VectorType>();
9000       if (VecType && VecType->getNumElements() == 1 &&
9001           isLaxVectorConversion(RHSType, LHSType)) {
9002         ExprResult *VecExpr = &RHS;
9003         *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
9004         Kind = CK_BitCast;
9005         return Compatible;
9006       }
9007     }
9008 
9009     // Allow assignments between fixed-length and sizeless SVE vectors.
9010     if (((LHSType->isSizelessBuiltinType() && RHSType->isVectorType()) ||
9011          (LHSType->isVectorType() && RHSType->isSizelessBuiltinType())) &&
9012         Context.areCompatibleSveTypes(LHSType, RHSType)) {
9013       Kind = CK_BitCast;
9014       return Compatible;
9015     }
9016 
9017     return Incompatible;
9018   }
9019 
9020   // Diagnose attempts to convert between __float128 and long double where
9021   // such conversions currently can't be handled.
9022   if (unsupportedTypeConversion(*this, LHSType, RHSType))
9023     return Incompatible;
9024 
9025   // Disallow assigning a _Complex to a real type in C++ mode since it simply
9026   // discards the imaginary part.
9027   if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
9028       !LHSType->getAs<ComplexType>())
9029     return Incompatible;
9030 
9031   // Arithmetic conversions.
9032   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
9033       !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
9034     if (ConvertRHS)
9035       Kind = PrepareScalarCast(RHS, LHSType);
9036     return Compatible;
9037   }
9038 
9039   // Conversions to normal pointers.
9040   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
9041     // U* -> T*
9042     if (isa<PointerType>(RHSType)) {
9043       LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9044       LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
9045       if (AddrSpaceL != AddrSpaceR)
9046         Kind = CK_AddressSpaceConversion;
9047       else if (Context.hasCvrSimilarType(RHSType, LHSType))
9048         Kind = CK_NoOp;
9049       else
9050         Kind = CK_BitCast;
9051       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
9052     }
9053 
9054     // int -> T*
9055     if (RHSType->isIntegerType()) {
9056       Kind = CK_IntegralToPointer; // FIXME: null?
9057       return IntToPointer;
9058     }
9059 
9060     // C pointers are not compatible with ObjC object pointers,
9061     // with two exceptions:
9062     if (isa<ObjCObjectPointerType>(RHSType)) {
9063       //  - conversions to void*
9064       if (LHSPointer->getPointeeType()->isVoidType()) {
9065         Kind = CK_BitCast;
9066         return Compatible;
9067       }
9068 
9069       //  - conversions from 'Class' to the redefinition type
9070       if (RHSType->isObjCClassType() &&
9071           Context.hasSameType(LHSType,
9072                               Context.getObjCClassRedefinitionType())) {
9073         Kind = CK_BitCast;
9074         return Compatible;
9075       }
9076 
9077       Kind = CK_BitCast;
9078       return IncompatiblePointer;
9079     }
9080 
9081     // U^ -> void*
9082     if (RHSType->getAs<BlockPointerType>()) {
9083       if (LHSPointer->getPointeeType()->isVoidType()) {
9084         LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9085         LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9086                                 ->getPointeeType()
9087                                 .getAddressSpace();
9088         Kind =
9089             AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9090         return Compatible;
9091       }
9092     }
9093 
9094     return Incompatible;
9095   }
9096 
9097   // Conversions to block pointers.
9098   if (isa<BlockPointerType>(LHSType)) {
9099     // U^ -> T^
9100     if (RHSType->isBlockPointerType()) {
9101       LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
9102                               ->getPointeeType()
9103                               .getAddressSpace();
9104       LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9105                               ->getPointeeType()
9106                               .getAddressSpace();
9107       Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9108       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
9109     }
9110 
9111     // int or null -> T^
9112     if (RHSType->isIntegerType()) {
9113       Kind = CK_IntegralToPointer; // FIXME: null
9114       return IntToBlockPointer;
9115     }
9116 
9117     // id -> T^
9118     if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
9119       Kind = CK_AnyPointerToBlockPointerCast;
9120       return Compatible;
9121     }
9122 
9123     // void* -> T^
9124     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
9125       if (RHSPT->getPointeeType()->isVoidType()) {
9126         Kind = CK_AnyPointerToBlockPointerCast;
9127         return Compatible;
9128       }
9129 
9130     return Incompatible;
9131   }
9132 
9133   // Conversions to Objective-C pointers.
9134   if (isa<ObjCObjectPointerType>(LHSType)) {
9135     // A* -> B*
9136     if (RHSType->isObjCObjectPointerType()) {
9137       Kind = CK_BitCast;
9138       Sema::AssignConvertType result =
9139         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
9140       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9141           result == Compatible &&
9142           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
9143         result = IncompatibleObjCWeakRef;
9144       return result;
9145     }
9146 
9147     // int or null -> A*
9148     if (RHSType->isIntegerType()) {
9149       Kind = CK_IntegralToPointer; // FIXME: null
9150       return IntToPointer;
9151     }
9152 
9153     // In general, C pointers are not compatible with ObjC object pointers,
9154     // with two exceptions:
9155     if (isa<PointerType>(RHSType)) {
9156       Kind = CK_CPointerToObjCPointerCast;
9157 
9158       //  - conversions from 'void*'
9159       if (RHSType->isVoidPointerType()) {
9160         return Compatible;
9161       }
9162 
9163       //  - conversions to 'Class' from its redefinition type
9164       if (LHSType->isObjCClassType() &&
9165           Context.hasSameType(RHSType,
9166                               Context.getObjCClassRedefinitionType())) {
9167         return Compatible;
9168       }
9169 
9170       return IncompatiblePointer;
9171     }
9172 
9173     // Only under strict condition T^ is compatible with an Objective-C pointer.
9174     if (RHSType->isBlockPointerType() &&
9175         LHSType->isBlockCompatibleObjCPointerType(Context)) {
9176       if (ConvertRHS)
9177         maybeExtendBlockObject(RHS);
9178       Kind = CK_BlockPointerToObjCPointerCast;
9179       return Compatible;
9180     }
9181 
9182     return Incompatible;
9183   }
9184 
9185   // Conversions from pointers that are not covered by the above.
9186   if (isa<PointerType>(RHSType)) {
9187     // T* -> _Bool
9188     if (LHSType == Context.BoolTy) {
9189       Kind = CK_PointerToBoolean;
9190       return Compatible;
9191     }
9192 
9193     // T* -> int
9194     if (LHSType->isIntegerType()) {
9195       Kind = CK_PointerToIntegral;
9196       return PointerToInt;
9197     }
9198 
9199     return Incompatible;
9200   }
9201 
9202   // Conversions from Objective-C pointers that are not covered by the above.
9203   if (isa<ObjCObjectPointerType>(RHSType)) {
9204     // T* -> _Bool
9205     if (LHSType == Context.BoolTy) {
9206       Kind = CK_PointerToBoolean;
9207       return Compatible;
9208     }
9209 
9210     // T* -> int
9211     if (LHSType->isIntegerType()) {
9212       Kind = CK_PointerToIntegral;
9213       return PointerToInt;
9214     }
9215 
9216     return Incompatible;
9217   }
9218 
9219   // struct A -> struct B
9220   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
9221     if (Context.typesAreCompatible(LHSType, RHSType)) {
9222       Kind = CK_NoOp;
9223       return Compatible;
9224     }
9225   }
9226 
9227   if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
9228     Kind = CK_IntToOCLSampler;
9229     return Compatible;
9230   }
9231 
9232   return Incompatible;
9233 }
9234 
9235 /// Constructs a transparent union from an expression that is
9236 /// used to initialize the transparent union.
9237 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
9238                                       ExprResult &EResult, QualType UnionType,
9239                                       FieldDecl *Field) {
9240   // Build an initializer list that designates the appropriate member
9241   // of the transparent union.
9242   Expr *E = EResult.get();
9243   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
9244                                                    E, SourceLocation());
9245   Initializer->setType(UnionType);
9246   Initializer->setInitializedFieldInUnion(Field);
9247 
9248   // Build a compound literal constructing a value of the transparent
9249   // union type from this initializer list.
9250   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
9251   EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
9252                                         VK_RValue, Initializer, false);
9253 }
9254 
9255 Sema::AssignConvertType
9256 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
9257                                                ExprResult &RHS) {
9258   QualType RHSType = RHS.get()->getType();
9259 
9260   // If the ArgType is a Union type, we want to handle a potential
9261   // transparent_union GCC extension.
9262   const RecordType *UT = ArgType->getAsUnionType();
9263   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
9264     return Incompatible;
9265 
9266   // The field to initialize within the transparent union.
9267   RecordDecl *UD = UT->getDecl();
9268   FieldDecl *InitField = nullptr;
9269   // It's compatible if the expression matches any of the fields.
9270   for (auto *it : UD->fields()) {
9271     if (it->getType()->isPointerType()) {
9272       // If the transparent union contains a pointer type, we allow:
9273       // 1) void pointer
9274       // 2) null pointer constant
9275       if (RHSType->isPointerType())
9276         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
9277           RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
9278           InitField = it;
9279           break;
9280         }
9281 
9282       if (RHS.get()->isNullPointerConstant(Context,
9283                                            Expr::NPC_ValueDependentIsNull)) {
9284         RHS = ImpCastExprToType(RHS.get(), it->getType(),
9285                                 CK_NullToPointer);
9286         InitField = it;
9287         break;
9288       }
9289     }
9290 
9291     CastKind Kind;
9292     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
9293           == Compatible) {
9294       RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
9295       InitField = it;
9296       break;
9297     }
9298   }
9299 
9300   if (!InitField)
9301     return Incompatible;
9302 
9303   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
9304   return Compatible;
9305 }
9306 
9307 Sema::AssignConvertType
9308 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
9309                                        bool Diagnose,
9310                                        bool DiagnoseCFAudited,
9311                                        bool ConvertRHS) {
9312   // We need to be able to tell the caller whether we diagnosed a problem, if
9313   // they ask us to issue diagnostics.
9314   assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
9315 
9316   // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
9317   // we can't avoid *all* modifications at the moment, so we need some somewhere
9318   // to put the updated value.
9319   ExprResult LocalRHS = CallerRHS;
9320   ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
9321 
9322   if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
9323     if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
9324       if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
9325           !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
9326         Diag(RHS.get()->getExprLoc(),
9327              diag::warn_noderef_to_dereferenceable_pointer)
9328             << RHS.get()->getSourceRange();
9329       }
9330     }
9331   }
9332 
9333   if (getLangOpts().CPlusPlus) {
9334     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
9335       // C++ 5.17p3: If the left operand is not of class type, the
9336       // expression is implicitly converted (C++ 4) to the
9337       // cv-unqualified type of the left operand.
9338       QualType RHSType = RHS.get()->getType();
9339       if (Diagnose) {
9340         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9341                                         AA_Assigning);
9342       } else {
9343         ImplicitConversionSequence ICS =
9344             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9345                                   /*SuppressUserConversions=*/false,
9346                                   AllowedExplicit::None,
9347                                   /*InOverloadResolution=*/false,
9348                                   /*CStyle=*/false,
9349                                   /*AllowObjCWritebackConversion=*/false);
9350         if (ICS.isFailure())
9351           return Incompatible;
9352         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9353                                         ICS, AA_Assigning);
9354       }
9355       if (RHS.isInvalid())
9356         return Incompatible;
9357       Sema::AssignConvertType result = Compatible;
9358       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9359           !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
9360         result = IncompatibleObjCWeakRef;
9361       return result;
9362     }
9363 
9364     // FIXME: Currently, we fall through and treat C++ classes like C
9365     // structures.
9366     // FIXME: We also fall through for atomics; not sure what should
9367     // happen there, though.
9368   } else if (RHS.get()->getType() == Context.OverloadTy) {
9369     // As a set of extensions to C, we support overloading on functions. These
9370     // functions need to be resolved here.
9371     DeclAccessPair DAP;
9372     if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
9373             RHS.get(), LHSType, /*Complain=*/false, DAP))
9374       RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
9375     else
9376       return Incompatible;
9377   }
9378 
9379   // C99 6.5.16.1p1: the left operand is a pointer and the right is
9380   // a null pointer constant.
9381   if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
9382        LHSType->isBlockPointerType()) &&
9383       RHS.get()->isNullPointerConstant(Context,
9384                                        Expr::NPC_ValueDependentIsNull)) {
9385     if (Diagnose || ConvertRHS) {
9386       CastKind Kind;
9387       CXXCastPath Path;
9388       CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
9389                              /*IgnoreBaseAccess=*/false, Diagnose);
9390       if (ConvertRHS)
9391         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
9392     }
9393     return Compatible;
9394   }
9395 
9396   // OpenCL queue_t type assignment.
9397   if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
9398                                  Context, Expr::NPC_ValueDependentIsNull)) {
9399     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9400     return Compatible;
9401   }
9402 
9403   // This check seems unnatural, however it is necessary to ensure the proper
9404   // conversion of functions/arrays. If the conversion were done for all
9405   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
9406   // expressions that suppress this implicit conversion (&, sizeof).
9407   //
9408   // Suppress this for references: C++ 8.5.3p5.
9409   if (!LHSType->isReferenceType()) {
9410     // FIXME: We potentially allocate here even if ConvertRHS is false.
9411     RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
9412     if (RHS.isInvalid())
9413       return Incompatible;
9414   }
9415   CastKind Kind;
9416   Sema::AssignConvertType result =
9417     CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
9418 
9419   // C99 6.5.16.1p2: The value of the right operand is converted to the
9420   // type of the assignment expression.
9421   // CheckAssignmentConstraints allows the left-hand side to be a reference,
9422   // so that we can use references in built-in functions even in C.
9423   // The getNonReferenceType() call makes sure that the resulting expression
9424   // does not have reference type.
9425   if (result != Incompatible && RHS.get()->getType() != LHSType) {
9426     QualType Ty = LHSType.getNonLValueExprType(Context);
9427     Expr *E = RHS.get();
9428 
9429     // Check for various Objective-C errors. If we are not reporting
9430     // diagnostics and just checking for errors, e.g., during overload
9431     // resolution, return Incompatible to indicate the failure.
9432     if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9433         CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
9434                             Diagnose, DiagnoseCFAudited) != ACR_okay) {
9435       if (!Diagnose)
9436         return Incompatible;
9437     }
9438     if (getLangOpts().ObjC &&
9439         (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType,
9440                                            E->getType(), E, Diagnose) ||
9441          CheckConversionToObjCLiteral(LHSType, E, Diagnose))) {
9442       if (!Diagnose)
9443         return Incompatible;
9444       // Replace the expression with a corrected version and continue so we
9445       // can find further errors.
9446       RHS = E;
9447       return Compatible;
9448     }
9449 
9450     if (ConvertRHS)
9451       RHS = ImpCastExprToType(E, Ty, Kind);
9452   }
9453 
9454   return result;
9455 }
9456 
9457 namespace {
9458 /// The original operand to an operator, prior to the application of the usual
9459 /// arithmetic conversions and converting the arguments of a builtin operator
9460 /// candidate.
9461 struct OriginalOperand {
9462   explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
9463     if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op))
9464       Op = MTE->getSubExpr();
9465     if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op))
9466       Op = BTE->getSubExpr();
9467     if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) {
9468       Orig = ICE->getSubExprAsWritten();
9469       Conversion = ICE->getConversionFunction();
9470     }
9471   }
9472 
9473   QualType getType() const { return Orig->getType(); }
9474 
9475   Expr *Orig;
9476   NamedDecl *Conversion;
9477 };
9478 }
9479 
9480 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
9481                                ExprResult &RHS) {
9482   OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
9483 
9484   Diag(Loc, diag::err_typecheck_invalid_operands)
9485     << OrigLHS.getType() << OrigRHS.getType()
9486     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9487 
9488   // If a user-defined conversion was applied to either of the operands prior
9489   // to applying the built-in operator rules, tell the user about it.
9490   if (OrigLHS.Conversion) {
9491     Diag(OrigLHS.Conversion->getLocation(),
9492          diag::note_typecheck_invalid_operands_converted)
9493       << 0 << LHS.get()->getType();
9494   }
9495   if (OrigRHS.Conversion) {
9496     Diag(OrigRHS.Conversion->getLocation(),
9497          diag::note_typecheck_invalid_operands_converted)
9498       << 1 << RHS.get()->getType();
9499   }
9500 
9501   return QualType();
9502 }
9503 
9504 // Diagnose cases where a scalar was implicitly converted to a vector and
9505 // diagnose the underlying types. Otherwise, diagnose the error
9506 // as invalid vector logical operands for non-C++ cases.
9507 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
9508                                             ExprResult &RHS) {
9509   QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
9510   QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
9511 
9512   bool LHSNatVec = LHSType->isVectorType();
9513   bool RHSNatVec = RHSType->isVectorType();
9514 
9515   if (!(LHSNatVec && RHSNatVec)) {
9516     Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
9517     Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
9518     Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
9519         << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
9520         << Vector->getSourceRange();
9521     return QualType();
9522   }
9523 
9524   Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
9525       << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
9526       << RHS.get()->getSourceRange();
9527 
9528   return QualType();
9529 }
9530 
9531 /// Try to convert a value of non-vector type to a vector type by converting
9532 /// the type to the element type of the vector and then performing a splat.
9533 /// If the language is OpenCL, we only use conversions that promote scalar
9534 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
9535 /// for float->int.
9536 ///
9537 /// OpenCL V2.0 6.2.6.p2:
9538 /// An error shall occur if any scalar operand type has greater rank
9539 /// than the type of the vector element.
9540 ///
9541 /// \param scalar - if non-null, actually perform the conversions
9542 /// \return true if the operation fails (but without diagnosing the failure)
9543 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
9544                                      QualType scalarTy,
9545                                      QualType vectorEltTy,
9546                                      QualType vectorTy,
9547                                      unsigned &DiagID) {
9548   // The conversion to apply to the scalar before splatting it,
9549   // if necessary.
9550   CastKind scalarCast = CK_NoOp;
9551 
9552   if (vectorEltTy->isIntegralType(S.Context)) {
9553     if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
9554         (scalarTy->isIntegerType() &&
9555          S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
9556       DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
9557       return true;
9558     }
9559     if (!scalarTy->isIntegralType(S.Context))
9560       return true;
9561     scalarCast = CK_IntegralCast;
9562   } else if (vectorEltTy->isRealFloatingType()) {
9563     if (scalarTy->isRealFloatingType()) {
9564       if (S.getLangOpts().OpenCL &&
9565           S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
9566         DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
9567         return true;
9568       }
9569       scalarCast = CK_FloatingCast;
9570     }
9571     else if (scalarTy->isIntegralType(S.Context))
9572       scalarCast = CK_IntegralToFloating;
9573     else
9574       return true;
9575   } else {
9576     return true;
9577   }
9578 
9579   // Adjust scalar if desired.
9580   if (scalar) {
9581     if (scalarCast != CK_NoOp)
9582       *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
9583     *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
9584   }
9585   return false;
9586 }
9587 
9588 /// Convert vector E to a vector with the same number of elements but different
9589 /// element type.
9590 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
9591   const auto *VecTy = E->getType()->getAs<VectorType>();
9592   assert(VecTy && "Expression E must be a vector");
9593   QualType NewVecTy = S.Context.getVectorType(ElementType,
9594                                               VecTy->getNumElements(),
9595                                               VecTy->getVectorKind());
9596 
9597   // Look through the implicit cast. Return the subexpression if its type is
9598   // NewVecTy.
9599   if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
9600     if (ICE->getSubExpr()->getType() == NewVecTy)
9601       return ICE->getSubExpr();
9602 
9603   auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
9604   return S.ImpCastExprToType(E, NewVecTy, Cast);
9605 }
9606 
9607 /// Test if a (constant) integer Int can be casted to another integer type
9608 /// IntTy without losing precision.
9609 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int,
9610                                       QualType OtherIntTy) {
9611   QualType IntTy = Int->get()->getType().getUnqualifiedType();
9612 
9613   // Reject cases where the value of the Int is unknown as that would
9614   // possibly cause truncation, but accept cases where the scalar can be
9615   // demoted without loss of precision.
9616   Expr::EvalResult EVResult;
9617   bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
9618   int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
9619   bool IntSigned = IntTy->hasSignedIntegerRepresentation();
9620   bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
9621 
9622   if (CstInt) {
9623     // If the scalar is constant and is of a higher order and has more active
9624     // bits that the vector element type, reject it.
9625     llvm::APSInt Result = EVResult.Val.getInt();
9626     unsigned NumBits = IntSigned
9627                            ? (Result.isNegative() ? Result.getMinSignedBits()
9628                                                   : Result.getActiveBits())
9629                            : Result.getActiveBits();
9630     if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
9631       return true;
9632 
9633     // If the signedness of the scalar type and the vector element type
9634     // differs and the number of bits is greater than that of the vector
9635     // element reject it.
9636     return (IntSigned != OtherIntSigned &&
9637             NumBits > S.Context.getIntWidth(OtherIntTy));
9638   }
9639 
9640   // Reject cases where the value of the scalar is not constant and it's
9641   // order is greater than that of the vector element type.
9642   return (Order < 0);
9643 }
9644 
9645 /// Test if a (constant) integer Int can be casted to floating point type
9646 /// FloatTy without losing precision.
9647 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int,
9648                                      QualType FloatTy) {
9649   QualType IntTy = Int->get()->getType().getUnqualifiedType();
9650 
9651   // Determine if the integer constant can be expressed as a floating point
9652   // number of the appropriate type.
9653   Expr::EvalResult EVResult;
9654   bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
9655 
9656   uint64_t Bits = 0;
9657   if (CstInt) {
9658     // Reject constants that would be truncated if they were converted to
9659     // the floating point type. Test by simple to/from conversion.
9660     // FIXME: Ideally the conversion to an APFloat and from an APFloat
9661     //        could be avoided if there was a convertFromAPInt method
9662     //        which could signal back if implicit truncation occurred.
9663     llvm::APSInt Result = EVResult.Val.getInt();
9664     llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
9665     Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
9666                            llvm::APFloat::rmTowardZero);
9667     llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
9668                              !IntTy->hasSignedIntegerRepresentation());
9669     bool Ignored = false;
9670     Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
9671                            &Ignored);
9672     if (Result != ConvertBack)
9673       return true;
9674   } else {
9675     // Reject types that cannot be fully encoded into the mantissa of
9676     // the float.
9677     Bits = S.Context.getTypeSize(IntTy);
9678     unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
9679         S.Context.getFloatTypeSemantics(FloatTy));
9680     if (Bits > FloatPrec)
9681       return true;
9682   }
9683 
9684   return false;
9685 }
9686 
9687 /// Attempt to convert and splat Scalar into a vector whose types matches
9688 /// Vector following GCC conversion rules. The rule is that implicit
9689 /// conversion can occur when Scalar can be casted to match Vector's element
9690 /// type without causing truncation of Scalar.
9691 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar,
9692                                         ExprResult *Vector) {
9693   QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
9694   QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
9695   const VectorType *VT = VectorTy->getAs<VectorType>();
9696 
9697   assert(!isa<ExtVectorType>(VT) &&
9698          "ExtVectorTypes should not be handled here!");
9699 
9700   QualType VectorEltTy = VT->getElementType();
9701 
9702   // Reject cases where the vector element type or the scalar element type are
9703   // not integral or floating point types.
9704   if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
9705     return true;
9706 
9707   // The conversion to apply to the scalar before splatting it,
9708   // if necessary.
9709   CastKind ScalarCast = CK_NoOp;
9710 
9711   // Accept cases where the vector elements are integers and the scalar is
9712   // an integer.
9713   // FIXME: Notionally if the scalar was a floating point value with a precise
9714   //        integral representation, we could cast it to an appropriate integer
9715   //        type and then perform the rest of the checks here. GCC will perform
9716   //        this conversion in some cases as determined by the input language.
9717   //        We should accept it on a language independent basis.
9718   if (VectorEltTy->isIntegralType(S.Context) &&
9719       ScalarTy->isIntegralType(S.Context) &&
9720       S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
9721 
9722     if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
9723       return true;
9724 
9725     ScalarCast = CK_IntegralCast;
9726   } else if (VectorEltTy->isIntegralType(S.Context) &&
9727              ScalarTy->isRealFloatingType()) {
9728     if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy))
9729       ScalarCast = CK_FloatingToIntegral;
9730     else
9731       return true;
9732   } else if (VectorEltTy->isRealFloatingType()) {
9733     if (ScalarTy->isRealFloatingType()) {
9734 
9735       // Reject cases where the scalar type is not a constant and has a higher
9736       // Order than the vector element type.
9737       llvm::APFloat Result(0.0);
9738 
9739       // Determine whether this is a constant scalar. In the event that the
9740       // value is dependent (and thus cannot be evaluated by the constant
9741       // evaluator), skip the evaluation. This will then diagnose once the
9742       // expression is instantiated.
9743       bool CstScalar = Scalar->get()->isValueDependent() ||
9744                        Scalar->get()->EvaluateAsFloat(Result, S.Context);
9745       int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
9746       if (!CstScalar && Order < 0)
9747         return true;
9748 
9749       // If the scalar cannot be safely casted to the vector element type,
9750       // reject it.
9751       if (CstScalar) {
9752         bool Truncated = false;
9753         Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
9754                        llvm::APFloat::rmNearestTiesToEven, &Truncated);
9755         if (Truncated)
9756           return true;
9757       }
9758 
9759       ScalarCast = CK_FloatingCast;
9760     } else if (ScalarTy->isIntegralType(S.Context)) {
9761       if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
9762         return true;
9763 
9764       ScalarCast = CK_IntegralToFloating;
9765     } else
9766       return true;
9767   } else if (ScalarTy->isEnumeralType())
9768     return true;
9769 
9770   // Adjust scalar if desired.
9771   if (Scalar) {
9772     if (ScalarCast != CK_NoOp)
9773       *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
9774     *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
9775   }
9776   return false;
9777 }
9778 
9779 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
9780                                    SourceLocation Loc, bool IsCompAssign,
9781                                    bool AllowBothBool,
9782                                    bool AllowBoolConversions) {
9783   if (!IsCompAssign) {
9784     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
9785     if (LHS.isInvalid())
9786       return QualType();
9787   }
9788   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
9789   if (RHS.isInvalid())
9790     return QualType();
9791 
9792   // For conversion purposes, we ignore any qualifiers.
9793   // For example, "const float" and "float" are equivalent.
9794   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
9795   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
9796 
9797   const VectorType *LHSVecType = LHSType->getAs<VectorType>();
9798   const VectorType *RHSVecType = RHSType->getAs<VectorType>();
9799   assert(LHSVecType || RHSVecType);
9800 
9801   if ((LHSVecType && LHSVecType->getElementType()->isBFloat16Type()) ||
9802       (RHSVecType && RHSVecType->getElementType()->isBFloat16Type()))
9803     return InvalidOperands(Loc, LHS, RHS);
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   // Returns true if the operands are SVE VLA and VLS types.
9908   auto IsSveConversion = [](QualType FirstType, QualType SecondType) {
9909     const VectorType *VecType = SecondType->getAs<VectorType>();
9910     return FirstType->isSizelessBuiltinType() && VecType &&
9911            (VecType->getVectorKind() == VectorType::SveFixedLengthDataVector ||
9912             VecType->getVectorKind() ==
9913                 VectorType::SveFixedLengthPredicateVector);
9914   };
9915 
9916   // If there's a sizeless and fixed-length operand, diagnose that.
9917   if (IsSveConversion(LHSType, RHSType) || IsSveConversion(RHSType, LHSType)) {
9918     Diag(Loc, diag::err_typecheck_vector_not_convertable_sizeless)
9919         << LHSType << RHSType;
9920     return QualType();
9921   }
9922 
9923   // If there's a non-vector, non-real operand, diagnose that.
9924   if ((!RHSVecType && !RHSType->isRealType()) ||
9925       (!LHSVecType && !LHSType->isRealType())) {
9926     Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
9927       << LHSType << RHSType
9928       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9929     return QualType();
9930   }
9931 
9932   // OpenCL V1.1 6.2.6.p1:
9933   // If the operands are of more than one vector type, then an error shall
9934   // occur. Implicit conversions between vector types are not permitted, per
9935   // section 6.2.1.
9936   if (getLangOpts().OpenCL &&
9937       RHSVecType && isa<ExtVectorType>(RHSVecType) &&
9938       LHSVecType && isa<ExtVectorType>(LHSVecType)) {
9939     Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
9940                                                            << RHSType;
9941     return QualType();
9942   }
9943 
9944 
9945   // If there is a vector type that is not a ExtVector and a scalar, we reach
9946   // this point if scalar could not be converted to the vector's element type
9947   // without truncation.
9948   if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
9949       (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
9950     QualType Scalar = LHSVecType ? RHSType : LHSType;
9951     QualType Vector = LHSVecType ? LHSType : RHSType;
9952     unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
9953     Diag(Loc,
9954          diag::err_typecheck_vector_not_convertable_implict_truncation)
9955         << ScalarOrVector << Scalar << Vector;
9956 
9957     return QualType();
9958   }
9959 
9960   // Otherwise, use the generic diagnostic.
9961   Diag(Loc, DiagID)
9962     << LHSType << RHSType
9963     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9964   return QualType();
9965 }
9966 
9967 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
9968 // expression.  These are mainly cases where the null pointer is used as an
9969 // integer instead of a pointer.
9970 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
9971                                 SourceLocation Loc, bool IsCompare) {
9972   // The canonical way to check for a GNU null is with isNullPointerConstant,
9973   // but we use a bit of a hack here for speed; this is a relatively
9974   // hot path, and isNullPointerConstant is slow.
9975   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
9976   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
9977 
9978   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
9979 
9980   // Avoid analyzing cases where the result will either be invalid (and
9981   // diagnosed as such) or entirely valid and not something to warn about.
9982   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
9983       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
9984     return;
9985 
9986   // Comparison operations would not make sense with a null pointer no matter
9987   // what the other expression is.
9988   if (!IsCompare) {
9989     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
9990         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
9991         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
9992     return;
9993   }
9994 
9995   // The rest of the operations only make sense with a null pointer
9996   // if the other expression is a pointer.
9997   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
9998       NonNullType->canDecayToPointerType())
9999     return;
10000 
10001   S.Diag(Loc, diag::warn_null_in_comparison_operation)
10002       << LHSNull /* LHS is NULL */ << NonNullType
10003       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10004 }
10005 
10006 static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS,
10007                                           SourceLocation Loc) {
10008   const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS);
10009   const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS);
10010   if (!LUE || !RUE)
10011     return;
10012   if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
10013       RUE->getKind() != UETT_SizeOf)
10014     return;
10015 
10016   const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens();
10017   QualType LHSTy = LHSArg->getType();
10018   QualType RHSTy;
10019 
10020   if (RUE->isArgumentType())
10021     RHSTy = RUE->getArgumentType();
10022   else
10023     RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
10024 
10025   if (LHSTy->isPointerType() && !RHSTy->isPointerType()) {
10026     if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy))
10027       return;
10028 
10029     S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
10030     if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
10031       if (const ValueDecl *LHSArgDecl = DRE->getDecl())
10032         S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here)
10033             << LHSArgDecl;
10034     }
10035   } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) {
10036     QualType ArrayElemTy = ArrayTy->getElementType();
10037     if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) ||
10038         ArrayElemTy->isDependentType() || RHSTy->isDependentType() ||
10039         RHSTy->isReferenceType() || ArrayElemTy->isCharType() ||
10040         S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy))
10041       return;
10042     S.Diag(Loc, diag::warn_division_sizeof_array)
10043         << LHSArg->getSourceRange() << ArrayElemTy << RHSTy;
10044     if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
10045       if (const ValueDecl *LHSArgDecl = DRE->getDecl())
10046         S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here)
10047             << LHSArgDecl;
10048     }
10049 
10050     S.Diag(Loc, diag::note_precedence_silence) << RHS;
10051   }
10052 }
10053 
10054 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
10055                                                ExprResult &RHS,
10056                                                SourceLocation Loc, bool IsDiv) {
10057   // Check for division/remainder by zero.
10058   Expr::EvalResult RHSValue;
10059   if (!RHS.get()->isValueDependent() &&
10060       RHS.get()->EvaluateAsInt(RHSValue, S.Context) &&
10061       RHSValue.Val.getInt() == 0)
10062     S.DiagRuntimeBehavior(Loc, RHS.get(),
10063                           S.PDiag(diag::warn_remainder_division_by_zero)
10064                             << IsDiv << RHS.get()->getSourceRange());
10065 }
10066 
10067 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
10068                                            SourceLocation Loc,
10069                                            bool IsCompAssign, bool IsDiv) {
10070   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10071 
10072   if (LHS.get()->getType()->isVectorType() ||
10073       RHS.get()->getType()->isVectorType())
10074     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10075                                /*AllowBothBool*/getLangOpts().AltiVec,
10076                                /*AllowBoolConversions*/false);
10077   if (!IsDiv && (LHS.get()->getType()->isConstantMatrixType() ||
10078                  RHS.get()->getType()->isConstantMatrixType()))
10079     return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign);
10080 
10081   QualType compType = UsualArithmeticConversions(
10082       LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
10083   if (LHS.isInvalid() || RHS.isInvalid())
10084     return QualType();
10085 
10086 
10087   if (compType.isNull() || !compType->isArithmeticType())
10088     return InvalidOperands(Loc, LHS, RHS);
10089   if (IsDiv) {
10090     DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
10091     DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc);
10092   }
10093   return compType;
10094 }
10095 
10096 QualType Sema::CheckRemainderOperands(
10097   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
10098   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10099 
10100   if (LHS.get()->getType()->isVectorType() ||
10101       RHS.get()->getType()->isVectorType()) {
10102     if (LHS.get()->getType()->hasIntegerRepresentation() &&
10103         RHS.get()->getType()->hasIntegerRepresentation())
10104       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10105                                  /*AllowBothBool*/getLangOpts().AltiVec,
10106                                  /*AllowBoolConversions*/false);
10107     return InvalidOperands(Loc, LHS, RHS);
10108   }
10109 
10110   QualType compType = UsualArithmeticConversions(
10111       LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
10112   if (LHS.isInvalid() || RHS.isInvalid())
10113     return QualType();
10114 
10115   if (compType.isNull() || !compType->isIntegerType())
10116     return InvalidOperands(Loc, LHS, RHS);
10117   DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
10118   return compType;
10119 }
10120 
10121 /// Diagnose invalid arithmetic on two void pointers.
10122 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
10123                                                 Expr *LHSExpr, Expr *RHSExpr) {
10124   S.Diag(Loc, S.getLangOpts().CPlusPlus
10125                 ? diag::err_typecheck_pointer_arith_void_type
10126                 : diag::ext_gnu_void_ptr)
10127     << 1 /* two pointers */ << LHSExpr->getSourceRange()
10128                             << RHSExpr->getSourceRange();
10129 }
10130 
10131 /// Diagnose invalid arithmetic on a void pointer.
10132 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
10133                                             Expr *Pointer) {
10134   S.Diag(Loc, S.getLangOpts().CPlusPlus
10135                 ? diag::err_typecheck_pointer_arith_void_type
10136                 : diag::ext_gnu_void_ptr)
10137     << 0 /* one pointer */ << Pointer->getSourceRange();
10138 }
10139 
10140 /// Diagnose invalid arithmetic on a null pointer.
10141 ///
10142 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
10143 /// idiom, which we recognize as a GNU extension.
10144 ///
10145 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc,
10146                                             Expr *Pointer, bool IsGNUIdiom) {
10147   if (IsGNUIdiom)
10148     S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
10149       << Pointer->getSourceRange();
10150   else
10151     S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
10152       << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
10153 }
10154 
10155 /// Diagnose invalid arithmetic on two function pointers.
10156 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
10157                                                     Expr *LHS, Expr *RHS) {
10158   assert(LHS->getType()->isAnyPointerType());
10159   assert(RHS->getType()->isAnyPointerType());
10160   S.Diag(Loc, S.getLangOpts().CPlusPlus
10161                 ? diag::err_typecheck_pointer_arith_function_type
10162                 : diag::ext_gnu_ptr_func_arith)
10163     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
10164     // We only show the second type if it differs from the first.
10165     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
10166                                                    RHS->getType())
10167     << RHS->getType()->getPointeeType()
10168     << LHS->getSourceRange() << RHS->getSourceRange();
10169 }
10170 
10171 /// Diagnose invalid arithmetic on a function pointer.
10172 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
10173                                                 Expr *Pointer) {
10174   assert(Pointer->getType()->isAnyPointerType());
10175   S.Diag(Loc, S.getLangOpts().CPlusPlus
10176                 ? diag::err_typecheck_pointer_arith_function_type
10177                 : diag::ext_gnu_ptr_func_arith)
10178     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
10179     << 0 /* one pointer, so only one type */
10180     << Pointer->getSourceRange();
10181 }
10182 
10183 /// Emit error if Operand is incomplete pointer type
10184 ///
10185 /// \returns True if pointer has incomplete type
10186 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
10187                                                  Expr *Operand) {
10188   QualType ResType = Operand->getType();
10189   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10190     ResType = ResAtomicType->getValueType();
10191 
10192   assert(ResType->isAnyPointerType() && !ResType->isDependentType());
10193   QualType PointeeTy = ResType->getPointeeType();
10194   return S.RequireCompleteSizedType(
10195       Loc, PointeeTy,
10196       diag::err_typecheck_arithmetic_incomplete_or_sizeless_type,
10197       Operand->getSourceRange());
10198 }
10199 
10200 /// Check the validity of an arithmetic pointer operand.
10201 ///
10202 /// If the operand has pointer type, this code will check for pointer types
10203 /// which are invalid in arithmetic operations. These will be diagnosed
10204 /// appropriately, including whether or not the use is supported as an
10205 /// extension.
10206 ///
10207 /// \returns True when the operand is valid to use (even if as an extension).
10208 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
10209                                             Expr *Operand) {
10210   QualType ResType = Operand->getType();
10211   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10212     ResType = ResAtomicType->getValueType();
10213 
10214   if (!ResType->isAnyPointerType()) return true;
10215 
10216   QualType PointeeTy = ResType->getPointeeType();
10217   if (PointeeTy->isVoidType()) {
10218     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
10219     return !S.getLangOpts().CPlusPlus;
10220   }
10221   if (PointeeTy->isFunctionType()) {
10222     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
10223     return !S.getLangOpts().CPlusPlus;
10224   }
10225 
10226   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
10227 
10228   return true;
10229 }
10230 
10231 /// Check the validity of a binary arithmetic operation w.r.t. pointer
10232 /// operands.
10233 ///
10234 /// This routine will diagnose any invalid arithmetic on pointer operands much
10235 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
10236 /// for emitting a single diagnostic even for operations where both LHS and RHS
10237 /// are (potentially problematic) pointers.
10238 ///
10239 /// \returns True when the operand is valid to use (even if as an extension).
10240 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
10241                                                 Expr *LHSExpr, Expr *RHSExpr) {
10242   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
10243   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
10244   if (!isLHSPointer && !isRHSPointer) return true;
10245 
10246   QualType LHSPointeeTy, RHSPointeeTy;
10247   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
10248   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
10249 
10250   // if both are pointers check if operation is valid wrt address spaces
10251   if (isLHSPointer && isRHSPointer) {
10252     if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy)) {
10253       S.Diag(Loc,
10254              diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
10255           << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
10256           << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
10257       return false;
10258     }
10259   }
10260 
10261   // Check for arithmetic on pointers to incomplete types.
10262   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
10263   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
10264   if (isLHSVoidPtr || isRHSVoidPtr) {
10265     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
10266     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
10267     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
10268 
10269     return !S.getLangOpts().CPlusPlus;
10270   }
10271 
10272   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
10273   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
10274   if (isLHSFuncPtr || isRHSFuncPtr) {
10275     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
10276     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
10277                                                                 RHSExpr);
10278     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
10279 
10280     return !S.getLangOpts().CPlusPlus;
10281   }
10282 
10283   if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
10284     return false;
10285   if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
10286     return false;
10287 
10288   return true;
10289 }
10290 
10291 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
10292 /// literal.
10293 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
10294                                   Expr *LHSExpr, Expr *RHSExpr) {
10295   StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
10296   Expr* IndexExpr = RHSExpr;
10297   if (!StrExpr) {
10298     StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
10299     IndexExpr = LHSExpr;
10300   }
10301 
10302   bool IsStringPlusInt = StrExpr &&
10303       IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
10304   if (!IsStringPlusInt || IndexExpr->isValueDependent())
10305     return;
10306 
10307   SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
10308   Self.Diag(OpLoc, diag::warn_string_plus_int)
10309       << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
10310 
10311   // Only print a fixit for "str" + int, not for int + "str".
10312   if (IndexExpr == RHSExpr) {
10313     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
10314     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
10315         << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
10316         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
10317         << FixItHint::CreateInsertion(EndLoc, "]");
10318   } else
10319     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
10320 }
10321 
10322 /// Emit a warning when adding a char literal to a string.
10323 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
10324                                    Expr *LHSExpr, Expr *RHSExpr) {
10325   const Expr *StringRefExpr = LHSExpr;
10326   const CharacterLiteral *CharExpr =
10327       dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
10328 
10329   if (!CharExpr) {
10330     CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
10331     StringRefExpr = RHSExpr;
10332   }
10333 
10334   if (!CharExpr || !StringRefExpr)
10335     return;
10336 
10337   const QualType StringType = StringRefExpr->getType();
10338 
10339   // Return if not a PointerType.
10340   if (!StringType->isAnyPointerType())
10341     return;
10342 
10343   // Return if not a CharacterType.
10344   if (!StringType->getPointeeType()->isAnyCharacterType())
10345     return;
10346 
10347   ASTContext &Ctx = Self.getASTContext();
10348   SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
10349 
10350   const QualType CharType = CharExpr->getType();
10351   if (!CharType->isAnyCharacterType() &&
10352       CharType->isIntegerType() &&
10353       llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
10354     Self.Diag(OpLoc, diag::warn_string_plus_char)
10355         << DiagRange << Ctx.CharTy;
10356   } else {
10357     Self.Diag(OpLoc, diag::warn_string_plus_char)
10358         << DiagRange << CharExpr->getType();
10359   }
10360 
10361   // Only print a fixit for str + char, not for char + str.
10362   if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
10363     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
10364     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
10365         << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
10366         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
10367         << FixItHint::CreateInsertion(EndLoc, "]");
10368   } else {
10369     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
10370   }
10371 }
10372 
10373 /// Emit error when two pointers are incompatible.
10374 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
10375                                            Expr *LHSExpr, Expr *RHSExpr) {
10376   assert(LHSExpr->getType()->isAnyPointerType());
10377   assert(RHSExpr->getType()->isAnyPointerType());
10378   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
10379     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
10380     << RHSExpr->getSourceRange();
10381 }
10382 
10383 // C99 6.5.6
10384 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
10385                                      SourceLocation Loc, BinaryOperatorKind Opc,
10386                                      QualType* CompLHSTy) {
10387   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10388 
10389   if (LHS.get()->getType()->isVectorType() ||
10390       RHS.get()->getType()->isVectorType()) {
10391     QualType compType = CheckVectorOperands(
10392         LHS, RHS, Loc, CompLHSTy,
10393         /*AllowBothBool*/getLangOpts().AltiVec,
10394         /*AllowBoolConversions*/getLangOpts().ZVector);
10395     if (CompLHSTy) *CompLHSTy = compType;
10396     return compType;
10397   }
10398 
10399   if (LHS.get()->getType()->isConstantMatrixType() ||
10400       RHS.get()->getType()->isConstantMatrixType()) {
10401     return CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
10402   }
10403 
10404   QualType compType = UsualArithmeticConversions(
10405       LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
10406   if (LHS.isInvalid() || RHS.isInvalid())
10407     return QualType();
10408 
10409   // Diagnose "string literal" '+' int and string '+' "char literal".
10410   if (Opc == BO_Add) {
10411     diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
10412     diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
10413   }
10414 
10415   // handle the common case first (both operands are arithmetic).
10416   if (!compType.isNull() && compType->isArithmeticType()) {
10417     if (CompLHSTy) *CompLHSTy = compType;
10418     return compType;
10419   }
10420 
10421   // Type-checking.  Ultimately the pointer's going to be in PExp;
10422   // note that we bias towards the LHS being the pointer.
10423   Expr *PExp = LHS.get(), *IExp = RHS.get();
10424 
10425   bool isObjCPointer;
10426   if (PExp->getType()->isPointerType()) {
10427     isObjCPointer = false;
10428   } else if (PExp->getType()->isObjCObjectPointerType()) {
10429     isObjCPointer = true;
10430   } else {
10431     std::swap(PExp, IExp);
10432     if (PExp->getType()->isPointerType()) {
10433       isObjCPointer = false;
10434     } else if (PExp->getType()->isObjCObjectPointerType()) {
10435       isObjCPointer = true;
10436     } else {
10437       return InvalidOperands(Loc, LHS, RHS);
10438     }
10439   }
10440   assert(PExp->getType()->isAnyPointerType());
10441 
10442   if (!IExp->getType()->isIntegerType())
10443     return InvalidOperands(Loc, LHS, RHS);
10444 
10445   // Adding to a null pointer results in undefined behavior.
10446   if (PExp->IgnoreParenCasts()->isNullPointerConstant(
10447           Context, Expr::NPC_ValueDependentIsNotNull)) {
10448     // In C++ adding zero to a null pointer is defined.
10449     Expr::EvalResult KnownVal;
10450     if (!getLangOpts().CPlusPlus ||
10451         (!IExp->isValueDependent() &&
10452          (!IExp->EvaluateAsInt(KnownVal, Context) ||
10453           KnownVal.Val.getInt() != 0))) {
10454       // Check the conditions to see if this is the 'p = nullptr + n' idiom.
10455       bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension(
10456           Context, BO_Add, PExp, IExp);
10457       diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
10458     }
10459   }
10460 
10461   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
10462     return QualType();
10463 
10464   if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
10465     return QualType();
10466 
10467   // Check array bounds for pointer arithemtic
10468   CheckArrayAccess(PExp, IExp);
10469 
10470   if (CompLHSTy) {
10471     QualType LHSTy = Context.isPromotableBitField(LHS.get());
10472     if (LHSTy.isNull()) {
10473       LHSTy = LHS.get()->getType();
10474       if (LHSTy->isPromotableIntegerType())
10475         LHSTy = Context.getPromotedIntegerType(LHSTy);
10476     }
10477     *CompLHSTy = LHSTy;
10478   }
10479 
10480   return PExp->getType();
10481 }
10482 
10483 // C99 6.5.6
10484 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
10485                                         SourceLocation Loc,
10486                                         QualType* CompLHSTy) {
10487   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10488 
10489   if (LHS.get()->getType()->isVectorType() ||
10490       RHS.get()->getType()->isVectorType()) {
10491     QualType compType = CheckVectorOperands(
10492         LHS, RHS, Loc, CompLHSTy,
10493         /*AllowBothBool*/getLangOpts().AltiVec,
10494         /*AllowBoolConversions*/getLangOpts().ZVector);
10495     if (CompLHSTy) *CompLHSTy = compType;
10496     return compType;
10497   }
10498 
10499   if (LHS.get()->getType()->isConstantMatrixType() ||
10500       RHS.get()->getType()->isConstantMatrixType()) {
10501     return CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
10502   }
10503 
10504   QualType compType = UsualArithmeticConversions(
10505       LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
10506   if (LHS.isInvalid() || RHS.isInvalid())
10507     return QualType();
10508 
10509   // Enforce type constraints: C99 6.5.6p3.
10510 
10511   // Handle the common case first (both operands are arithmetic).
10512   if (!compType.isNull() && compType->isArithmeticType()) {
10513     if (CompLHSTy) *CompLHSTy = compType;
10514     return compType;
10515   }
10516 
10517   // Either ptr - int   or   ptr - ptr.
10518   if (LHS.get()->getType()->isAnyPointerType()) {
10519     QualType lpointee = LHS.get()->getType()->getPointeeType();
10520 
10521     // Diagnose bad cases where we step over interface counts.
10522     if (LHS.get()->getType()->isObjCObjectPointerType() &&
10523         checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
10524       return QualType();
10525 
10526     // The result type of a pointer-int computation is the pointer type.
10527     if (RHS.get()->getType()->isIntegerType()) {
10528       // Subtracting from a null pointer should produce a warning.
10529       // The last argument to the diagnose call says this doesn't match the
10530       // GNU int-to-pointer idiom.
10531       if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context,
10532                                            Expr::NPC_ValueDependentIsNotNull)) {
10533         // In C++ adding zero to a null pointer is defined.
10534         Expr::EvalResult KnownVal;
10535         if (!getLangOpts().CPlusPlus ||
10536             (!RHS.get()->isValueDependent() &&
10537              (!RHS.get()->EvaluateAsInt(KnownVal, Context) ||
10538               KnownVal.Val.getInt() != 0))) {
10539           diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
10540         }
10541       }
10542 
10543       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
10544         return QualType();
10545 
10546       // Check array bounds for pointer arithemtic
10547       CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
10548                        /*AllowOnePastEnd*/true, /*IndexNegated*/true);
10549 
10550       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
10551       return LHS.get()->getType();
10552     }
10553 
10554     // Handle pointer-pointer subtractions.
10555     if (const PointerType *RHSPTy
10556           = RHS.get()->getType()->getAs<PointerType>()) {
10557       QualType rpointee = RHSPTy->getPointeeType();
10558 
10559       if (getLangOpts().CPlusPlus) {
10560         // Pointee types must be the same: C++ [expr.add]
10561         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
10562           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
10563         }
10564       } else {
10565         // Pointee types must be compatible C99 6.5.6p3
10566         if (!Context.typesAreCompatible(
10567                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
10568                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
10569           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
10570           return QualType();
10571         }
10572       }
10573 
10574       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
10575                                                LHS.get(), RHS.get()))
10576         return QualType();
10577 
10578       // FIXME: Add warnings for nullptr - ptr.
10579 
10580       // The pointee type may have zero size.  As an extension, a structure or
10581       // union may have zero size or an array may have zero length.  In this
10582       // case subtraction does not make sense.
10583       if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
10584         CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
10585         if (ElementSize.isZero()) {
10586           Diag(Loc,diag::warn_sub_ptr_zero_size_types)
10587             << rpointee.getUnqualifiedType()
10588             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10589         }
10590       }
10591 
10592       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
10593       return Context.getPointerDiffType();
10594     }
10595   }
10596 
10597   return InvalidOperands(Loc, LHS, RHS);
10598 }
10599 
10600 static bool isScopedEnumerationType(QualType T) {
10601   if (const EnumType *ET = T->getAs<EnumType>())
10602     return ET->getDecl()->isScoped();
10603   return false;
10604 }
10605 
10606 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
10607                                    SourceLocation Loc, BinaryOperatorKind Opc,
10608                                    QualType LHSType) {
10609   // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
10610   // so skip remaining warnings as we don't want to modify values within Sema.
10611   if (S.getLangOpts().OpenCL)
10612     return;
10613 
10614   // Check right/shifter operand
10615   Expr::EvalResult RHSResult;
10616   if (RHS.get()->isValueDependent() ||
10617       !RHS.get()->EvaluateAsInt(RHSResult, S.Context))
10618     return;
10619   llvm::APSInt Right = RHSResult.Val.getInt();
10620 
10621   if (Right.isNegative()) {
10622     S.DiagRuntimeBehavior(Loc, RHS.get(),
10623                           S.PDiag(diag::warn_shift_negative)
10624                             << RHS.get()->getSourceRange());
10625     return;
10626   }
10627 
10628   QualType LHSExprType = LHS.get()->getType();
10629   uint64_t LeftSize = S.Context.getTypeSize(LHSExprType);
10630   if (LHSExprType->isExtIntType())
10631     LeftSize = S.Context.getIntWidth(LHSExprType);
10632   else if (LHSExprType->isFixedPointType()) {
10633     auto FXSema = S.Context.getFixedPointSemantics(LHSExprType);
10634     LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding();
10635   }
10636   llvm::APInt LeftBits(Right.getBitWidth(), LeftSize);
10637   if (Right.uge(LeftBits)) {
10638     S.DiagRuntimeBehavior(Loc, RHS.get(),
10639                           S.PDiag(diag::warn_shift_gt_typewidth)
10640                             << RHS.get()->getSourceRange());
10641     return;
10642   }
10643 
10644   // FIXME: We probably need to handle fixed point types specially here.
10645   if (Opc != BO_Shl || LHSExprType->isFixedPointType())
10646     return;
10647 
10648   // When left shifting an ICE which is signed, we can check for overflow which
10649   // according to C++ standards prior to C++2a has undefined behavior
10650   // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one
10651   // more than the maximum value representable in the result type, so never
10652   // warn for those. (FIXME: Unsigned left-shift overflow in a constant
10653   // expression is still probably a bug.)
10654   Expr::EvalResult LHSResult;
10655   if (LHS.get()->isValueDependent() ||
10656       LHSType->hasUnsignedIntegerRepresentation() ||
10657       !LHS.get()->EvaluateAsInt(LHSResult, S.Context))
10658     return;
10659   llvm::APSInt Left = LHSResult.Val.getInt();
10660 
10661   // If LHS does not have a signed type and non-negative value
10662   // then, the behavior is undefined before C++2a. Warn about it.
10663   if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined() &&
10664       !S.getLangOpts().CPlusPlus20) {
10665     S.DiagRuntimeBehavior(Loc, LHS.get(),
10666                           S.PDiag(diag::warn_shift_lhs_negative)
10667                             << LHS.get()->getSourceRange());
10668     return;
10669   }
10670 
10671   llvm::APInt ResultBits =
10672       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
10673   if (LeftBits.uge(ResultBits))
10674     return;
10675   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
10676   Result = Result.shl(Right);
10677 
10678   // Print the bit representation of the signed integer as an unsigned
10679   // hexadecimal number.
10680   SmallString<40> HexResult;
10681   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
10682 
10683   // If we are only missing a sign bit, this is less likely to result in actual
10684   // bugs -- if the result is cast back to an unsigned type, it will have the
10685   // expected value. Thus we place this behind a different warning that can be
10686   // turned off separately if needed.
10687   if (LeftBits == ResultBits - 1) {
10688     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
10689         << HexResult << LHSType
10690         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10691     return;
10692   }
10693 
10694   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
10695     << HexResult.str() << Result.getMinSignedBits() << LHSType
10696     << Left.getBitWidth() << LHS.get()->getSourceRange()
10697     << RHS.get()->getSourceRange();
10698 }
10699 
10700 /// Return the resulting type when a vector is shifted
10701 ///        by a scalar or vector shift amount.
10702 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
10703                                  SourceLocation Loc, bool IsCompAssign) {
10704   // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
10705   if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
10706       !LHS.get()->getType()->isVectorType()) {
10707     S.Diag(Loc, diag::err_shift_rhs_only_vector)
10708       << RHS.get()->getType() << LHS.get()->getType()
10709       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10710     return QualType();
10711   }
10712 
10713   if (!IsCompAssign) {
10714     LHS = S.UsualUnaryConversions(LHS.get());
10715     if (LHS.isInvalid()) return QualType();
10716   }
10717 
10718   RHS = S.UsualUnaryConversions(RHS.get());
10719   if (RHS.isInvalid()) return QualType();
10720 
10721   QualType LHSType = LHS.get()->getType();
10722   // Note that LHS might be a scalar because the routine calls not only in
10723   // OpenCL case.
10724   const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
10725   QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
10726 
10727   // Note that RHS might not be a vector.
10728   QualType RHSType = RHS.get()->getType();
10729   const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
10730   QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
10731 
10732   // The operands need to be integers.
10733   if (!LHSEleType->isIntegerType()) {
10734     S.Diag(Loc, diag::err_typecheck_expect_int)
10735       << LHS.get()->getType() << LHS.get()->getSourceRange();
10736     return QualType();
10737   }
10738 
10739   if (!RHSEleType->isIntegerType()) {
10740     S.Diag(Loc, diag::err_typecheck_expect_int)
10741       << RHS.get()->getType() << RHS.get()->getSourceRange();
10742     return QualType();
10743   }
10744 
10745   if (!LHSVecTy) {
10746     assert(RHSVecTy);
10747     if (IsCompAssign)
10748       return RHSType;
10749     if (LHSEleType != RHSEleType) {
10750       LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
10751       LHSEleType = RHSEleType;
10752     }
10753     QualType VecTy =
10754         S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
10755     LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
10756     LHSType = VecTy;
10757   } else if (RHSVecTy) {
10758     // OpenCL v1.1 s6.3.j says that for vector types, the operators
10759     // are applied component-wise. So if RHS is a vector, then ensure
10760     // that the number of elements is the same as LHS...
10761     if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
10762       S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
10763         << LHS.get()->getType() << RHS.get()->getType()
10764         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10765       return QualType();
10766     }
10767     if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
10768       const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
10769       const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
10770       if (LHSBT != RHSBT &&
10771           S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
10772         S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
10773             << LHS.get()->getType() << RHS.get()->getType()
10774             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10775       }
10776     }
10777   } else {
10778     // ...else expand RHS to match the number of elements in LHS.
10779     QualType VecTy =
10780       S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
10781     RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
10782   }
10783 
10784   return LHSType;
10785 }
10786 
10787 // C99 6.5.7
10788 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
10789                                   SourceLocation Loc, BinaryOperatorKind Opc,
10790                                   bool IsCompAssign) {
10791   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10792 
10793   // Vector shifts promote their scalar inputs to vector type.
10794   if (LHS.get()->getType()->isVectorType() ||
10795       RHS.get()->getType()->isVectorType()) {
10796     if (LangOpts.ZVector) {
10797       // The shift operators for the z vector extensions work basically
10798       // like general shifts, except that neither the LHS nor the RHS is
10799       // allowed to be a "vector bool".
10800       if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
10801         if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
10802           return InvalidOperands(Loc, LHS, RHS);
10803       if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
10804         if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
10805           return InvalidOperands(Loc, LHS, RHS);
10806     }
10807     return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
10808   }
10809 
10810   // Shifts don't perform usual arithmetic conversions, they just do integer
10811   // promotions on each operand. C99 6.5.7p3
10812 
10813   // For the LHS, do usual unary conversions, but then reset them away
10814   // if this is a compound assignment.
10815   ExprResult OldLHS = LHS;
10816   LHS = UsualUnaryConversions(LHS.get());
10817   if (LHS.isInvalid())
10818     return QualType();
10819   QualType LHSType = LHS.get()->getType();
10820   if (IsCompAssign) LHS = OldLHS;
10821 
10822   // The RHS is simpler.
10823   RHS = UsualUnaryConversions(RHS.get());
10824   if (RHS.isInvalid())
10825     return QualType();
10826   QualType RHSType = RHS.get()->getType();
10827 
10828   // C99 6.5.7p2: Each of the operands shall have integer type.
10829   // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point.
10830   if ((!LHSType->isFixedPointOrIntegerType() &&
10831        !LHSType->hasIntegerRepresentation()) ||
10832       !RHSType->hasIntegerRepresentation())
10833     return InvalidOperands(Loc, LHS, RHS);
10834 
10835   // C++0x: Don't allow scoped enums. FIXME: Use something better than
10836   // hasIntegerRepresentation() above instead of this.
10837   if (isScopedEnumerationType(LHSType) ||
10838       isScopedEnumerationType(RHSType)) {
10839     return InvalidOperands(Loc, LHS, RHS);
10840   }
10841   // Sanity-check shift operands
10842   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
10843 
10844   // "The type of the result is that of the promoted left operand."
10845   return LHSType;
10846 }
10847 
10848 /// Diagnose bad pointer comparisons.
10849 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
10850                                               ExprResult &LHS, ExprResult &RHS,
10851                                               bool IsError) {
10852   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
10853                       : diag::ext_typecheck_comparison_of_distinct_pointers)
10854     << LHS.get()->getType() << RHS.get()->getType()
10855     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10856 }
10857 
10858 /// Returns false if the pointers are converted to a composite type,
10859 /// true otherwise.
10860 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
10861                                            ExprResult &LHS, ExprResult &RHS) {
10862   // C++ [expr.rel]p2:
10863   //   [...] Pointer conversions (4.10) and qualification
10864   //   conversions (4.4) are performed on pointer operands (or on
10865   //   a pointer operand and a null pointer constant) to bring
10866   //   them to their composite pointer type. [...]
10867   //
10868   // C++ [expr.eq]p1 uses the same notion for (in)equality
10869   // comparisons of pointers.
10870 
10871   QualType LHSType = LHS.get()->getType();
10872   QualType RHSType = RHS.get()->getType();
10873   assert(LHSType->isPointerType() || RHSType->isPointerType() ||
10874          LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
10875 
10876   QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
10877   if (T.isNull()) {
10878     if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) &&
10879         (RHSType->isAnyPointerType() || RHSType->isMemberPointerType()))
10880       diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
10881     else
10882       S.InvalidOperands(Loc, LHS, RHS);
10883     return true;
10884   }
10885 
10886   return false;
10887 }
10888 
10889 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
10890                                                     ExprResult &LHS,
10891                                                     ExprResult &RHS,
10892                                                     bool IsError) {
10893   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
10894                       : diag::ext_typecheck_comparison_of_fptr_to_void)
10895     << LHS.get()->getType() << RHS.get()->getType()
10896     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10897 }
10898 
10899 static bool isObjCObjectLiteral(ExprResult &E) {
10900   switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
10901   case Stmt::ObjCArrayLiteralClass:
10902   case Stmt::ObjCDictionaryLiteralClass:
10903   case Stmt::ObjCStringLiteralClass:
10904   case Stmt::ObjCBoxedExprClass:
10905     return true;
10906   default:
10907     // Note that ObjCBoolLiteral is NOT an object literal!
10908     return false;
10909   }
10910 }
10911 
10912 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
10913   const ObjCObjectPointerType *Type =
10914     LHS->getType()->getAs<ObjCObjectPointerType>();
10915 
10916   // If this is not actually an Objective-C object, bail out.
10917   if (!Type)
10918     return false;
10919 
10920   // Get the LHS object's interface type.
10921   QualType InterfaceType = Type->getPointeeType();
10922 
10923   // If the RHS isn't an Objective-C object, bail out.
10924   if (!RHS->getType()->isObjCObjectPointerType())
10925     return false;
10926 
10927   // Try to find the -isEqual: method.
10928   Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
10929   ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
10930                                                       InterfaceType,
10931                                                       /*IsInstance=*/true);
10932   if (!Method) {
10933     if (Type->isObjCIdType()) {
10934       // For 'id', just check the global pool.
10935       Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
10936                                                   /*receiverId=*/true);
10937     } else {
10938       // Check protocols.
10939       Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
10940                                              /*IsInstance=*/true);
10941     }
10942   }
10943 
10944   if (!Method)
10945     return false;
10946 
10947   QualType T = Method->parameters()[0]->getType();
10948   if (!T->isObjCObjectPointerType())
10949     return false;
10950 
10951   QualType R = Method->getReturnType();
10952   if (!R->isScalarType())
10953     return false;
10954 
10955   return true;
10956 }
10957 
10958 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
10959   FromE = FromE->IgnoreParenImpCasts();
10960   switch (FromE->getStmtClass()) {
10961     default:
10962       break;
10963     case Stmt::ObjCStringLiteralClass:
10964       // "string literal"
10965       return LK_String;
10966     case Stmt::ObjCArrayLiteralClass:
10967       // "array literal"
10968       return LK_Array;
10969     case Stmt::ObjCDictionaryLiteralClass:
10970       // "dictionary literal"
10971       return LK_Dictionary;
10972     case Stmt::BlockExprClass:
10973       return LK_Block;
10974     case Stmt::ObjCBoxedExprClass: {
10975       Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
10976       switch (Inner->getStmtClass()) {
10977         case Stmt::IntegerLiteralClass:
10978         case Stmt::FloatingLiteralClass:
10979         case Stmt::CharacterLiteralClass:
10980         case Stmt::ObjCBoolLiteralExprClass:
10981         case Stmt::CXXBoolLiteralExprClass:
10982           // "numeric literal"
10983           return LK_Numeric;
10984         case Stmt::ImplicitCastExprClass: {
10985           CastKind CK = cast<CastExpr>(Inner)->getCastKind();
10986           // Boolean literals can be represented by implicit casts.
10987           if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
10988             return LK_Numeric;
10989           break;
10990         }
10991         default:
10992           break;
10993       }
10994       return LK_Boxed;
10995     }
10996   }
10997   return LK_None;
10998 }
10999 
11000 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
11001                                           ExprResult &LHS, ExprResult &RHS,
11002                                           BinaryOperator::Opcode Opc){
11003   Expr *Literal;
11004   Expr *Other;
11005   if (isObjCObjectLiteral(LHS)) {
11006     Literal = LHS.get();
11007     Other = RHS.get();
11008   } else {
11009     Literal = RHS.get();
11010     Other = LHS.get();
11011   }
11012 
11013   // Don't warn on comparisons against nil.
11014   Other = Other->IgnoreParenCasts();
11015   if (Other->isNullPointerConstant(S.getASTContext(),
11016                                    Expr::NPC_ValueDependentIsNotNull))
11017     return;
11018 
11019   // This should be kept in sync with warn_objc_literal_comparison.
11020   // LK_String should always be after the other literals, since it has its own
11021   // warning flag.
11022   Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
11023   assert(LiteralKind != Sema::LK_Block);
11024   if (LiteralKind == Sema::LK_None) {
11025     llvm_unreachable("Unknown Objective-C object literal kind");
11026   }
11027 
11028   if (LiteralKind == Sema::LK_String)
11029     S.Diag(Loc, diag::warn_objc_string_literal_comparison)
11030       << Literal->getSourceRange();
11031   else
11032     S.Diag(Loc, diag::warn_objc_literal_comparison)
11033       << LiteralKind << Literal->getSourceRange();
11034 
11035   if (BinaryOperator::isEqualityOp(Opc) &&
11036       hasIsEqualMethod(S, LHS.get(), RHS.get())) {
11037     SourceLocation Start = LHS.get()->getBeginLoc();
11038     SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc());
11039     CharSourceRange OpRange =
11040       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
11041 
11042     S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
11043       << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
11044       << FixItHint::CreateReplacement(OpRange, " isEqual:")
11045       << FixItHint::CreateInsertion(End, "]");
11046   }
11047 }
11048 
11049 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
11050 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
11051                                            ExprResult &RHS, SourceLocation Loc,
11052                                            BinaryOperatorKind Opc) {
11053   // Check that left hand side is !something.
11054   UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
11055   if (!UO || UO->getOpcode() != UO_LNot) return;
11056 
11057   // Only check if the right hand side is non-bool arithmetic type.
11058   if (RHS.get()->isKnownToHaveBooleanValue()) return;
11059 
11060   // Make sure that the something in !something is not bool.
11061   Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
11062   if (SubExpr->isKnownToHaveBooleanValue()) return;
11063 
11064   // Emit warning.
11065   bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
11066   S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
11067       << Loc << IsBitwiseOp;
11068 
11069   // First note suggest !(x < y)
11070   SourceLocation FirstOpen = SubExpr->getBeginLoc();
11071   SourceLocation FirstClose = RHS.get()->getEndLoc();
11072   FirstClose = S.getLocForEndOfToken(FirstClose);
11073   if (FirstClose.isInvalid())
11074     FirstOpen = SourceLocation();
11075   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
11076       << IsBitwiseOp
11077       << FixItHint::CreateInsertion(FirstOpen, "(")
11078       << FixItHint::CreateInsertion(FirstClose, ")");
11079 
11080   // Second note suggests (!x) < y
11081   SourceLocation SecondOpen = LHS.get()->getBeginLoc();
11082   SourceLocation SecondClose = LHS.get()->getEndLoc();
11083   SecondClose = S.getLocForEndOfToken(SecondClose);
11084   if (SecondClose.isInvalid())
11085     SecondOpen = SourceLocation();
11086   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
11087       << FixItHint::CreateInsertion(SecondOpen, "(")
11088       << FixItHint::CreateInsertion(SecondClose, ")");
11089 }
11090 
11091 // Returns true if E refers to a non-weak array.
11092 static bool checkForArray(const Expr *E) {
11093   const ValueDecl *D = nullptr;
11094   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
11095     D = DR->getDecl();
11096   } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
11097     if (Mem->isImplicitAccess())
11098       D = Mem->getMemberDecl();
11099   }
11100   if (!D)
11101     return false;
11102   return D->getType()->isArrayType() && !D->isWeak();
11103 }
11104 
11105 /// Diagnose some forms of syntactically-obvious tautological comparison.
11106 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc,
11107                                            Expr *LHS, Expr *RHS,
11108                                            BinaryOperatorKind Opc) {
11109   Expr *LHSStripped = LHS->IgnoreParenImpCasts();
11110   Expr *RHSStripped = RHS->IgnoreParenImpCasts();
11111 
11112   QualType LHSType = LHS->getType();
11113   QualType RHSType = RHS->getType();
11114   if (LHSType->hasFloatingRepresentation() ||
11115       (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
11116       S.inTemplateInstantiation())
11117     return;
11118 
11119   // Comparisons between two array types are ill-formed for operator<=>, so
11120   // we shouldn't emit any additional warnings about it.
11121   if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
11122     return;
11123 
11124   // For non-floating point types, check for self-comparisons of the form
11125   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
11126   // often indicate logic errors in the program.
11127   //
11128   // NOTE: Don't warn about comparison expressions resulting from macro
11129   // expansion. Also don't warn about comparisons which are only self
11130   // comparisons within a template instantiation. The warnings should catch
11131   // obvious cases in the definition of the template anyways. The idea is to
11132   // warn when the typed comparison operator will always evaluate to the same
11133   // result.
11134 
11135   // Used for indexing into %select in warn_comparison_always
11136   enum {
11137     AlwaysConstant,
11138     AlwaysTrue,
11139     AlwaysFalse,
11140     AlwaysEqual, // std::strong_ordering::equal from operator<=>
11141   };
11142 
11143   // C++2a [depr.array.comp]:
11144   //   Equality and relational comparisons ([expr.eq], [expr.rel]) between two
11145   //   operands of array type are deprecated.
11146   if (S.getLangOpts().CPlusPlus20 && LHSStripped->getType()->isArrayType() &&
11147       RHSStripped->getType()->isArrayType()) {
11148     S.Diag(Loc, diag::warn_depr_array_comparison)
11149         << LHS->getSourceRange() << RHS->getSourceRange()
11150         << LHSStripped->getType() << RHSStripped->getType();
11151     // Carry on to produce the tautological comparison warning, if this
11152     // expression is potentially-evaluated, we can resolve the array to a
11153     // non-weak declaration, and so on.
11154   }
11155 
11156   if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) {
11157     if (Expr::isSameComparisonOperand(LHS, RHS)) {
11158       unsigned Result;
11159       switch (Opc) {
11160       case BO_EQ:
11161       case BO_LE:
11162       case BO_GE:
11163         Result = AlwaysTrue;
11164         break;
11165       case BO_NE:
11166       case BO_LT:
11167       case BO_GT:
11168         Result = AlwaysFalse;
11169         break;
11170       case BO_Cmp:
11171         Result = AlwaysEqual;
11172         break;
11173       default:
11174         Result = AlwaysConstant;
11175         break;
11176       }
11177       S.DiagRuntimeBehavior(Loc, nullptr,
11178                             S.PDiag(diag::warn_comparison_always)
11179                                 << 0 /*self-comparison*/
11180                                 << Result);
11181     } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) {
11182       // What is it always going to evaluate to?
11183       unsigned Result;
11184       switch (Opc) {
11185       case BO_EQ: // e.g. array1 == array2
11186         Result = AlwaysFalse;
11187         break;
11188       case BO_NE: // e.g. array1 != array2
11189         Result = AlwaysTrue;
11190         break;
11191       default: // e.g. array1 <= array2
11192         // The best we can say is 'a constant'
11193         Result = AlwaysConstant;
11194         break;
11195       }
11196       S.DiagRuntimeBehavior(Loc, nullptr,
11197                             S.PDiag(diag::warn_comparison_always)
11198                                 << 1 /*array comparison*/
11199                                 << Result);
11200     }
11201   }
11202 
11203   if (isa<CastExpr>(LHSStripped))
11204     LHSStripped = LHSStripped->IgnoreParenCasts();
11205   if (isa<CastExpr>(RHSStripped))
11206     RHSStripped = RHSStripped->IgnoreParenCasts();
11207 
11208   // Warn about comparisons against a string constant (unless the other
11209   // operand is null); the user probably wants string comparison function.
11210   Expr *LiteralString = nullptr;
11211   Expr *LiteralStringStripped = nullptr;
11212   if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
11213       !RHSStripped->isNullPointerConstant(S.Context,
11214                                           Expr::NPC_ValueDependentIsNull)) {
11215     LiteralString = LHS;
11216     LiteralStringStripped = LHSStripped;
11217   } else if ((isa<StringLiteral>(RHSStripped) ||
11218               isa<ObjCEncodeExpr>(RHSStripped)) &&
11219              !LHSStripped->isNullPointerConstant(S.Context,
11220                                           Expr::NPC_ValueDependentIsNull)) {
11221     LiteralString = RHS;
11222     LiteralStringStripped = RHSStripped;
11223   }
11224 
11225   if (LiteralString) {
11226     S.DiagRuntimeBehavior(Loc, nullptr,
11227                           S.PDiag(diag::warn_stringcompare)
11228                               << isa<ObjCEncodeExpr>(LiteralStringStripped)
11229                               << LiteralString->getSourceRange());
11230   }
11231 }
11232 
11233 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) {
11234   switch (CK) {
11235   default: {
11236 #ifndef NDEBUG
11237     llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
11238                  << "\n";
11239 #endif
11240     llvm_unreachable("unhandled cast kind");
11241   }
11242   case CK_UserDefinedConversion:
11243     return ICK_Identity;
11244   case CK_LValueToRValue:
11245     return ICK_Lvalue_To_Rvalue;
11246   case CK_ArrayToPointerDecay:
11247     return ICK_Array_To_Pointer;
11248   case CK_FunctionToPointerDecay:
11249     return ICK_Function_To_Pointer;
11250   case CK_IntegralCast:
11251     return ICK_Integral_Conversion;
11252   case CK_FloatingCast:
11253     return ICK_Floating_Conversion;
11254   case CK_IntegralToFloating:
11255   case CK_FloatingToIntegral:
11256     return ICK_Floating_Integral;
11257   case CK_IntegralComplexCast:
11258   case CK_FloatingComplexCast:
11259   case CK_FloatingComplexToIntegralComplex:
11260   case CK_IntegralComplexToFloatingComplex:
11261     return ICK_Complex_Conversion;
11262   case CK_FloatingComplexToReal:
11263   case CK_FloatingRealToComplex:
11264   case CK_IntegralComplexToReal:
11265   case CK_IntegralRealToComplex:
11266     return ICK_Complex_Real;
11267   }
11268 }
11269 
11270 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E,
11271                                              QualType FromType,
11272                                              SourceLocation Loc) {
11273   // Check for a narrowing implicit conversion.
11274   StandardConversionSequence SCS;
11275   SCS.setAsIdentityConversion();
11276   SCS.setToType(0, FromType);
11277   SCS.setToType(1, ToType);
11278   if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
11279     SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
11280 
11281   APValue PreNarrowingValue;
11282   QualType PreNarrowingType;
11283   switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
11284                                PreNarrowingType,
11285                                /*IgnoreFloatToIntegralConversion*/ true)) {
11286   case NK_Dependent_Narrowing:
11287     // Implicit conversion to a narrower type, but the expression is
11288     // value-dependent so we can't tell whether it's actually narrowing.
11289   case NK_Not_Narrowing:
11290     return false;
11291 
11292   case NK_Constant_Narrowing:
11293     // Implicit conversion to a narrower type, and the value is not a constant
11294     // expression.
11295     S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
11296         << /*Constant*/ 1
11297         << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
11298     return true;
11299 
11300   case NK_Variable_Narrowing:
11301     // Implicit conversion to a narrower type, and the value is not a constant
11302     // expression.
11303   case NK_Type_Narrowing:
11304     S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
11305         << /*Constant*/ 0 << FromType << ToType;
11306     // TODO: It's not a constant expression, but what if the user intended it
11307     // to be? Can we produce notes to help them figure out why it isn't?
11308     return true;
11309   }
11310   llvm_unreachable("unhandled case in switch");
11311 }
11312 
11313 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S,
11314                                                          ExprResult &LHS,
11315                                                          ExprResult &RHS,
11316                                                          SourceLocation Loc) {
11317   QualType LHSType = LHS.get()->getType();
11318   QualType RHSType = RHS.get()->getType();
11319   // Dig out the original argument type and expression before implicit casts
11320   // were applied. These are the types/expressions we need to check the
11321   // [expr.spaceship] requirements against.
11322   ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
11323   ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
11324   QualType LHSStrippedType = LHSStripped.get()->getType();
11325   QualType RHSStrippedType = RHSStripped.get()->getType();
11326 
11327   // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
11328   // other is not, the program is ill-formed.
11329   if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
11330     S.InvalidOperands(Loc, LHSStripped, RHSStripped);
11331     return QualType();
11332   }
11333 
11334   // FIXME: Consider combining this with checkEnumArithmeticConversions.
11335   int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
11336                     RHSStrippedType->isEnumeralType();
11337   if (NumEnumArgs == 1) {
11338     bool LHSIsEnum = LHSStrippedType->isEnumeralType();
11339     QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
11340     if (OtherTy->hasFloatingRepresentation()) {
11341       S.InvalidOperands(Loc, LHSStripped, RHSStripped);
11342       return QualType();
11343     }
11344   }
11345   if (NumEnumArgs == 2) {
11346     // C++2a [expr.spaceship]p5: If both operands have the same enumeration
11347     // type E, the operator yields the result of converting the operands
11348     // to the underlying type of E and applying <=> to the converted operands.
11349     if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
11350       S.InvalidOperands(Loc, LHS, RHS);
11351       return QualType();
11352     }
11353     QualType IntType =
11354         LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType();
11355     assert(IntType->isArithmeticType());
11356 
11357     // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
11358     // promote the boolean type, and all other promotable integer types, to
11359     // avoid this.
11360     if (IntType->isPromotableIntegerType())
11361       IntType = S.Context.getPromotedIntegerType(IntType);
11362 
11363     LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
11364     RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
11365     LHSType = RHSType = IntType;
11366   }
11367 
11368   // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
11369   // usual arithmetic conversions are applied to the operands.
11370   QualType Type =
11371       S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison);
11372   if (LHS.isInvalid() || RHS.isInvalid())
11373     return QualType();
11374   if (Type.isNull())
11375     return S.InvalidOperands(Loc, LHS, RHS);
11376 
11377   Optional<ComparisonCategoryType> CCT =
11378       getComparisonCategoryForBuiltinCmp(Type);
11379   if (!CCT)
11380     return S.InvalidOperands(Loc, LHS, RHS);
11381 
11382   bool HasNarrowing = checkThreeWayNarrowingConversion(
11383       S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc());
11384   HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType,
11385                                                    RHS.get()->getBeginLoc());
11386   if (HasNarrowing)
11387     return QualType();
11388 
11389   assert(!Type.isNull() && "composite type for <=> has not been set");
11390 
11391   return S.CheckComparisonCategoryType(
11392       *CCT, Loc, Sema::ComparisonCategoryUsage::OperatorInExpression);
11393 }
11394 
11395 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS,
11396                                                  ExprResult &RHS,
11397                                                  SourceLocation Loc,
11398                                                  BinaryOperatorKind Opc) {
11399   if (Opc == BO_Cmp)
11400     return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
11401 
11402   // C99 6.5.8p3 / C99 6.5.9p4
11403   QualType Type =
11404       S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison);
11405   if (LHS.isInvalid() || RHS.isInvalid())
11406     return QualType();
11407   if (Type.isNull())
11408     return S.InvalidOperands(Loc, LHS, RHS);
11409   assert(Type->isArithmeticType() || Type->isEnumeralType());
11410 
11411   if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc))
11412     return S.InvalidOperands(Loc, LHS, RHS);
11413 
11414   // Check for comparisons of floating point operands using != and ==.
11415   if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc))
11416     S.CheckFloatComparison(Loc, LHS.get(), RHS.get());
11417 
11418   // The result of comparisons is 'bool' in C++, 'int' in C.
11419   return S.Context.getLogicalOperationType();
11420 }
11421 
11422 void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) {
11423   if (!NullE.get()->getType()->isAnyPointerType())
11424     return;
11425   int NullValue = PP.isMacroDefined("NULL") ? 0 : 1;
11426   if (!E.get()->getType()->isAnyPointerType() &&
11427       E.get()->isNullPointerConstant(Context,
11428                                      Expr::NPC_ValueDependentIsNotNull) ==
11429         Expr::NPCK_ZeroExpression) {
11430     if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) {
11431       if (CL->getValue() == 0)
11432         Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
11433             << NullValue
11434             << FixItHint::CreateReplacement(E.get()->getExprLoc(),
11435                                             NullValue ? "NULL" : "(void *)0");
11436     } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) {
11437         TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
11438         QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType();
11439         if (T == Context.CharTy)
11440           Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
11441               << NullValue
11442               << FixItHint::CreateReplacement(E.get()->getExprLoc(),
11443                                               NullValue ? "NULL" : "(void *)0");
11444       }
11445   }
11446 }
11447 
11448 // C99 6.5.8, C++ [expr.rel]
11449 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
11450                                     SourceLocation Loc,
11451                                     BinaryOperatorKind Opc) {
11452   bool IsRelational = BinaryOperator::isRelationalOp(Opc);
11453   bool IsThreeWay = Opc == BO_Cmp;
11454   bool IsOrdered = IsRelational || IsThreeWay;
11455   auto IsAnyPointerType = [](ExprResult E) {
11456     QualType Ty = E.get()->getType();
11457     return Ty->isPointerType() || Ty->isMemberPointerType();
11458   };
11459 
11460   // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
11461   // type, array-to-pointer, ..., conversions are performed on both operands to
11462   // bring them to their composite type.
11463   // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
11464   // any type-related checks.
11465   if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
11466     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
11467     if (LHS.isInvalid())
11468       return QualType();
11469     RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
11470     if (RHS.isInvalid())
11471       return QualType();
11472   } else {
11473     LHS = DefaultLvalueConversion(LHS.get());
11474     if (LHS.isInvalid())
11475       return QualType();
11476     RHS = DefaultLvalueConversion(RHS.get());
11477     if (RHS.isInvalid())
11478       return QualType();
11479   }
11480 
11481   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true);
11482   if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) {
11483     CheckPtrComparisonWithNullChar(LHS, RHS);
11484     CheckPtrComparisonWithNullChar(RHS, LHS);
11485   }
11486 
11487   // Handle vector comparisons separately.
11488   if (LHS.get()->getType()->isVectorType() ||
11489       RHS.get()->getType()->isVectorType())
11490     return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
11491 
11492   diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
11493   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
11494 
11495   QualType LHSType = LHS.get()->getType();
11496   QualType RHSType = RHS.get()->getType();
11497   if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
11498       (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
11499     return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
11500 
11501   const Expr::NullPointerConstantKind LHSNullKind =
11502       LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
11503   const Expr::NullPointerConstantKind RHSNullKind =
11504       RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
11505   bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
11506   bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
11507 
11508   auto computeResultTy = [&]() {
11509     if (Opc != BO_Cmp)
11510       return Context.getLogicalOperationType();
11511     assert(getLangOpts().CPlusPlus);
11512     assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
11513 
11514     QualType CompositeTy = LHS.get()->getType();
11515     assert(!CompositeTy->isReferenceType());
11516 
11517     Optional<ComparisonCategoryType> CCT =
11518         getComparisonCategoryForBuiltinCmp(CompositeTy);
11519     if (!CCT)
11520       return InvalidOperands(Loc, LHS, RHS);
11521 
11522     if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) {
11523       // P0946R0: Comparisons between a null pointer constant and an object
11524       // pointer result in std::strong_equality, which is ill-formed under
11525       // P1959R0.
11526       Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero)
11527           << (LHSIsNull ? LHS.get()->getSourceRange()
11528                         : RHS.get()->getSourceRange());
11529       return QualType();
11530     }
11531 
11532     return CheckComparisonCategoryType(
11533         *CCT, Loc, ComparisonCategoryUsage::OperatorInExpression);
11534   };
11535 
11536   if (!IsOrdered && LHSIsNull != RHSIsNull) {
11537     bool IsEquality = Opc == BO_EQ;
11538     if (RHSIsNull)
11539       DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
11540                                    RHS.get()->getSourceRange());
11541     else
11542       DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
11543                                    LHS.get()->getSourceRange());
11544   }
11545 
11546   if ((LHSType->isIntegerType() && !LHSIsNull) ||
11547       (RHSType->isIntegerType() && !RHSIsNull)) {
11548     // Skip normal pointer conversion checks in this case; we have better
11549     // diagnostics for this below.
11550   } else if (getLangOpts().CPlusPlus) {
11551     // Equality comparison of a function pointer to a void pointer is invalid,
11552     // but we allow it as an extension.
11553     // FIXME: If we really want to allow this, should it be part of composite
11554     // pointer type computation so it works in conditionals too?
11555     if (!IsOrdered &&
11556         ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
11557          (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
11558       // This is a gcc extension compatibility comparison.
11559       // In a SFINAE context, we treat this as a hard error to maintain
11560       // conformance with the C++ standard.
11561       diagnoseFunctionPointerToVoidComparison(
11562           *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
11563 
11564       if (isSFINAEContext())
11565         return QualType();
11566 
11567       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
11568       return computeResultTy();
11569     }
11570 
11571     // C++ [expr.eq]p2:
11572     //   If at least one operand is a pointer [...] bring them to their
11573     //   composite pointer type.
11574     // C++ [expr.spaceship]p6
11575     //  If at least one of the operands is of pointer type, [...] bring them
11576     //  to their composite pointer type.
11577     // C++ [expr.rel]p2:
11578     //   If both operands are pointers, [...] bring them to their composite
11579     //   pointer type.
11580     // For <=>, the only valid non-pointer types are arrays and functions, and
11581     // we already decayed those, so this is really the same as the relational
11582     // comparison rule.
11583     if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
11584             (IsOrdered ? 2 : 1) &&
11585         (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
11586                                          RHSType->isObjCObjectPointerType()))) {
11587       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
11588         return QualType();
11589       return computeResultTy();
11590     }
11591   } else if (LHSType->isPointerType() &&
11592              RHSType->isPointerType()) { // C99 6.5.8p2
11593     // All of the following pointer-related warnings are GCC extensions, except
11594     // when handling null pointer constants.
11595     QualType LCanPointeeTy =
11596       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
11597     QualType RCanPointeeTy =
11598       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
11599 
11600     // C99 6.5.9p2 and C99 6.5.8p2
11601     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
11602                                    RCanPointeeTy.getUnqualifiedType())) {
11603       if (IsRelational) {
11604         // Pointers both need to point to complete or incomplete types
11605         if ((LCanPointeeTy->isIncompleteType() !=
11606              RCanPointeeTy->isIncompleteType()) &&
11607             !getLangOpts().C11) {
11608           Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers)
11609               << LHS.get()->getSourceRange() << RHS.get()->getSourceRange()
11610               << LHSType << RHSType << LCanPointeeTy->isIncompleteType()
11611               << RCanPointeeTy->isIncompleteType();
11612         }
11613         if (LCanPointeeTy->isFunctionType()) {
11614           // Valid unless a relational comparison of function pointers
11615           Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
11616               << LHSType << RHSType << LHS.get()->getSourceRange()
11617               << RHS.get()->getSourceRange();
11618         }
11619       }
11620     } else if (!IsRelational &&
11621                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
11622       // Valid unless comparison between non-null pointer and function pointer
11623       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
11624           && !LHSIsNull && !RHSIsNull)
11625         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
11626                                                 /*isError*/false);
11627     } else {
11628       // Invalid
11629       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
11630     }
11631     if (LCanPointeeTy != RCanPointeeTy) {
11632       // Treat NULL constant as a special case in OpenCL.
11633       if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
11634         if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy)) {
11635           Diag(Loc,
11636                diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
11637               << LHSType << RHSType << 0 /* comparison */
11638               << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11639         }
11640       }
11641       LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
11642       LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
11643       CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
11644                                                : CK_BitCast;
11645       if (LHSIsNull && !RHSIsNull)
11646         LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
11647       else
11648         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
11649     }
11650     return computeResultTy();
11651   }
11652 
11653   if (getLangOpts().CPlusPlus) {
11654     // C++ [expr.eq]p4:
11655     //   Two operands of type std::nullptr_t or one operand of type
11656     //   std::nullptr_t and the other a null pointer constant compare equal.
11657     if (!IsOrdered && LHSIsNull && RHSIsNull) {
11658       if (LHSType->isNullPtrType()) {
11659         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11660         return computeResultTy();
11661       }
11662       if (RHSType->isNullPtrType()) {
11663         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11664         return computeResultTy();
11665       }
11666     }
11667 
11668     // Comparison of Objective-C pointers and block pointers against nullptr_t.
11669     // These aren't covered by the composite pointer type rules.
11670     if (!IsOrdered && RHSType->isNullPtrType() &&
11671         (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
11672       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11673       return computeResultTy();
11674     }
11675     if (!IsOrdered && LHSType->isNullPtrType() &&
11676         (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
11677       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11678       return computeResultTy();
11679     }
11680 
11681     if (IsRelational &&
11682         ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
11683          (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
11684       // HACK: Relational comparison of nullptr_t against a pointer type is
11685       // invalid per DR583, but we allow it within std::less<> and friends,
11686       // since otherwise common uses of it break.
11687       // FIXME: Consider removing this hack once LWG fixes std::less<> and
11688       // friends to have std::nullptr_t overload candidates.
11689       DeclContext *DC = CurContext;
11690       if (isa<FunctionDecl>(DC))
11691         DC = DC->getParent();
11692       if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
11693         if (CTSD->isInStdNamespace() &&
11694             llvm::StringSwitch<bool>(CTSD->getName())
11695                 .Cases("less", "less_equal", "greater", "greater_equal", true)
11696                 .Default(false)) {
11697           if (RHSType->isNullPtrType())
11698             RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11699           else
11700             LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11701           return computeResultTy();
11702         }
11703       }
11704     }
11705 
11706     // C++ [expr.eq]p2:
11707     //   If at least one operand is a pointer to member, [...] bring them to
11708     //   their composite pointer type.
11709     if (!IsOrdered &&
11710         (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
11711       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
11712         return QualType();
11713       else
11714         return computeResultTy();
11715     }
11716   }
11717 
11718   // Handle block pointer types.
11719   if (!IsOrdered && LHSType->isBlockPointerType() &&
11720       RHSType->isBlockPointerType()) {
11721     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
11722     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
11723 
11724     if (!LHSIsNull && !RHSIsNull &&
11725         !Context.typesAreCompatible(lpointee, rpointee)) {
11726       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
11727         << LHSType << RHSType << LHS.get()->getSourceRange()
11728         << RHS.get()->getSourceRange();
11729     }
11730     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
11731     return computeResultTy();
11732   }
11733 
11734   // Allow block pointers to be compared with null pointer constants.
11735   if (!IsOrdered
11736       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
11737           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
11738     if (!LHSIsNull && !RHSIsNull) {
11739       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
11740              ->getPointeeType()->isVoidType())
11741             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
11742                 ->getPointeeType()->isVoidType())))
11743         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
11744           << LHSType << RHSType << LHS.get()->getSourceRange()
11745           << RHS.get()->getSourceRange();
11746     }
11747     if (LHSIsNull && !RHSIsNull)
11748       LHS = ImpCastExprToType(LHS.get(), RHSType,
11749                               RHSType->isPointerType() ? CK_BitCast
11750                                 : CK_AnyPointerToBlockPointerCast);
11751     else
11752       RHS = ImpCastExprToType(RHS.get(), LHSType,
11753                               LHSType->isPointerType() ? CK_BitCast
11754                                 : CK_AnyPointerToBlockPointerCast);
11755     return computeResultTy();
11756   }
11757 
11758   if (LHSType->isObjCObjectPointerType() ||
11759       RHSType->isObjCObjectPointerType()) {
11760     const PointerType *LPT = LHSType->getAs<PointerType>();
11761     const PointerType *RPT = RHSType->getAs<PointerType>();
11762     if (LPT || RPT) {
11763       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
11764       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
11765 
11766       if (!LPtrToVoid && !RPtrToVoid &&
11767           !Context.typesAreCompatible(LHSType, RHSType)) {
11768         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
11769                                           /*isError*/false);
11770       }
11771       // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than
11772       // the RHS, but we have test coverage for this behavior.
11773       // FIXME: Consider using convertPointersToCompositeType in C++.
11774       if (LHSIsNull && !RHSIsNull) {
11775         Expr *E = LHS.get();
11776         if (getLangOpts().ObjCAutoRefCount)
11777           CheckObjCConversion(SourceRange(), RHSType, E,
11778                               CCK_ImplicitConversion);
11779         LHS = ImpCastExprToType(E, RHSType,
11780                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
11781       }
11782       else {
11783         Expr *E = RHS.get();
11784         if (getLangOpts().ObjCAutoRefCount)
11785           CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion,
11786                               /*Diagnose=*/true,
11787                               /*DiagnoseCFAudited=*/false, Opc);
11788         RHS = ImpCastExprToType(E, LHSType,
11789                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
11790       }
11791       return computeResultTy();
11792     }
11793     if (LHSType->isObjCObjectPointerType() &&
11794         RHSType->isObjCObjectPointerType()) {
11795       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
11796         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
11797                                           /*isError*/false);
11798       if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
11799         diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
11800 
11801       if (LHSIsNull && !RHSIsNull)
11802         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
11803       else
11804         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
11805       return computeResultTy();
11806     }
11807 
11808     if (!IsOrdered && LHSType->isBlockPointerType() &&
11809         RHSType->isBlockCompatibleObjCPointerType(Context)) {
11810       LHS = ImpCastExprToType(LHS.get(), RHSType,
11811                               CK_BlockPointerToObjCPointerCast);
11812       return computeResultTy();
11813     } else if (!IsOrdered &&
11814                LHSType->isBlockCompatibleObjCPointerType(Context) &&
11815                RHSType->isBlockPointerType()) {
11816       RHS = ImpCastExprToType(RHS.get(), LHSType,
11817                               CK_BlockPointerToObjCPointerCast);
11818       return computeResultTy();
11819     }
11820   }
11821   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
11822       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
11823     unsigned DiagID = 0;
11824     bool isError = false;
11825     if (LangOpts.DebuggerSupport) {
11826       // Under a debugger, allow the comparison of pointers to integers,
11827       // since users tend to want to compare addresses.
11828     } else if ((LHSIsNull && LHSType->isIntegerType()) ||
11829                (RHSIsNull && RHSType->isIntegerType())) {
11830       if (IsOrdered) {
11831         isError = getLangOpts().CPlusPlus;
11832         DiagID =
11833           isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
11834                   : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
11835       }
11836     } else if (getLangOpts().CPlusPlus) {
11837       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
11838       isError = true;
11839     } else if (IsOrdered)
11840       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
11841     else
11842       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
11843 
11844     if (DiagID) {
11845       Diag(Loc, DiagID)
11846         << LHSType << RHSType << LHS.get()->getSourceRange()
11847         << RHS.get()->getSourceRange();
11848       if (isError)
11849         return QualType();
11850     }
11851 
11852     if (LHSType->isIntegerType())
11853       LHS = ImpCastExprToType(LHS.get(), RHSType,
11854                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
11855     else
11856       RHS = ImpCastExprToType(RHS.get(), LHSType,
11857                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
11858     return computeResultTy();
11859   }
11860 
11861   // Handle block pointers.
11862   if (!IsOrdered && RHSIsNull
11863       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
11864     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11865     return computeResultTy();
11866   }
11867   if (!IsOrdered && LHSIsNull
11868       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
11869     LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11870     return computeResultTy();
11871   }
11872 
11873   if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) {
11874     if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
11875       return computeResultTy();
11876     }
11877 
11878     if (LHSType->isQueueT() && RHSType->isQueueT()) {
11879       return computeResultTy();
11880     }
11881 
11882     if (LHSIsNull && RHSType->isQueueT()) {
11883       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11884       return computeResultTy();
11885     }
11886 
11887     if (LHSType->isQueueT() && RHSIsNull) {
11888       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11889       return computeResultTy();
11890     }
11891   }
11892 
11893   return InvalidOperands(Loc, LHS, RHS);
11894 }
11895 
11896 // Return a signed ext_vector_type that is of identical size and number of
11897 // elements. For floating point vectors, return an integer type of identical
11898 // size and number of elements. In the non ext_vector_type case, search from
11899 // the largest type to the smallest type to avoid cases where long long == long,
11900 // where long gets picked over long long.
11901 QualType Sema::GetSignedVectorType(QualType V) {
11902   const VectorType *VTy = V->castAs<VectorType>();
11903   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
11904 
11905   if (isa<ExtVectorType>(VTy)) {
11906     if (TypeSize == Context.getTypeSize(Context.CharTy))
11907       return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
11908     else if (TypeSize == Context.getTypeSize(Context.ShortTy))
11909       return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
11910     else if (TypeSize == Context.getTypeSize(Context.IntTy))
11911       return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
11912     else if (TypeSize == Context.getTypeSize(Context.LongTy))
11913       return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
11914     assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
11915            "Unhandled vector element size in vector compare");
11916     return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
11917   }
11918 
11919   if (TypeSize == Context.getTypeSize(Context.LongLongTy))
11920     return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
11921                                  VectorType::GenericVector);
11922   else if (TypeSize == Context.getTypeSize(Context.LongTy))
11923     return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
11924                                  VectorType::GenericVector);
11925   else if (TypeSize == Context.getTypeSize(Context.IntTy))
11926     return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
11927                                  VectorType::GenericVector);
11928   else if (TypeSize == Context.getTypeSize(Context.ShortTy))
11929     return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
11930                                  VectorType::GenericVector);
11931   assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
11932          "Unhandled vector element size in vector compare");
11933   return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
11934                                VectorType::GenericVector);
11935 }
11936 
11937 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
11938 /// operates on extended vector types.  Instead of producing an IntTy result,
11939 /// like a scalar comparison, a vector comparison produces a vector of integer
11940 /// types.
11941 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
11942                                           SourceLocation Loc,
11943                                           BinaryOperatorKind Opc) {
11944   if (Opc == BO_Cmp) {
11945     Diag(Loc, diag::err_three_way_vector_comparison);
11946     return QualType();
11947   }
11948 
11949   // Check to make sure we're operating on vectors of the same type and width,
11950   // Allowing one side to be a scalar of element type.
11951   QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
11952                               /*AllowBothBool*/true,
11953                               /*AllowBoolConversions*/getLangOpts().ZVector);
11954   if (vType.isNull())
11955     return vType;
11956 
11957   QualType LHSType = LHS.get()->getType();
11958 
11959   // If AltiVec, the comparison results in a numeric type, i.e.
11960   // bool for C++, int for C
11961   if (getLangOpts().AltiVec &&
11962       vType->castAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
11963     return Context.getLogicalOperationType();
11964 
11965   // For non-floating point types, check for self-comparisons of the form
11966   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
11967   // often indicate logic errors in the program.
11968   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
11969 
11970   // Check for comparisons of floating point operands using != and ==.
11971   if (BinaryOperator::isEqualityOp(Opc) &&
11972       LHSType->hasFloatingRepresentation()) {
11973     assert(RHS.get()->getType()->hasFloatingRepresentation());
11974     CheckFloatComparison(Loc, LHS.get(), RHS.get());
11975   }
11976 
11977   // Return a signed type for the vector.
11978   return GetSignedVectorType(vType);
11979 }
11980 
11981 static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS,
11982                                     const ExprResult &XorRHS,
11983                                     const SourceLocation Loc) {
11984   // Do not diagnose macros.
11985   if (Loc.isMacroID())
11986     return;
11987 
11988   bool Negative = false;
11989   bool ExplicitPlus = false;
11990   const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get());
11991   const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get());
11992 
11993   if (!LHSInt)
11994     return;
11995   if (!RHSInt) {
11996     // Check negative literals.
11997     if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) {
11998       UnaryOperatorKind Opc = UO->getOpcode();
11999       if (Opc != UO_Minus && Opc != UO_Plus)
12000         return;
12001       RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr());
12002       if (!RHSInt)
12003         return;
12004       Negative = (Opc == UO_Minus);
12005       ExplicitPlus = !Negative;
12006     } else {
12007       return;
12008     }
12009   }
12010 
12011   const llvm::APInt &LeftSideValue = LHSInt->getValue();
12012   llvm::APInt RightSideValue = RHSInt->getValue();
12013   if (LeftSideValue != 2 && LeftSideValue != 10)
12014     return;
12015 
12016   if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth())
12017     return;
12018 
12019   CharSourceRange ExprRange = CharSourceRange::getCharRange(
12020       LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation()));
12021   llvm::StringRef ExprStr =
12022       Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts());
12023 
12024   CharSourceRange XorRange =
12025       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
12026   llvm::StringRef XorStr =
12027       Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts());
12028   // Do not diagnose if xor keyword/macro is used.
12029   if (XorStr == "xor")
12030     return;
12031 
12032   std::string LHSStr = std::string(Lexer::getSourceText(
12033       CharSourceRange::getTokenRange(LHSInt->getSourceRange()),
12034       S.getSourceManager(), S.getLangOpts()));
12035   std::string RHSStr = std::string(Lexer::getSourceText(
12036       CharSourceRange::getTokenRange(RHSInt->getSourceRange()),
12037       S.getSourceManager(), S.getLangOpts()));
12038 
12039   if (Negative) {
12040     RightSideValue = -RightSideValue;
12041     RHSStr = "-" + RHSStr;
12042   } else if (ExplicitPlus) {
12043     RHSStr = "+" + RHSStr;
12044   }
12045 
12046   StringRef LHSStrRef = LHSStr;
12047   StringRef RHSStrRef = RHSStr;
12048   // Do not diagnose literals with digit separators, binary, hexadecimal, octal
12049   // literals.
12050   if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") ||
12051       RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") ||
12052       LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") ||
12053       RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") ||
12054       (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) ||
12055       (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) ||
12056       LHSStrRef.find('\'') != StringRef::npos ||
12057       RHSStrRef.find('\'') != StringRef::npos)
12058     return;
12059 
12060   bool SuggestXor = S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor");
12061   const llvm::APInt XorValue = LeftSideValue ^ RightSideValue;
12062   int64_t RightSideIntValue = RightSideValue.getSExtValue();
12063   if (LeftSideValue == 2 && RightSideIntValue >= 0) {
12064     std::string SuggestedExpr = "1 << " + RHSStr;
12065     bool Overflow = false;
12066     llvm::APInt One = (LeftSideValue - 1);
12067     llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow);
12068     if (Overflow) {
12069       if (RightSideIntValue < 64)
12070         S.Diag(Loc, diag::warn_xor_used_as_pow_base)
12071             << ExprStr << XorValue.toString(10, true) << ("1LL << " + RHSStr)
12072             << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr);
12073       else if (RightSideIntValue == 64)
12074         S.Diag(Loc, diag::warn_xor_used_as_pow) << ExprStr << XorValue.toString(10, true);
12075       else
12076         return;
12077     } else {
12078       S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra)
12079           << ExprStr << XorValue.toString(10, true) << SuggestedExpr
12080           << PowValue.toString(10, true)
12081           << FixItHint::CreateReplacement(
12082                  ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr);
12083     }
12084 
12085     S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0x2 ^ " + RHSStr) << SuggestXor;
12086   } else if (LeftSideValue == 10) {
12087     std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue);
12088     S.Diag(Loc, diag::warn_xor_used_as_pow_base)
12089         << ExprStr << XorValue.toString(10, true) << SuggestedValue
12090         << FixItHint::CreateReplacement(ExprRange, SuggestedValue);
12091     S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0xA ^ " + RHSStr) << SuggestXor;
12092   }
12093 }
12094 
12095 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
12096                                           SourceLocation Loc) {
12097   // Ensure that either both operands are of the same vector type, or
12098   // one operand is of a vector type and the other is of its element type.
12099   QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
12100                                        /*AllowBothBool*/true,
12101                                        /*AllowBoolConversions*/false);
12102   if (vType.isNull())
12103     return InvalidOperands(Loc, LHS, RHS);
12104   if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
12105       !getLangOpts().OpenCLCPlusPlus && vType->hasFloatingRepresentation())
12106     return InvalidOperands(Loc, LHS, RHS);
12107   // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
12108   //        usage of the logical operators && and || with vectors in C. This
12109   //        check could be notionally dropped.
12110   if (!getLangOpts().CPlusPlus &&
12111       !(isa<ExtVectorType>(vType->getAs<VectorType>())))
12112     return InvalidLogicalVectorOperands(Loc, LHS, RHS);
12113 
12114   return GetSignedVectorType(LHS.get()->getType());
12115 }
12116 
12117 QualType Sema::CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS,
12118                                               SourceLocation Loc,
12119                                               bool IsCompAssign) {
12120   if (!IsCompAssign) {
12121     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
12122     if (LHS.isInvalid())
12123       return QualType();
12124   }
12125   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
12126   if (RHS.isInvalid())
12127     return QualType();
12128 
12129   // For conversion purposes, we ignore any qualifiers.
12130   // For example, "const float" and "float" are equivalent.
12131   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
12132   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
12133 
12134   const MatrixType *LHSMatType = LHSType->getAs<MatrixType>();
12135   const MatrixType *RHSMatType = RHSType->getAs<MatrixType>();
12136   assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
12137 
12138   if (Context.hasSameType(LHSType, RHSType))
12139     return LHSType;
12140 
12141   // Type conversion may change LHS/RHS. Keep copies to the original results, in
12142   // case we have to return InvalidOperands.
12143   ExprResult OriginalLHS = LHS;
12144   ExprResult OriginalRHS = RHS;
12145   if (LHSMatType && !RHSMatType) {
12146     RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType());
12147     if (!RHS.isInvalid())
12148       return LHSType;
12149 
12150     return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
12151   }
12152 
12153   if (!LHSMatType && RHSMatType) {
12154     LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType());
12155     if (!LHS.isInvalid())
12156       return RHSType;
12157     return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
12158   }
12159 
12160   return InvalidOperands(Loc, LHS, RHS);
12161 }
12162 
12163 QualType Sema::CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS,
12164                                            SourceLocation Loc,
12165                                            bool IsCompAssign) {
12166   if (!IsCompAssign) {
12167     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
12168     if (LHS.isInvalid())
12169       return QualType();
12170   }
12171   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
12172   if (RHS.isInvalid())
12173     return QualType();
12174 
12175   auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>();
12176   auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>();
12177   assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
12178 
12179   if (LHSMatType && RHSMatType) {
12180     if (LHSMatType->getNumColumns() != RHSMatType->getNumRows())
12181       return InvalidOperands(Loc, LHS, RHS);
12182 
12183     if (!Context.hasSameType(LHSMatType->getElementType(),
12184                              RHSMatType->getElementType()))
12185       return InvalidOperands(Loc, LHS, RHS);
12186 
12187     return Context.getConstantMatrixType(LHSMatType->getElementType(),
12188                                          LHSMatType->getNumRows(),
12189                                          RHSMatType->getNumColumns());
12190   }
12191   return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
12192 }
12193 
12194 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
12195                                            SourceLocation Loc,
12196                                            BinaryOperatorKind Opc) {
12197   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
12198 
12199   bool IsCompAssign =
12200       Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
12201 
12202   if (LHS.get()->getType()->isVectorType() ||
12203       RHS.get()->getType()->isVectorType()) {
12204     if (LHS.get()->getType()->hasIntegerRepresentation() &&
12205         RHS.get()->getType()->hasIntegerRepresentation())
12206       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
12207                         /*AllowBothBool*/true,
12208                         /*AllowBoolConversions*/getLangOpts().ZVector);
12209     return InvalidOperands(Loc, LHS, RHS);
12210   }
12211 
12212   if (Opc == BO_And)
12213     diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
12214 
12215   if (LHS.get()->getType()->hasFloatingRepresentation() ||
12216       RHS.get()->getType()->hasFloatingRepresentation())
12217     return InvalidOperands(Loc, LHS, RHS);
12218 
12219   ExprResult LHSResult = LHS, RHSResult = RHS;
12220   QualType compType = UsualArithmeticConversions(
12221       LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp);
12222   if (LHSResult.isInvalid() || RHSResult.isInvalid())
12223     return QualType();
12224   LHS = LHSResult.get();
12225   RHS = RHSResult.get();
12226 
12227   if (Opc == BO_Xor)
12228     diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc);
12229 
12230   if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
12231     return compType;
12232   return InvalidOperands(Loc, LHS, RHS);
12233 }
12234 
12235 // C99 6.5.[13,14]
12236 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
12237                                            SourceLocation Loc,
12238                                            BinaryOperatorKind Opc) {
12239   // Check vector operands differently.
12240   if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
12241     return CheckVectorLogicalOperands(LHS, RHS, Loc);
12242 
12243   bool EnumConstantInBoolContext = false;
12244   for (const ExprResult &HS : {LHS, RHS}) {
12245     if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) {
12246       const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl());
12247       if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1)
12248         EnumConstantInBoolContext = true;
12249     }
12250   }
12251 
12252   if (EnumConstantInBoolContext)
12253     Diag(Loc, diag::warn_enum_constant_in_bool_context);
12254 
12255   // Diagnose cases where the user write a logical and/or but probably meant a
12256   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
12257   // is a constant.
12258   if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() &&
12259       !LHS.get()->getType()->isBooleanType() &&
12260       RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
12261       // Don't warn in macros or template instantiations.
12262       !Loc.isMacroID() && !inTemplateInstantiation()) {
12263     // If the RHS can be constant folded, and if it constant folds to something
12264     // that isn't 0 or 1 (which indicate a potential logical operation that
12265     // happened to fold to true/false) then warn.
12266     // Parens on the RHS are ignored.
12267     Expr::EvalResult EVResult;
12268     if (RHS.get()->EvaluateAsInt(EVResult, Context)) {
12269       llvm::APSInt Result = EVResult.Val.getInt();
12270       if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
12271            !RHS.get()->getExprLoc().isMacroID()) ||
12272           (Result != 0 && Result != 1)) {
12273         Diag(Loc, diag::warn_logical_instead_of_bitwise)
12274           << RHS.get()->getSourceRange()
12275           << (Opc == BO_LAnd ? "&&" : "||");
12276         // Suggest replacing the logical operator with the bitwise version
12277         Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
12278             << (Opc == BO_LAnd ? "&" : "|")
12279             << FixItHint::CreateReplacement(SourceRange(
12280                                                  Loc, getLocForEndOfToken(Loc)),
12281                                             Opc == BO_LAnd ? "&" : "|");
12282         if (Opc == BO_LAnd)
12283           // Suggest replacing "Foo() && kNonZero" with "Foo()"
12284           Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
12285               << FixItHint::CreateRemoval(
12286                      SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()),
12287                                  RHS.get()->getEndLoc()));
12288       }
12289     }
12290   }
12291 
12292   if (!Context.getLangOpts().CPlusPlus) {
12293     // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
12294     // not operate on the built-in scalar and vector float types.
12295     if (Context.getLangOpts().OpenCL &&
12296         Context.getLangOpts().OpenCLVersion < 120) {
12297       if (LHS.get()->getType()->isFloatingType() ||
12298           RHS.get()->getType()->isFloatingType())
12299         return InvalidOperands(Loc, LHS, RHS);
12300     }
12301 
12302     LHS = UsualUnaryConversions(LHS.get());
12303     if (LHS.isInvalid())
12304       return QualType();
12305 
12306     RHS = UsualUnaryConversions(RHS.get());
12307     if (RHS.isInvalid())
12308       return QualType();
12309 
12310     if (!LHS.get()->getType()->isScalarType() ||
12311         !RHS.get()->getType()->isScalarType())
12312       return InvalidOperands(Loc, LHS, RHS);
12313 
12314     return Context.IntTy;
12315   }
12316 
12317   // The following is safe because we only use this method for
12318   // non-overloadable operands.
12319 
12320   // C++ [expr.log.and]p1
12321   // C++ [expr.log.or]p1
12322   // The operands are both contextually converted to type bool.
12323   ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
12324   if (LHSRes.isInvalid())
12325     return InvalidOperands(Loc, LHS, RHS);
12326   LHS = LHSRes;
12327 
12328   ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
12329   if (RHSRes.isInvalid())
12330     return InvalidOperands(Loc, LHS, RHS);
12331   RHS = RHSRes;
12332 
12333   // C++ [expr.log.and]p2
12334   // C++ [expr.log.or]p2
12335   // The result is a bool.
12336   return Context.BoolTy;
12337 }
12338 
12339 static bool IsReadonlyMessage(Expr *E, Sema &S) {
12340   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
12341   if (!ME) return false;
12342   if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
12343   ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
12344       ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
12345   if (!Base) return false;
12346   return Base->getMethodDecl() != nullptr;
12347 }
12348 
12349 /// Is the given expression (which must be 'const') a reference to a
12350 /// variable which was originally non-const, but which has become
12351 /// 'const' due to being captured within a block?
12352 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
12353 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
12354   assert(E->isLValue() && E->getType().isConstQualified());
12355   E = E->IgnoreParens();
12356 
12357   // Must be a reference to a declaration from an enclosing scope.
12358   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
12359   if (!DRE) return NCCK_None;
12360   if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
12361 
12362   // The declaration must be a variable which is not declared 'const'.
12363   VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
12364   if (!var) return NCCK_None;
12365   if (var->getType().isConstQualified()) return NCCK_None;
12366   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
12367 
12368   // Decide whether the first capture was for a block or a lambda.
12369   DeclContext *DC = S.CurContext, *Prev = nullptr;
12370   // Decide whether the first capture was for a block or a lambda.
12371   while (DC) {
12372     // For init-capture, it is possible that the variable belongs to the
12373     // template pattern of the current context.
12374     if (auto *FD = dyn_cast<FunctionDecl>(DC))
12375       if (var->isInitCapture() &&
12376           FD->getTemplateInstantiationPattern() == var->getDeclContext())
12377         break;
12378     if (DC == var->getDeclContext())
12379       break;
12380     Prev = DC;
12381     DC = DC->getParent();
12382   }
12383   // Unless we have an init-capture, we've gone one step too far.
12384   if (!var->isInitCapture())
12385     DC = Prev;
12386   return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
12387 }
12388 
12389 static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
12390   Ty = Ty.getNonReferenceType();
12391   if (IsDereference && Ty->isPointerType())
12392     Ty = Ty->getPointeeType();
12393   return !Ty.isConstQualified();
12394 }
12395 
12396 // Update err_typecheck_assign_const and note_typecheck_assign_const
12397 // when this enum is changed.
12398 enum {
12399   ConstFunction,
12400   ConstVariable,
12401   ConstMember,
12402   ConstMethod,
12403   NestedConstMember,
12404   ConstUnknown,  // Keep as last element
12405 };
12406 
12407 /// Emit the "read-only variable not assignable" error and print notes to give
12408 /// more information about why the variable is not assignable, such as pointing
12409 /// to the declaration of a const variable, showing that a method is const, or
12410 /// that the function is returning a const reference.
12411 static void DiagnoseConstAssignment(Sema &S, const Expr *E,
12412                                     SourceLocation Loc) {
12413   SourceRange ExprRange = E->getSourceRange();
12414 
12415   // Only emit one error on the first const found.  All other consts will emit
12416   // a note to the error.
12417   bool DiagnosticEmitted = false;
12418 
12419   // Track if the current expression is the result of a dereference, and if the
12420   // next checked expression is the result of a dereference.
12421   bool IsDereference = false;
12422   bool NextIsDereference = false;
12423 
12424   // Loop to process MemberExpr chains.
12425   while (true) {
12426     IsDereference = NextIsDereference;
12427 
12428     E = E->IgnoreImplicit()->IgnoreParenImpCasts();
12429     if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
12430       NextIsDereference = ME->isArrow();
12431       const ValueDecl *VD = ME->getMemberDecl();
12432       if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
12433         // Mutable fields can be modified even if the class is const.
12434         if (Field->isMutable()) {
12435           assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
12436           break;
12437         }
12438 
12439         if (!IsTypeModifiable(Field->getType(), IsDereference)) {
12440           if (!DiagnosticEmitted) {
12441             S.Diag(Loc, diag::err_typecheck_assign_const)
12442                 << ExprRange << ConstMember << false /*static*/ << Field
12443                 << Field->getType();
12444             DiagnosticEmitted = true;
12445           }
12446           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
12447               << ConstMember << false /*static*/ << Field << Field->getType()
12448               << Field->getSourceRange();
12449         }
12450         E = ME->getBase();
12451         continue;
12452       } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
12453         if (VDecl->getType().isConstQualified()) {
12454           if (!DiagnosticEmitted) {
12455             S.Diag(Loc, diag::err_typecheck_assign_const)
12456                 << ExprRange << ConstMember << true /*static*/ << VDecl
12457                 << VDecl->getType();
12458             DiagnosticEmitted = true;
12459           }
12460           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
12461               << ConstMember << true /*static*/ << VDecl << VDecl->getType()
12462               << VDecl->getSourceRange();
12463         }
12464         // Static fields do not inherit constness from parents.
12465         break;
12466       }
12467       break; // End MemberExpr
12468     } else if (const ArraySubscriptExpr *ASE =
12469                    dyn_cast<ArraySubscriptExpr>(E)) {
12470       E = ASE->getBase()->IgnoreParenImpCasts();
12471       continue;
12472     } else if (const ExtVectorElementExpr *EVE =
12473                    dyn_cast<ExtVectorElementExpr>(E)) {
12474       E = EVE->getBase()->IgnoreParenImpCasts();
12475       continue;
12476     }
12477     break;
12478   }
12479 
12480   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
12481     // Function calls
12482     const FunctionDecl *FD = CE->getDirectCallee();
12483     if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
12484       if (!DiagnosticEmitted) {
12485         S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
12486                                                       << ConstFunction << FD;
12487         DiagnosticEmitted = true;
12488       }
12489       S.Diag(FD->getReturnTypeSourceRange().getBegin(),
12490              diag::note_typecheck_assign_const)
12491           << ConstFunction << FD << FD->getReturnType()
12492           << FD->getReturnTypeSourceRange();
12493     }
12494   } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
12495     // Point to variable declaration.
12496     if (const ValueDecl *VD = DRE->getDecl()) {
12497       if (!IsTypeModifiable(VD->getType(), IsDereference)) {
12498         if (!DiagnosticEmitted) {
12499           S.Diag(Loc, diag::err_typecheck_assign_const)
12500               << ExprRange << ConstVariable << VD << VD->getType();
12501           DiagnosticEmitted = true;
12502         }
12503         S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
12504             << ConstVariable << VD << VD->getType() << VD->getSourceRange();
12505       }
12506     }
12507   } else if (isa<CXXThisExpr>(E)) {
12508     if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
12509       if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
12510         if (MD->isConst()) {
12511           if (!DiagnosticEmitted) {
12512             S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
12513                                                           << ConstMethod << MD;
12514             DiagnosticEmitted = true;
12515           }
12516           S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
12517               << ConstMethod << MD << MD->getSourceRange();
12518         }
12519       }
12520     }
12521   }
12522 
12523   if (DiagnosticEmitted)
12524     return;
12525 
12526   // Can't determine a more specific message, so display the generic error.
12527   S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
12528 }
12529 
12530 enum OriginalExprKind {
12531   OEK_Variable,
12532   OEK_Member,
12533   OEK_LValue
12534 };
12535 
12536 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD,
12537                                          const RecordType *Ty,
12538                                          SourceLocation Loc, SourceRange Range,
12539                                          OriginalExprKind OEK,
12540                                          bool &DiagnosticEmitted) {
12541   std::vector<const RecordType *> RecordTypeList;
12542   RecordTypeList.push_back(Ty);
12543   unsigned NextToCheckIndex = 0;
12544   // We walk the record hierarchy breadth-first to ensure that we print
12545   // diagnostics in field nesting order.
12546   while (RecordTypeList.size() > NextToCheckIndex) {
12547     bool IsNested = NextToCheckIndex > 0;
12548     for (const FieldDecl *Field :
12549          RecordTypeList[NextToCheckIndex]->getDecl()->fields()) {
12550       // First, check every field for constness.
12551       QualType FieldTy = Field->getType();
12552       if (FieldTy.isConstQualified()) {
12553         if (!DiagnosticEmitted) {
12554           S.Diag(Loc, diag::err_typecheck_assign_const)
12555               << Range << NestedConstMember << OEK << VD
12556               << IsNested << Field;
12557           DiagnosticEmitted = true;
12558         }
12559         S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
12560             << NestedConstMember << IsNested << Field
12561             << FieldTy << Field->getSourceRange();
12562       }
12563 
12564       // Then we append it to the list to check next in order.
12565       FieldTy = FieldTy.getCanonicalType();
12566       if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) {
12567         if (llvm::find(RecordTypeList, FieldRecTy) == RecordTypeList.end())
12568           RecordTypeList.push_back(FieldRecTy);
12569       }
12570     }
12571     ++NextToCheckIndex;
12572   }
12573 }
12574 
12575 /// Emit an error for the case where a record we are trying to assign to has a
12576 /// const-qualified field somewhere in its hierarchy.
12577 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
12578                                          SourceLocation Loc) {
12579   QualType Ty = E->getType();
12580   assert(Ty->isRecordType() && "lvalue was not record?");
12581   SourceRange Range = E->getSourceRange();
12582   const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>();
12583   bool DiagEmitted = false;
12584 
12585   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
12586     DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
12587             Range, OEK_Member, DiagEmitted);
12588   else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
12589     DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
12590             Range, OEK_Variable, DiagEmitted);
12591   else
12592     DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
12593             Range, OEK_LValue, DiagEmitted);
12594   if (!DiagEmitted)
12595     DiagnoseConstAssignment(S, E, Loc);
12596 }
12597 
12598 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
12599 /// emit an error and return true.  If so, return false.
12600 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
12601   assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
12602 
12603   S.CheckShadowingDeclModification(E, Loc);
12604 
12605   SourceLocation OrigLoc = Loc;
12606   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
12607                                                               &Loc);
12608   if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
12609     IsLV = Expr::MLV_InvalidMessageExpression;
12610   if (IsLV == Expr::MLV_Valid)
12611     return false;
12612 
12613   unsigned DiagID = 0;
12614   bool NeedType = false;
12615   switch (IsLV) { // C99 6.5.16p2
12616   case Expr::MLV_ConstQualified:
12617     // Use a specialized diagnostic when we're assigning to an object
12618     // from an enclosing function or block.
12619     if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
12620       if (NCCK == NCCK_Block)
12621         DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
12622       else
12623         DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
12624       break;
12625     }
12626 
12627     // In ARC, use some specialized diagnostics for occasions where we
12628     // infer 'const'.  These are always pseudo-strong variables.
12629     if (S.getLangOpts().ObjCAutoRefCount) {
12630       DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
12631       if (declRef && isa<VarDecl>(declRef->getDecl())) {
12632         VarDecl *var = cast<VarDecl>(declRef->getDecl());
12633 
12634         // Use the normal diagnostic if it's pseudo-__strong but the
12635         // user actually wrote 'const'.
12636         if (var->isARCPseudoStrong() &&
12637             (!var->getTypeSourceInfo() ||
12638              !var->getTypeSourceInfo()->getType().isConstQualified())) {
12639           // There are three pseudo-strong cases:
12640           //  - self
12641           ObjCMethodDecl *method = S.getCurMethodDecl();
12642           if (method && var == method->getSelfDecl()) {
12643             DiagID = method->isClassMethod()
12644               ? diag::err_typecheck_arc_assign_self_class_method
12645               : diag::err_typecheck_arc_assign_self;
12646 
12647           //  - Objective-C externally_retained attribute.
12648           } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
12649                      isa<ParmVarDecl>(var)) {
12650             DiagID = diag::err_typecheck_arc_assign_externally_retained;
12651 
12652           //  - fast enumeration variables
12653           } else {
12654             DiagID = diag::err_typecheck_arr_assign_enumeration;
12655           }
12656 
12657           SourceRange Assign;
12658           if (Loc != OrigLoc)
12659             Assign = SourceRange(OrigLoc, OrigLoc);
12660           S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
12661           // We need to preserve the AST regardless, so migration tool
12662           // can do its job.
12663           return false;
12664         }
12665       }
12666     }
12667 
12668     // If none of the special cases above are triggered, then this is a
12669     // simple const assignment.
12670     if (DiagID == 0) {
12671       DiagnoseConstAssignment(S, E, Loc);
12672       return true;
12673     }
12674 
12675     break;
12676   case Expr::MLV_ConstAddrSpace:
12677     DiagnoseConstAssignment(S, E, Loc);
12678     return true;
12679   case Expr::MLV_ConstQualifiedField:
12680     DiagnoseRecursiveConstFields(S, E, Loc);
12681     return true;
12682   case Expr::MLV_ArrayType:
12683   case Expr::MLV_ArrayTemporary:
12684     DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
12685     NeedType = true;
12686     break;
12687   case Expr::MLV_NotObjectType:
12688     DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
12689     NeedType = true;
12690     break;
12691   case Expr::MLV_LValueCast:
12692     DiagID = diag::err_typecheck_lvalue_casts_not_supported;
12693     break;
12694   case Expr::MLV_Valid:
12695     llvm_unreachable("did not take early return for MLV_Valid");
12696   case Expr::MLV_InvalidExpression:
12697   case Expr::MLV_MemberFunction:
12698   case Expr::MLV_ClassTemporary:
12699     DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
12700     break;
12701   case Expr::MLV_IncompleteType:
12702   case Expr::MLV_IncompleteVoidType:
12703     return S.RequireCompleteType(Loc, E->getType(),
12704              diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
12705   case Expr::MLV_DuplicateVectorComponents:
12706     DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
12707     break;
12708   case Expr::MLV_NoSetterProperty:
12709     llvm_unreachable("readonly properties should be processed differently");
12710   case Expr::MLV_InvalidMessageExpression:
12711     DiagID = diag::err_readonly_message_assignment;
12712     break;
12713   case Expr::MLV_SubObjCPropertySetting:
12714     DiagID = diag::err_no_subobject_property_setting;
12715     break;
12716   }
12717 
12718   SourceRange Assign;
12719   if (Loc != OrigLoc)
12720     Assign = SourceRange(OrigLoc, OrigLoc);
12721   if (NeedType)
12722     S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
12723   else
12724     S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
12725   return true;
12726 }
12727 
12728 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
12729                                          SourceLocation Loc,
12730                                          Sema &Sema) {
12731   if (Sema.inTemplateInstantiation())
12732     return;
12733   if (Sema.isUnevaluatedContext())
12734     return;
12735   if (Loc.isInvalid() || Loc.isMacroID())
12736     return;
12737   if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
12738     return;
12739 
12740   // C / C++ fields
12741   MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
12742   MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
12743   if (ML && MR) {
12744     if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
12745       return;
12746     const ValueDecl *LHSDecl =
12747         cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl());
12748     const ValueDecl *RHSDecl =
12749         cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl());
12750     if (LHSDecl != RHSDecl)
12751       return;
12752     if (LHSDecl->getType().isVolatileQualified())
12753       return;
12754     if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
12755       if (RefTy->getPointeeType().isVolatileQualified())
12756         return;
12757 
12758     Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
12759   }
12760 
12761   // Objective-C instance variables
12762   ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
12763   ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
12764   if (OL && OR && OL->getDecl() == OR->getDecl()) {
12765     DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
12766     DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
12767     if (RL && RR && RL->getDecl() == RR->getDecl())
12768       Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
12769   }
12770 }
12771 
12772 // C99 6.5.16.1
12773 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
12774                                        SourceLocation Loc,
12775                                        QualType CompoundType) {
12776   assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
12777 
12778   // Verify that LHS is a modifiable lvalue, and emit error if not.
12779   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
12780     return QualType();
12781 
12782   QualType LHSType = LHSExpr->getType();
12783   QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
12784                                              CompoundType;
12785   // OpenCL v1.2 s6.1.1.1 p2:
12786   // The half data type can only be used to declare a pointer to a buffer that
12787   // contains half values
12788   if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
12789     LHSType->isHalfType()) {
12790     Diag(Loc, diag::err_opencl_half_load_store) << 1
12791         << LHSType.getUnqualifiedType();
12792     return QualType();
12793   }
12794 
12795   AssignConvertType ConvTy;
12796   if (CompoundType.isNull()) {
12797     Expr *RHSCheck = RHS.get();
12798 
12799     CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
12800 
12801     QualType LHSTy(LHSType);
12802     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
12803     if (RHS.isInvalid())
12804       return QualType();
12805     // Special case of NSObject attributes on c-style pointer types.
12806     if (ConvTy == IncompatiblePointer &&
12807         ((Context.isObjCNSObjectType(LHSType) &&
12808           RHSType->isObjCObjectPointerType()) ||
12809          (Context.isObjCNSObjectType(RHSType) &&
12810           LHSType->isObjCObjectPointerType())))
12811       ConvTy = Compatible;
12812 
12813     if (ConvTy == Compatible &&
12814         LHSType->isObjCObjectType())
12815         Diag(Loc, diag::err_objc_object_assignment)
12816           << LHSType;
12817 
12818     // If the RHS is a unary plus or minus, check to see if they = and + are
12819     // right next to each other.  If so, the user may have typo'd "x =+ 4"
12820     // instead of "x += 4".
12821     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
12822       RHSCheck = ICE->getSubExpr();
12823     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
12824       if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
12825           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
12826           // Only if the two operators are exactly adjacent.
12827           Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
12828           // And there is a space or other character before the subexpr of the
12829           // unary +/-.  We don't want to warn on "x=-1".
12830           Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() &&
12831           UO->getSubExpr()->getBeginLoc().isFileID()) {
12832         Diag(Loc, diag::warn_not_compound_assign)
12833           << (UO->getOpcode() == UO_Plus ? "+" : "-")
12834           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
12835       }
12836     }
12837 
12838     if (ConvTy == Compatible) {
12839       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
12840         // Warn about retain cycles where a block captures the LHS, but
12841         // not if the LHS is a simple variable into which the block is
12842         // being stored...unless that variable can be captured by reference!
12843         const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
12844         const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
12845         if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
12846           checkRetainCycles(LHSExpr, RHS.get());
12847       }
12848 
12849       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
12850           LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
12851         // It is safe to assign a weak reference into a strong variable.
12852         // Although this code can still have problems:
12853         //   id x = self.weakProp;
12854         //   id y = self.weakProp;
12855         // we do not warn to warn spuriously when 'x' and 'y' are on separate
12856         // paths through the function. This should be revisited if
12857         // -Wrepeated-use-of-weak is made flow-sensitive.
12858         // For ObjCWeak only, we do not warn if the assign is to a non-weak
12859         // variable, which will be valid for the current autorelease scope.
12860         if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
12861                              RHS.get()->getBeginLoc()))
12862           getCurFunction()->markSafeWeakUse(RHS.get());
12863 
12864       } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
12865         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
12866       }
12867     }
12868   } else {
12869     // Compound assignment "x += y"
12870     ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
12871   }
12872 
12873   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
12874                                RHS.get(), AA_Assigning))
12875     return QualType();
12876 
12877   CheckForNullPointerDereference(*this, LHSExpr);
12878 
12879   if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) {
12880     if (CompoundType.isNull()) {
12881       // C++2a [expr.ass]p5:
12882       //   A simple-assignment whose left operand is of a volatile-qualified
12883       //   type is deprecated unless the assignment is either a discarded-value
12884       //   expression or an unevaluated operand
12885       ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr);
12886     } else {
12887       // C++2a [expr.ass]p6:
12888       //   [Compound-assignment] expressions are deprecated if E1 has
12889       //   volatile-qualified type
12890       Diag(Loc, diag::warn_deprecated_compound_assign_volatile) << LHSType;
12891     }
12892   }
12893 
12894   // C99 6.5.16p3: The type of an assignment expression is the type of the
12895   // left operand unless the left operand has qualified type, in which case
12896   // it is the unqualified version of the type of the left operand.
12897   // C99 6.5.16.1p2: In simple assignment, the value of the right operand
12898   // is converted to the type of the assignment expression (above).
12899   // C++ 5.17p1: the type of the assignment expression is that of its left
12900   // operand.
12901   return (getLangOpts().CPlusPlus
12902           ? LHSType : LHSType.getUnqualifiedType());
12903 }
12904 
12905 // Only ignore explicit casts to void.
12906 static bool IgnoreCommaOperand(const Expr *E) {
12907   E = E->IgnoreParens();
12908 
12909   if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
12910     if (CE->getCastKind() == CK_ToVoid) {
12911       return true;
12912     }
12913 
12914     // static_cast<void> on a dependent type will not show up as CK_ToVoid.
12915     if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
12916         CE->getSubExpr()->getType()->isDependentType()) {
12917       return true;
12918     }
12919   }
12920 
12921   return false;
12922 }
12923 
12924 // Look for instances where it is likely the comma operator is confused with
12925 // another operator.  There is an explicit list of acceptable expressions for
12926 // the left hand side of the comma operator, otherwise emit a warning.
12927 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
12928   // No warnings in macros
12929   if (Loc.isMacroID())
12930     return;
12931 
12932   // Don't warn in template instantiations.
12933   if (inTemplateInstantiation())
12934     return;
12935 
12936   // Scope isn't fine-grained enough to explicitly list the specific cases, so
12937   // instead, skip more than needed, then call back into here with the
12938   // CommaVisitor in SemaStmt.cpp.
12939   // The listed locations are the initialization and increment portions
12940   // of a for loop.  The additional checks are on the condition of
12941   // if statements, do/while loops, and for loops.
12942   // Differences in scope flags for C89 mode requires the extra logic.
12943   const unsigned ForIncrementFlags =
12944       getLangOpts().C99 || getLangOpts().CPlusPlus
12945           ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope
12946           : Scope::ContinueScope | Scope::BreakScope;
12947   const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
12948   const unsigned ScopeFlags = getCurScope()->getFlags();
12949   if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
12950       (ScopeFlags & ForInitFlags) == ForInitFlags)
12951     return;
12952 
12953   // If there are multiple comma operators used together, get the RHS of the
12954   // of the comma operator as the LHS.
12955   while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
12956     if (BO->getOpcode() != BO_Comma)
12957       break;
12958     LHS = BO->getRHS();
12959   }
12960 
12961   // Only allow some expressions on LHS to not warn.
12962   if (IgnoreCommaOperand(LHS))
12963     return;
12964 
12965   Diag(Loc, diag::warn_comma_operator);
12966   Diag(LHS->getBeginLoc(), diag::note_cast_to_void)
12967       << LHS->getSourceRange()
12968       << FixItHint::CreateInsertion(LHS->getBeginLoc(),
12969                                     LangOpts.CPlusPlus ? "static_cast<void>("
12970                                                        : "(void)(")
12971       << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()),
12972                                     ")");
12973 }
12974 
12975 // C99 6.5.17
12976 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
12977                                    SourceLocation Loc) {
12978   LHS = S.CheckPlaceholderExpr(LHS.get());
12979   RHS = S.CheckPlaceholderExpr(RHS.get());
12980   if (LHS.isInvalid() || RHS.isInvalid())
12981     return QualType();
12982 
12983   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
12984   // operands, but not unary promotions.
12985   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
12986 
12987   // So we treat the LHS as a ignored value, and in C++ we allow the
12988   // containing site to determine what should be done with the RHS.
12989   LHS = S.IgnoredValueConversions(LHS.get());
12990   if (LHS.isInvalid())
12991     return QualType();
12992 
12993   S.DiagnoseUnusedExprResult(LHS.get());
12994 
12995   if (!S.getLangOpts().CPlusPlus) {
12996     RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
12997     if (RHS.isInvalid())
12998       return QualType();
12999     if (!RHS.get()->getType()->isVoidType())
13000       S.RequireCompleteType(Loc, RHS.get()->getType(),
13001                             diag::err_incomplete_type);
13002   }
13003 
13004   if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
13005     S.DiagnoseCommaOperator(LHS.get(), Loc);
13006 
13007   return RHS.get()->getType();
13008 }
13009 
13010 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
13011 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
13012 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
13013                                                ExprValueKind &VK,
13014                                                ExprObjectKind &OK,
13015                                                SourceLocation OpLoc,
13016                                                bool IsInc, bool IsPrefix) {
13017   if (Op->isTypeDependent())
13018     return S.Context.DependentTy;
13019 
13020   QualType ResType = Op->getType();
13021   // Atomic types can be used for increment / decrement where the non-atomic
13022   // versions can, so ignore the _Atomic() specifier for the purpose of
13023   // checking.
13024   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
13025     ResType = ResAtomicType->getValueType();
13026 
13027   assert(!ResType.isNull() && "no type for increment/decrement expression");
13028 
13029   if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
13030     // Decrement of bool is not allowed.
13031     if (!IsInc) {
13032       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
13033       return QualType();
13034     }
13035     // Increment of bool sets it to true, but is deprecated.
13036     S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
13037                                               : diag::warn_increment_bool)
13038       << Op->getSourceRange();
13039   } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
13040     // Error on enum increments and decrements in C++ mode
13041     S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
13042     return QualType();
13043   } else if (ResType->isRealType()) {
13044     // OK!
13045   } else if (ResType->isPointerType()) {
13046     // C99 6.5.2.4p2, 6.5.6p2
13047     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
13048       return QualType();
13049   } else if (ResType->isObjCObjectPointerType()) {
13050     // On modern runtimes, ObjC pointer arithmetic is forbidden.
13051     // Otherwise, we just need a complete type.
13052     if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
13053         checkArithmeticOnObjCPointer(S, OpLoc, Op))
13054       return QualType();
13055   } else if (ResType->isAnyComplexType()) {
13056     // C99 does not support ++/-- on complex types, we allow as an extension.
13057     S.Diag(OpLoc, diag::ext_integer_increment_complex)
13058       << ResType << Op->getSourceRange();
13059   } else if (ResType->isPlaceholderType()) {
13060     ExprResult PR = S.CheckPlaceholderExpr(Op);
13061     if (PR.isInvalid()) return QualType();
13062     return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
13063                                           IsInc, IsPrefix);
13064   } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
13065     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
13066   } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
13067              (ResType->castAs<VectorType>()->getVectorKind() !=
13068               VectorType::AltiVecBool)) {
13069     // The z vector extensions allow ++ and -- for non-bool vectors.
13070   } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
13071             ResType->castAs<VectorType>()->getElementType()->isIntegerType()) {
13072     // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
13073   } else {
13074     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
13075       << ResType << int(IsInc) << Op->getSourceRange();
13076     return QualType();
13077   }
13078   // At this point, we know we have a real, complex or pointer type.
13079   // Now make sure the operand is a modifiable lvalue.
13080   if (CheckForModifiableLvalue(Op, OpLoc, S))
13081     return QualType();
13082   if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) {
13083     // C++2a [expr.pre.inc]p1, [expr.post.inc]p1:
13084     //   An operand with volatile-qualified type is deprecated
13085     S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile)
13086         << IsInc << ResType;
13087   }
13088   // In C++, a prefix increment is the same type as the operand. Otherwise
13089   // (in C or with postfix), the increment is the unqualified type of the
13090   // operand.
13091   if (IsPrefix && S.getLangOpts().CPlusPlus) {
13092     VK = VK_LValue;
13093     OK = Op->getObjectKind();
13094     return ResType;
13095   } else {
13096     VK = VK_RValue;
13097     return ResType.getUnqualifiedType();
13098   }
13099 }
13100 
13101 
13102 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
13103 /// This routine allows us to typecheck complex/recursive expressions
13104 /// where the declaration is needed for type checking. We only need to
13105 /// handle cases when the expression references a function designator
13106 /// or is an lvalue. Here are some examples:
13107 ///  - &(x) => x
13108 ///  - &*****f => f for f a function designator.
13109 ///  - &s.xx => s
13110 ///  - &s.zz[1].yy -> s, if zz is an array
13111 ///  - *(x + 1) -> x, if x is an array
13112 ///  - &"123"[2] -> 0
13113 ///  - & __real__ x -> x
13114 ///
13115 /// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to
13116 /// members.
13117 static ValueDecl *getPrimaryDecl(Expr *E) {
13118   switch (E->getStmtClass()) {
13119   case Stmt::DeclRefExprClass:
13120     return cast<DeclRefExpr>(E)->getDecl();
13121   case Stmt::MemberExprClass:
13122     // If this is an arrow operator, the address is an offset from
13123     // the base's value, so the object the base refers to is
13124     // irrelevant.
13125     if (cast<MemberExpr>(E)->isArrow())
13126       return nullptr;
13127     // Otherwise, the expression refers to a part of the base
13128     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
13129   case Stmt::ArraySubscriptExprClass: {
13130     // FIXME: This code shouldn't be necessary!  We should catch the implicit
13131     // promotion of register arrays earlier.
13132     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
13133     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
13134       if (ICE->getSubExpr()->getType()->isArrayType())
13135         return getPrimaryDecl(ICE->getSubExpr());
13136     }
13137     return nullptr;
13138   }
13139   case Stmt::UnaryOperatorClass: {
13140     UnaryOperator *UO = cast<UnaryOperator>(E);
13141 
13142     switch(UO->getOpcode()) {
13143     case UO_Real:
13144     case UO_Imag:
13145     case UO_Extension:
13146       return getPrimaryDecl(UO->getSubExpr());
13147     default:
13148       return nullptr;
13149     }
13150   }
13151   case Stmt::ParenExprClass:
13152     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
13153   case Stmt::ImplicitCastExprClass:
13154     // If the result of an implicit cast is an l-value, we care about
13155     // the sub-expression; otherwise, the result here doesn't matter.
13156     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
13157   case Stmt::CXXUuidofExprClass:
13158     return cast<CXXUuidofExpr>(E)->getGuidDecl();
13159   default:
13160     return nullptr;
13161   }
13162 }
13163 
13164 namespace {
13165 enum {
13166   AO_Bit_Field = 0,
13167   AO_Vector_Element = 1,
13168   AO_Property_Expansion = 2,
13169   AO_Register_Variable = 3,
13170   AO_Matrix_Element = 4,
13171   AO_No_Error = 5
13172 };
13173 }
13174 /// Diagnose invalid operand for address of operations.
13175 ///
13176 /// \param Type The type of operand which cannot have its address taken.
13177 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
13178                                          Expr *E, unsigned Type) {
13179   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
13180 }
13181 
13182 /// CheckAddressOfOperand - The operand of & must be either a function
13183 /// designator or an lvalue designating an object. If it is an lvalue, the
13184 /// object cannot be declared with storage class register or be a bit field.
13185 /// Note: The usual conversions are *not* applied to the operand of the &
13186 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
13187 /// In C++, the operand might be an overloaded function name, in which case
13188 /// we allow the '&' but retain the overloaded-function type.
13189 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
13190   if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
13191     if (PTy->getKind() == BuiltinType::Overload) {
13192       Expr *E = OrigOp.get()->IgnoreParens();
13193       if (!isa<OverloadExpr>(E)) {
13194         assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
13195         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
13196           << OrigOp.get()->getSourceRange();
13197         return QualType();
13198       }
13199 
13200       OverloadExpr *Ovl = cast<OverloadExpr>(E);
13201       if (isa<UnresolvedMemberExpr>(Ovl))
13202         if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
13203           Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
13204             << OrigOp.get()->getSourceRange();
13205           return QualType();
13206         }
13207 
13208       return Context.OverloadTy;
13209     }
13210 
13211     if (PTy->getKind() == BuiltinType::UnknownAny)
13212       return Context.UnknownAnyTy;
13213 
13214     if (PTy->getKind() == BuiltinType::BoundMember) {
13215       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
13216         << OrigOp.get()->getSourceRange();
13217       return QualType();
13218     }
13219 
13220     OrigOp = CheckPlaceholderExpr(OrigOp.get());
13221     if (OrigOp.isInvalid()) return QualType();
13222   }
13223 
13224   if (OrigOp.get()->isTypeDependent())
13225     return Context.DependentTy;
13226 
13227   assert(!OrigOp.get()->getType()->isPlaceholderType());
13228 
13229   // Make sure to ignore parentheses in subsequent checks
13230   Expr *op = OrigOp.get()->IgnoreParens();
13231 
13232   // In OpenCL captures for blocks called as lambda functions
13233   // are located in the private address space. Blocks used in
13234   // enqueue_kernel can be located in a different address space
13235   // depending on a vendor implementation. Thus preventing
13236   // taking an address of the capture to avoid invalid AS casts.
13237   if (LangOpts.OpenCL) {
13238     auto* VarRef = dyn_cast<DeclRefExpr>(op);
13239     if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
13240       Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
13241       return QualType();
13242     }
13243   }
13244 
13245   if (getLangOpts().C99) {
13246     // Implement C99-only parts of addressof rules.
13247     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
13248       if (uOp->getOpcode() == UO_Deref)
13249         // Per C99 6.5.3.2, the address of a deref always returns a valid result
13250         // (assuming the deref expression is valid).
13251         return uOp->getSubExpr()->getType();
13252     }
13253     // Technically, there should be a check for array subscript
13254     // expressions here, but the result of one is always an lvalue anyway.
13255   }
13256   ValueDecl *dcl = getPrimaryDecl(op);
13257 
13258   if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
13259     if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
13260                                            op->getBeginLoc()))
13261       return QualType();
13262 
13263   Expr::LValueClassification lval = op->ClassifyLValue(Context);
13264   unsigned AddressOfError = AO_No_Error;
13265 
13266   if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
13267     bool sfinae = (bool)isSFINAEContext();
13268     Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
13269                                   : diag::ext_typecheck_addrof_temporary)
13270       << op->getType() << op->getSourceRange();
13271     if (sfinae)
13272       return QualType();
13273     // Materialize the temporary as an lvalue so that we can take its address.
13274     OrigOp = op =
13275         CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
13276   } else if (isa<ObjCSelectorExpr>(op)) {
13277     return Context.getPointerType(op->getType());
13278   } else if (lval == Expr::LV_MemberFunction) {
13279     // If it's an instance method, make a member pointer.
13280     // The expression must have exactly the form &A::foo.
13281 
13282     // If the underlying expression isn't a decl ref, give up.
13283     if (!isa<DeclRefExpr>(op)) {
13284       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
13285         << OrigOp.get()->getSourceRange();
13286       return QualType();
13287     }
13288     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
13289     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
13290 
13291     // The id-expression was parenthesized.
13292     if (OrigOp.get() != DRE) {
13293       Diag(OpLoc, diag::err_parens_pointer_member_function)
13294         << OrigOp.get()->getSourceRange();
13295 
13296     // The method was named without a qualifier.
13297     } else if (!DRE->getQualifier()) {
13298       if (MD->getParent()->getName().empty())
13299         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
13300           << op->getSourceRange();
13301       else {
13302         SmallString<32> Str;
13303         StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
13304         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
13305           << op->getSourceRange()
13306           << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
13307       }
13308     }
13309 
13310     // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
13311     if (isa<CXXDestructorDecl>(MD))
13312       Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
13313 
13314     QualType MPTy = Context.getMemberPointerType(
13315         op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
13316     // Under the MS ABI, lock down the inheritance model now.
13317     if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13318       (void)isCompleteType(OpLoc, MPTy);
13319     return MPTy;
13320   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
13321     // C99 6.5.3.2p1
13322     // The operand must be either an l-value or a function designator
13323     if (!op->getType()->isFunctionType()) {
13324       // Use a special diagnostic for loads from property references.
13325       if (isa<PseudoObjectExpr>(op)) {
13326         AddressOfError = AO_Property_Expansion;
13327       } else {
13328         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
13329           << op->getType() << op->getSourceRange();
13330         return QualType();
13331       }
13332     }
13333   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
13334     // The operand cannot be a bit-field
13335     AddressOfError = AO_Bit_Field;
13336   } else if (op->getObjectKind() == OK_VectorComponent) {
13337     // The operand cannot be an element of a vector
13338     AddressOfError = AO_Vector_Element;
13339   } else if (op->getObjectKind() == OK_MatrixComponent) {
13340     // The operand cannot be an element of a matrix.
13341     AddressOfError = AO_Matrix_Element;
13342   } else if (dcl) { // C99 6.5.3.2p1
13343     // We have an lvalue with a decl. Make sure the decl is not declared
13344     // with the register storage-class specifier.
13345     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
13346       // in C++ it is not error to take address of a register
13347       // variable (c++03 7.1.1P3)
13348       if (vd->getStorageClass() == SC_Register &&
13349           !getLangOpts().CPlusPlus) {
13350         AddressOfError = AO_Register_Variable;
13351       }
13352     } else if (isa<MSPropertyDecl>(dcl)) {
13353       AddressOfError = AO_Property_Expansion;
13354     } else if (isa<FunctionTemplateDecl>(dcl)) {
13355       return Context.OverloadTy;
13356     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
13357       // Okay: we can take the address of a field.
13358       // Could be a pointer to member, though, if there is an explicit
13359       // scope qualifier for the class.
13360       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
13361         DeclContext *Ctx = dcl->getDeclContext();
13362         if (Ctx && Ctx->isRecord()) {
13363           if (dcl->getType()->isReferenceType()) {
13364             Diag(OpLoc,
13365                  diag::err_cannot_form_pointer_to_member_of_reference_type)
13366               << dcl->getDeclName() << dcl->getType();
13367             return QualType();
13368           }
13369 
13370           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
13371             Ctx = Ctx->getParent();
13372 
13373           QualType MPTy = Context.getMemberPointerType(
13374               op->getType(),
13375               Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
13376           // Under the MS ABI, lock down the inheritance model now.
13377           if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13378             (void)isCompleteType(OpLoc, MPTy);
13379           return MPTy;
13380         }
13381       }
13382     } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) &&
13383                !isa<BindingDecl>(dcl) && !isa<MSGuidDecl>(dcl))
13384       llvm_unreachable("Unknown/unexpected decl type");
13385   }
13386 
13387   if (AddressOfError != AO_No_Error) {
13388     diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
13389     return QualType();
13390   }
13391 
13392   if (lval == Expr::LV_IncompleteVoidType) {
13393     // Taking the address of a void variable is technically illegal, but we
13394     // allow it in cases which are otherwise valid.
13395     // Example: "extern void x; void* y = &x;".
13396     Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
13397   }
13398 
13399   // If the operand has type "type", the result has type "pointer to type".
13400   if (op->getType()->isObjCObjectType())
13401     return Context.getObjCObjectPointerType(op->getType());
13402 
13403   CheckAddressOfPackedMember(op);
13404 
13405   return Context.getPointerType(op->getType());
13406 }
13407 
13408 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
13409   const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
13410   if (!DRE)
13411     return;
13412   const Decl *D = DRE->getDecl();
13413   if (!D)
13414     return;
13415   const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
13416   if (!Param)
13417     return;
13418   if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
13419     if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
13420       return;
13421   if (FunctionScopeInfo *FD = S.getCurFunction())
13422     if (!FD->ModifiedNonNullParams.count(Param))
13423       FD->ModifiedNonNullParams.insert(Param);
13424 }
13425 
13426 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
13427 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
13428                                         SourceLocation OpLoc) {
13429   if (Op->isTypeDependent())
13430     return S.Context.DependentTy;
13431 
13432   ExprResult ConvResult = S.UsualUnaryConversions(Op);
13433   if (ConvResult.isInvalid())
13434     return QualType();
13435   Op = ConvResult.get();
13436   QualType OpTy = Op->getType();
13437   QualType Result;
13438 
13439   if (isa<CXXReinterpretCastExpr>(Op)) {
13440     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
13441     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
13442                                      Op->getSourceRange());
13443   }
13444 
13445   if (const PointerType *PT = OpTy->getAs<PointerType>())
13446   {
13447     Result = PT->getPointeeType();
13448   }
13449   else if (const ObjCObjectPointerType *OPT =
13450              OpTy->getAs<ObjCObjectPointerType>())
13451     Result = OPT->getPointeeType();
13452   else {
13453     ExprResult PR = S.CheckPlaceholderExpr(Op);
13454     if (PR.isInvalid()) return QualType();
13455     if (PR.get() != Op)
13456       return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
13457   }
13458 
13459   if (Result.isNull()) {
13460     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
13461       << OpTy << Op->getSourceRange();
13462     return QualType();
13463   }
13464 
13465   // Note that per both C89 and C99, indirection is always legal, even if Result
13466   // is an incomplete type or void.  It would be possible to warn about
13467   // dereferencing a void pointer, but it's completely well-defined, and such a
13468   // warning is unlikely to catch any mistakes. In C++, indirection is not valid
13469   // for pointers to 'void' but is fine for any other pointer type:
13470   //
13471   // C++ [expr.unary.op]p1:
13472   //   [...] the expression to which [the unary * operator] is applied shall
13473   //   be a pointer to an object type, or a pointer to a function type
13474   if (S.getLangOpts().CPlusPlus && Result->isVoidType())
13475     S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
13476       << OpTy << Op->getSourceRange();
13477 
13478   // Dereferences are usually l-values...
13479   VK = VK_LValue;
13480 
13481   // ...except that certain expressions are never l-values in C.
13482   if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
13483     VK = VK_RValue;
13484 
13485   return Result;
13486 }
13487 
13488 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
13489   BinaryOperatorKind Opc;
13490   switch (Kind) {
13491   default: llvm_unreachable("Unknown binop!");
13492   case tok::periodstar:           Opc = BO_PtrMemD; break;
13493   case tok::arrowstar:            Opc = BO_PtrMemI; break;
13494   case tok::star:                 Opc = BO_Mul; break;
13495   case tok::slash:                Opc = BO_Div; break;
13496   case tok::percent:              Opc = BO_Rem; break;
13497   case tok::plus:                 Opc = BO_Add; break;
13498   case tok::minus:                Opc = BO_Sub; break;
13499   case tok::lessless:             Opc = BO_Shl; break;
13500   case tok::greatergreater:       Opc = BO_Shr; break;
13501   case tok::lessequal:            Opc = BO_LE; break;
13502   case tok::less:                 Opc = BO_LT; break;
13503   case tok::greaterequal:         Opc = BO_GE; break;
13504   case tok::greater:              Opc = BO_GT; break;
13505   case tok::exclaimequal:         Opc = BO_NE; break;
13506   case tok::equalequal:           Opc = BO_EQ; break;
13507   case tok::spaceship:            Opc = BO_Cmp; break;
13508   case tok::amp:                  Opc = BO_And; break;
13509   case tok::caret:                Opc = BO_Xor; break;
13510   case tok::pipe:                 Opc = BO_Or; break;
13511   case tok::ampamp:               Opc = BO_LAnd; break;
13512   case tok::pipepipe:             Opc = BO_LOr; break;
13513   case tok::equal:                Opc = BO_Assign; break;
13514   case tok::starequal:            Opc = BO_MulAssign; break;
13515   case tok::slashequal:           Opc = BO_DivAssign; break;
13516   case tok::percentequal:         Opc = BO_RemAssign; break;
13517   case tok::plusequal:            Opc = BO_AddAssign; break;
13518   case tok::minusequal:           Opc = BO_SubAssign; break;
13519   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
13520   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
13521   case tok::ampequal:             Opc = BO_AndAssign; break;
13522   case tok::caretequal:           Opc = BO_XorAssign; break;
13523   case tok::pipeequal:            Opc = BO_OrAssign; break;
13524   case tok::comma:                Opc = BO_Comma; break;
13525   }
13526   return Opc;
13527 }
13528 
13529 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
13530   tok::TokenKind Kind) {
13531   UnaryOperatorKind Opc;
13532   switch (Kind) {
13533   default: llvm_unreachable("Unknown unary op!");
13534   case tok::plusplus:     Opc = UO_PreInc; break;
13535   case tok::minusminus:   Opc = UO_PreDec; break;
13536   case tok::amp:          Opc = UO_AddrOf; break;
13537   case tok::star:         Opc = UO_Deref; break;
13538   case tok::plus:         Opc = UO_Plus; break;
13539   case tok::minus:        Opc = UO_Minus; break;
13540   case tok::tilde:        Opc = UO_Not; break;
13541   case tok::exclaim:      Opc = UO_LNot; break;
13542   case tok::kw___real:    Opc = UO_Real; break;
13543   case tok::kw___imag:    Opc = UO_Imag; break;
13544   case tok::kw___extension__: Opc = UO_Extension; break;
13545   }
13546   return Opc;
13547 }
13548 
13549 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
13550 /// This warning suppressed in the event of macro expansions.
13551 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
13552                                    SourceLocation OpLoc, bool IsBuiltin) {
13553   if (S.inTemplateInstantiation())
13554     return;
13555   if (S.isUnevaluatedContext())
13556     return;
13557   if (OpLoc.isInvalid() || OpLoc.isMacroID())
13558     return;
13559   LHSExpr = LHSExpr->IgnoreParenImpCasts();
13560   RHSExpr = RHSExpr->IgnoreParenImpCasts();
13561   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
13562   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
13563   if (!LHSDeclRef || !RHSDeclRef ||
13564       LHSDeclRef->getLocation().isMacroID() ||
13565       RHSDeclRef->getLocation().isMacroID())
13566     return;
13567   const ValueDecl *LHSDecl =
13568     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
13569   const ValueDecl *RHSDecl =
13570     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
13571   if (LHSDecl != RHSDecl)
13572     return;
13573   if (LHSDecl->getType().isVolatileQualified())
13574     return;
13575   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
13576     if (RefTy->getPointeeType().isVolatileQualified())
13577       return;
13578 
13579   S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
13580                           : diag::warn_self_assignment_overloaded)
13581       << LHSDeclRef->getType() << LHSExpr->getSourceRange()
13582       << RHSExpr->getSourceRange();
13583 }
13584 
13585 /// Check if a bitwise-& is performed on an Objective-C pointer.  This
13586 /// is usually indicative of introspection within the Objective-C pointer.
13587 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
13588                                           SourceLocation OpLoc) {
13589   if (!S.getLangOpts().ObjC)
13590     return;
13591 
13592   const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
13593   const Expr *LHS = L.get();
13594   const Expr *RHS = R.get();
13595 
13596   if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
13597     ObjCPointerExpr = LHS;
13598     OtherExpr = RHS;
13599   }
13600   else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
13601     ObjCPointerExpr = RHS;
13602     OtherExpr = LHS;
13603   }
13604 
13605   // This warning is deliberately made very specific to reduce false
13606   // positives with logic that uses '&' for hashing.  This logic mainly
13607   // looks for code trying to introspect into tagged pointers, which
13608   // code should generally never do.
13609   if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
13610     unsigned Diag = diag::warn_objc_pointer_masking;
13611     // Determine if we are introspecting the result of performSelectorXXX.
13612     const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
13613     // Special case messages to -performSelector and friends, which
13614     // can return non-pointer values boxed in a pointer value.
13615     // Some clients may wish to silence warnings in this subcase.
13616     if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
13617       Selector S = ME->getSelector();
13618       StringRef SelArg0 = S.getNameForSlot(0);
13619       if (SelArg0.startswith("performSelector"))
13620         Diag = diag::warn_objc_pointer_masking_performSelector;
13621     }
13622 
13623     S.Diag(OpLoc, Diag)
13624       << ObjCPointerExpr->getSourceRange();
13625   }
13626 }
13627 
13628 static NamedDecl *getDeclFromExpr(Expr *E) {
13629   if (!E)
13630     return nullptr;
13631   if (auto *DRE = dyn_cast<DeclRefExpr>(E))
13632     return DRE->getDecl();
13633   if (auto *ME = dyn_cast<MemberExpr>(E))
13634     return ME->getMemberDecl();
13635   if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
13636     return IRE->getDecl();
13637   return nullptr;
13638 }
13639 
13640 // This helper function promotes a binary operator's operands (which are of a
13641 // half vector type) to a vector of floats and then truncates the result to
13642 // a vector of either half or short.
13643 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS,
13644                                       BinaryOperatorKind Opc, QualType ResultTy,
13645                                       ExprValueKind VK, ExprObjectKind OK,
13646                                       bool IsCompAssign, SourceLocation OpLoc,
13647                                       FPOptionsOverride FPFeatures) {
13648   auto &Context = S.getASTContext();
13649   assert((isVector(ResultTy, Context.HalfTy) ||
13650           isVector(ResultTy, Context.ShortTy)) &&
13651          "Result must be a vector of half or short");
13652   assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
13653          isVector(RHS.get()->getType(), Context.HalfTy) &&
13654          "both operands expected to be a half vector");
13655 
13656   RHS = convertVector(RHS.get(), Context.FloatTy, S);
13657   QualType BinOpResTy = RHS.get()->getType();
13658 
13659   // If Opc is a comparison, ResultType is a vector of shorts. In that case,
13660   // change BinOpResTy to a vector of ints.
13661   if (isVector(ResultTy, Context.ShortTy))
13662     BinOpResTy = S.GetSignedVectorType(BinOpResTy);
13663 
13664   if (IsCompAssign)
13665     return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc,
13666                                           ResultTy, VK, OK, OpLoc, FPFeatures,
13667                                           BinOpResTy, BinOpResTy);
13668 
13669   LHS = convertVector(LHS.get(), Context.FloatTy, S);
13670   auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc,
13671                                     BinOpResTy, VK, OK, OpLoc, FPFeatures);
13672   return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S);
13673 }
13674 
13675 static std::pair<ExprResult, ExprResult>
13676 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr,
13677                            Expr *RHSExpr) {
13678   ExprResult LHS = LHSExpr, RHS = RHSExpr;
13679   if (!S.getLangOpts().CPlusPlus) {
13680     // C cannot handle TypoExpr nodes on either side of a binop because it
13681     // doesn't handle dependent types properly, so make sure any TypoExprs have
13682     // been dealt with before checking the operands.
13683     LHS = S.CorrectDelayedTyposInExpr(LHS);
13684     RHS = S.CorrectDelayedTyposInExpr(
13685         RHS, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false,
13686         [Opc, LHS](Expr *E) {
13687           if (Opc != BO_Assign)
13688             return ExprResult(E);
13689           // Avoid correcting the RHS to the same Expr as the LHS.
13690           Decl *D = getDeclFromExpr(E);
13691           return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
13692         });
13693   }
13694   return std::make_pair(LHS, RHS);
13695 }
13696 
13697 /// Returns true if conversion between vectors of halfs and vectors of floats
13698 /// is needed.
13699 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
13700                                      Expr *E0, Expr *E1 = nullptr) {
13701   if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType ||
13702       Ctx.getTargetInfo().useFP16ConversionIntrinsics())
13703     return false;
13704 
13705   auto HasVectorOfHalfType = [&Ctx](Expr *E) {
13706     QualType Ty = E->IgnoreImplicit()->getType();
13707 
13708     // Don't promote half precision neon vectors like float16x4_t in arm_neon.h
13709     // to vectors of floats. Although the element type of the vectors is __fp16,
13710     // the vectors shouldn't be treated as storage-only types. See the
13711     // discussion here: https://reviews.llvm.org/rG825235c140e7
13712     if (const VectorType *VT = Ty->getAs<VectorType>()) {
13713       if (VT->getVectorKind() == VectorType::NeonVector)
13714         return false;
13715       return VT->getElementType().getCanonicalType() == Ctx.HalfTy;
13716     }
13717     return false;
13718   };
13719 
13720   return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1));
13721 }
13722 
13723 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
13724 /// operator @p Opc at location @c TokLoc. This routine only supports
13725 /// built-in operations; ActOnBinOp handles overloaded operators.
13726 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
13727                                     BinaryOperatorKind Opc,
13728                                     Expr *LHSExpr, Expr *RHSExpr) {
13729   if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
13730     // The syntax only allows initializer lists on the RHS of assignment,
13731     // so we don't need to worry about accepting invalid code for
13732     // non-assignment operators.
13733     // C++11 5.17p9:
13734     //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
13735     //   of x = {} is x = T().
13736     InitializationKind Kind = InitializationKind::CreateDirectList(
13737         RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
13738     InitializedEntity Entity =
13739         InitializedEntity::InitializeTemporary(LHSExpr->getType());
13740     InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
13741     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
13742     if (Init.isInvalid())
13743       return Init;
13744     RHSExpr = Init.get();
13745   }
13746 
13747   ExprResult LHS = LHSExpr, RHS = RHSExpr;
13748   QualType ResultTy;     // Result type of the binary operator.
13749   // The following two variables are used for compound assignment operators
13750   QualType CompLHSTy;    // Type of LHS after promotions for computation
13751   QualType CompResultTy; // Type of computation result
13752   ExprValueKind VK = VK_RValue;
13753   ExprObjectKind OK = OK_Ordinary;
13754   bool ConvertHalfVec = false;
13755 
13756   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
13757   if (!LHS.isUsable() || !RHS.isUsable())
13758     return ExprError();
13759 
13760   if (getLangOpts().OpenCL) {
13761     QualType LHSTy = LHSExpr->getType();
13762     QualType RHSTy = RHSExpr->getType();
13763     // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
13764     // the ATOMIC_VAR_INIT macro.
13765     if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
13766       SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
13767       if (BO_Assign == Opc)
13768         Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
13769       else
13770         ResultTy = InvalidOperands(OpLoc, LHS, RHS);
13771       return ExprError();
13772     }
13773 
13774     // OpenCL special types - image, sampler, pipe, and blocks are to be used
13775     // only with a builtin functions and therefore should be disallowed here.
13776     if (LHSTy->isImageType() || RHSTy->isImageType() ||
13777         LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
13778         LHSTy->isPipeType() || RHSTy->isPipeType() ||
13779         LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
13780       ResultTy = InvalidOperands(OpLoc, LHS, RHS);
13781       return ExprError();
13782     }
13783   }
13784 
13785   switch (Opc) {
13786   case BO_Assign:
13787     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
13788     if (getLangOpts().CPlusPlus &&
13789         LHS.get()->getObjectKind() != OK_ObjCProperty) {
13790       VK = LHS.get()->getValueKind();
13791       OK = LHS.get()->getObjectKind();
13792     }
13793     if (!ResultTy.isNull()) {
13794       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
13795       DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
13796 
13797       // Avoid copying a block to the heap if the block is assigned to a local
13798       // auto variable that is declared in the same scope as the block. This
13799       // optimization is unsafe if the local variable is declared in an outer
13800       // scope. For example:
13801       //
13802       // BlockTy b;
13803       // {
13804       //   b = ^{...};
13805       // }
13806       // // It is unsafe to invoke the block here if it wasn't copied to the
13807       // // heap.
13808       // b();
13809 
13810       if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens()))
13811         if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
13812           if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
13813             if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD))
13814               BE->getBlockDecl()->setCanAvoidCopyToHeap();
13815 
13816       if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion())
13817         checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(),
13818                               NTCUC_Assignment, NTCUK_Copy);
13819     }
13820     RecordModifiableNonNullParam(*this, LHS.get());
13821     break;
13822   case BO_PtrMemD:
13823   case BO_PtrMemI:
13824     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
13825                                             Opc == BO_PtrMemI);
13826     break;
13827   case BO_Mul:
13828   case BO_Div:
13829     ConvertHalfVec = true;
13830     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
13831                                            Opc == BO_Div);
13832     break;
13833   case BO_Rem:
13834     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
13835     break;
13836   case BO_Add:
13837     ConvertHalfVec = true;
13838     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
13839     break;
13840   case BO_Sub:
13841     ConvertHalfVec = true;
13842     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
13843     break;
13844   case BO_Shl:
13845   case BO_Shr:
13846     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
13847     break;
13848   case BO_LE:
13849   case BO_LT:
13850   case BO_GE:
13851   case BO_GT:
13852     ConvertHalfVec = true;
13853     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
13854     break;
13855   case BO_EQ:
13856   case BO_NE:
13857     ConvertHalfVec = true;
13858     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
13859     break;
13860   case BO_Cmp:
13861     ConvertHalfVec = true;
13862     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
13863     assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
13864     break;
13865   case BO_And:
13866     checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
13867     LLVM_FALLTHROUGH;
13868   case BO_Xor:
13869   case BO_Or:
13870     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
13871     break;
13872   case BO_LAnd:
13873   case BO_LOr:
13874     ConvertHalfVec = true;
13875     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
13876     break;
13877   case BO_MulAssign:
13878   case BO_DivAssign:
13879     ConvertHalfVec = true;
13880     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
13881                                                Opc == BO_DivAssign);
13882     CompLHSTy = CompResultTy;
13883     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13884       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13885     break;
13886   case BO_RemAssign:
13887     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
13888     CompLHSTy = CompResultTy;
13889     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13890       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13891     break;
13892   case BO_AddAssign:
13893     ConvertHalfVec = true;
13894     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
13895     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13896       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13897     break;
13898   case BO_SubAssign:
13899     ConvertHalfVec = true;
13900     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
13901     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13902       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13903     break;
13904   case BO_ShlAssign:
13905   case BO_ShrAssign:
13906     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
13907     CompLHSTy = CompResultTy;
13908     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13909       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13910     break;
13911   case BO_AndAssign:
13912   case BO_OrAssign: // fallthrough
13913     DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
13914     LLVM_FALLTHROUGH;
13915   case BO_XorAssign:
13916     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
13917     CompLHSTy = CompResultTy;
13918     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13919       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13920     break;
13921   case BO_Comma:
13922     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
13923     if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
13924       VK = RHS.get()->getValueKind();
13925       OK = RHS.get()->getObjectKind();
13926     }
13927     break;
13928   }
13929   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
13930     return ExprError();
13931 
13932   // Some of the binary operations require promoting operands of half vector to
13933   // float vectors and truncating the result back to half vector. For now, we do
13934   // this only when HalfArgsAndReturn is set (that is, when the target is arm or
13935   // arm64).
13936   assert(isVector(RHS.get()->getType(), Context.HalfTy) ==
13937          isVector(LHS.get()->getType(), Context.HalfTy) &&
13938          "both sides are half vectors or neither sides are");
13939   ConvertHalfVec =
13940       needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get());
13941 
13942   // Check for array bounds violations for both sides of the BinaryOperator
13943   CheckArrayAccess(LHS.get());
13944   CheckArrayAccess(RHS.get());
13945 
13946   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
13947     NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
13948                                                  &Context.Idents.get("object_setClass"),
13949                                                  SourceLocation(), LookupOrdinaryName);
13950     if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
13951       SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc());
13952       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign)
13953           << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(),
13954                                         "object_setClass(")
13955           << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc),
13956                                           ",")
13957           << FixItHint::CreateInsertion(RHSLocEnd, ")");
13958     }
13959     else
13960       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
13961   }
13962   else if (const ObjCIvarRefExpr *OIRE =
13963            dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
13964     DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
13965 
13966   // Opc is not a compound assignment if CompResultTy is null.
13967   if (CompResultTy.isNull()) {
13968     if (ConvertHalfVec)
13969       return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
13970                                  OpLoc, CurFPFeatureOverrides());
13971     return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy,
13972                                   VK, OK, OpLoc, CurFPFeatureOverrides());
13973   }
13974 
13975   // Handle compound assignments.
13976   if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
13977       OK_ObjCProperty) {
13978     VK = VK_LValue;
13979     OK = LHS.get()->getObjectKind();
13980   }
13981 
13982   // The LHS is not converted to the result type for fixed-point compound
13983   // assignment as the common type is computed on demand. Reset the CompLHSTy
13984   // to the LHS type we would have gotten after unary conversions.
13985   if (CompResultTy->isFixedPointType())
13986     CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType();
13987 
13988   if (ConvertHalfVec)
13989     return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
13990                                OpLoc, CurFPFeatureOverrides());
13991 
13992   return CompoundAssignOperator::Create(
13993       Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc,
13994       CurFPFeatureOverrides(), CompLHSTy, CompResultTy);
13995 }
13996 
13997 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
13998 /// operators are mixed in a way that suggests that the programmer forgot that
13999 /// comparison operators have higher precedence. The most typical example of
14000 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
14001 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
14002                                       SourceLocation OpLoc, Expr *LHSExpr,
14003                                       Expr *RHSExpr) {
14004   BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
14005   BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
14006 
14007   // Check that one of the sides is a comparison operator and the other isn't.
14008   bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
14009   bool isRightComp = RHSBO && RHSBO->isComparisonOp();
14010   if (isLeftComp == isRightComp)
14011     return;
14012 
14013   // Bitwise operations are sometimes used as eager logical ops.
14014   // Don't diagnose this.
14015   bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
14016   bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
14017   if (isLeftBitwise || isRightBitwise)
14018     return;
14019 
14020   SourceRange DiagRange = isLeftComp
14021                               ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
14022                               : SourceRange(OpLoc, RHSExpr->getEndLoc());
14023   StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
14024   SourceRange ParensRange =
14025       isLeftComp
14026           ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
14027           : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
14028 
14029   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
14030     << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
14031   SuggestParentheses(Self, OpLoc,
14032     Self.PDiag(diag::note_precedence_silence) << OpStr,
14033     (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
14034   SuggestParentheses(Self, OpLoc,
14035     Self.PDiag(diag::note_precedence_bitwise_first)
14036       << BinaryOperator::getOpcodeStr(Opc),
14037     ParensRange);
14038 }
14039 
14040 /// It accepts a '&&' expr that is inside a '||' one.
14041 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
14042 /// in parentheses.
14043 static void
14044 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
14045                                        BinaryOperator *Bop) {
14046   assert(Bop->getOpcode() == BO_LAnd);
14047   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
14048       << Bop->getSourceRange() << OpLoc;
14049   SuggestParentheses(Self, Bop->getOperatorLoc(),
14050     Self.PDiag(diag::note_precedence_silence)
14051       << Bop->getOpcodeStr(),
14052     Bop->getSourceRange());
14053 }
14054 
14055 /// Returns true if the given expression can be evaluated as a constant
14056 /// 'true'.
14057 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
14058   bool Res;
14059   return !E->isValueDependent() &&
14060          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
14061 }
14062 
14063 /// Returns true if the given expression can be evaluated as a constant
14064 /// 'false'.
14065 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
14066   bool Res;
14067   return !E->isValueDependent() &&
14068          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
14069 }
14070 
14071 /// Look for '&&' in the left hand of a '||' expr.
14072 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
14073                                              Expr *LHSExpr, Expr *RHSExpr) {
14074   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
14075     if (Bop->getOpcode() == BO_LAnd) {
14076       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
14077       if (EvaluatesAsFalse(S, RHSExpr))
14078         return;
14079       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
14080       if (!EvaluatesAsTrue(S, Bop->getLHS()))
14081         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
14082     } else if (Bop->getOpcode() == BO_LOr) {
14083       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
14084         // If it's "a || b && 1 || c" we didn't warn earlier for
14085         // "a || b && 1", but warn now.
14086         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
14087           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
14088       }
14089     }
14090   }
14091 }
14092 
14093 /// Look for '&&' in the right hand of a '||' expr.
14094 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
14095                                              Expr *LHSExpr, Expr *RHSExpr) {
14096   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
14097     if (Bop->getOpcode() == BO_LAnd) {
14098       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
14099       if (EvaluatesAsFalse(S, LHSExpr))
14100         return;
14101       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
14102       if (!EvaluatesAsTrue(S, Bop->getRHS()))
14103         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
14104     }
14105   }
14106 }
14107 
14108 /// Look for bitwise op in the left or right hand of a bitwise op with
14109 /// lower precedence and emit a diagnostic together with a fixit hint that wraps
14110 /// the '&' expression in parentheses.
14111 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
14112                                          SourceLocation OpLoc, Expr *SubExpr) {
14113   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
14114     if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
14115       S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
14116         << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
14117         << Bop->getSourceRange() << OpLoc;
14118       SuggestParentheses(S, Bop->getOperatorLoc(),
14119         S.PDiag(diag::note_precedence_silence)
14120           << Bop->getOpcodeStr(),
14121         Bop->getSourceRange());
14122     }
14123   }
14124 }
14125 
14126 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
14127                                     Expr *SubExpr, StringRef Shift) {
14128   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
14129     if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
14130       StringRef Op = Bop->getOpcodeStr();
14131       S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
14132           << Bop->getSourceRange() << OpLoc << Shift << Op;
14133       SuggestParentheses(S, Bop->getOperatorLoc(),
14134           S.PDiag(diag::note_precedence_silence) << Op,
14135           Bop->getSourceRange());
14136     }
14137   }
14138 }
14139 
14140 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
14141                                  Expr *LHSExpr, Expr *RHSExpr) {
14142   CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
14143   if (!OCE)
14144     return;
14145 
14146   FunctionDecl *FD = OCE->getDirectCallee();
14147   if (!FD || !FD->isOverloadedOperator())
14148     return;
14149 
14150   OverloadedOperatorKind Kind = FD->getOverloadedOperator();
14151   if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
14152     return;
14153 
14154   S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
14155       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
14156       << (Kind == OO_LessLess);
14157   SuggestParentheses(S, OCE->getOperatorLoc(),
14158                      S.PDiag(diag::note_precedence_silence)
14159                          << (Kind == OO_LessLess ? "<<" : ">>"),
14160                      OCE->getSourceRange());
14161   SuggestParentheses(
14162       S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first),
14163       SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc()));
14164 }
14165 
14166 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
14167 /// precedence.
14168 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
14169                                     SourceLocation OpLoc, Expr *LHSExpr,
14170                                     Expr *RHSExpr){
14171   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
14172   if (BinaryOperator::isBitwiseOp(Opc))
14173     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
14174 
14175   // Diagnose "arg1 & arg2 | arg3"
14176   if ((Opc == BO_Or || Opc == BO_Xor) &&
14177       !OpLoc.isMacroID()/* Don't warn in macros. */) {
14178     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
14179     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
14180   }
14181 
14182   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
14183   // We don't warn for 'assert(a || b && "bad")' since this is safe.
14184   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
14185     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
14186     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
14187   }
14188 
14189   if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
14190       || Opc == BO_Shr) {
14191     StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
14192     DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
14193     DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
14194   }
14195 
14196   // Warn on overloaded shift operators and comparisons, such as:
14197   // cout << 5 == 4;
14198   if (BinaryOperator::isComparisonOp(Opc))
14199     DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
14200 }
14201 
14202 // Binary Operators.  'Tok' is the token for the operator.
14203 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
14204                             tok::TokenKind Kind,
14205                             Expr *LHSExpr, Expr *RHSExpr) {
14206   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
14207   assert(LHSExpr && "ActOnBinOp(): missing left expression");
14208   assert(RHSExpr && "ActOnBinOp(): missing right expression");
14209 
14210   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
14211   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
14212 
14213   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
14214 }
14215 
14216 void Sema::LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc,
14217                        UnresolvedSetImpl &Functions) {
14218   OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
14219   if (OverOp != OO_None && OverOp != OO_Equal)
14220     LookupOverloadedOperatorName(OverOp, S, Functions);
14221 
14222   // In C++20 onwards, we may have a second operator to look up.
14223   if (getLangOpts().CPlusPlus20) {
14224     if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp))
14225       LookupOverloadedOperatorName(ExtraOp, S, Functions);
14226   }
14227 }
14228 
14229 /// Build an overloaded binary operator expression in the given scope.
14230 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
14231                                        BinaryOperatorKind Opc,
14232                                        Expr *LHS, Expr *RHS) {
14233   switch (Opc) {
14234   case BO_Assign:
14235   case BO_DivAssign:
14236   case BO_RemAssign:
14237   case BO_SubAssign:
14238   case BO_AndAssign:
14239   case BO_OrAssign:
14240   case BO_XorAssign:
14241     DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
14242     CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
14243     break;
14244   default:
14245     break;
14246   }
14247 
14248   // Find all of the overloaded operators visible from this point.
14249   UnresolvedSet<16> Functions;
14250   S.LookupBinOp(Sc, OpLoc, Opc, Functions);
14251 
14252   // Build the (potentially-overloaded, potentially-dependent)
14253   // binary operation.
14254   return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
14255 }
14256 
14257 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
14258                             BinaryOperatorKind Opc,
14259                             Expr *LHSExpr, Expr *RHSExpr) {
14260   ExprResult LHS, RHS;
14261   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
14262   if (!LHS.isUsable() || !RHS.isUsable())
14263     return ExprError();
14264   LHSExpr = LHS.get();
14265   RHSExpr = RHS.get();
14266 
14267   // We want to end up calling one of checkPseudoObjectAssignment
14268   // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
14269   // both expressions are overloadable or either is type-dependent),
14270   // or CreateBuiltinBinOp (in any other case).  We also want to get
14271   // any placeholder types out of the way.
14272 
14273   // Handle pseudo-objects in the LHS.
14274   if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
14275     // Assignments with a pseudo-object l-value need special analysis.
14276     if (pty->getKind() == BuiltinType::PseudoObject &&
14277         BinaryOperator::isAssignmentOp(Opc))
14278       return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
14279 
14280     // Don't resolve overloads if the other type is overloadable.
14281     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
14282       // We can't actually test that if we still have a placeholder,
14283       // though.  Fortunately, none of the exceptions we see in that
14284       // code below are valid when the LHS is an overload set.  Note
14285       // that an overload set can be dependently-typed, but it never
14286       // instantiates to having an overloadable type.
14287       ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
14288       if (resolvedRHS.isInvalid()) return ExprError();
14289       RHSExpr = resolvedRHS.get();
14290 
14291       if (RHSExpr->isTypeDependent() ||
14292           RHSExpr->getType()->isOverloadableType())
14293         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14294     }
14295 
14296     // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
14297     // template, diagnose the missing 'template' keyword instead of diagnosing
14298     // an invalid use of a bound member function.
14299     //
14300     // Note that "A::x < b" might be valid if 'b' has an overloadable type due
14301     // to C++1z [over.over]/1.4, but we already checked for that case above.
14302     if (Opc == BO_LT && inTemplateInstantiation() &&
14303         (pty->getKind() == BuiltinType::BoundMember ||
14304          pty->getKind() == BuiltinType::Overload)) {
14305       auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
14306       if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
14307           std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) {
14308             return isa<FunctionTemplateDecl>(ND);
14309           })) {
14310         Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
14311                                 : OE->getNameLoc(),
14312              diag::err_template_kw_missing)
14313           << OE->getName().getAsString() << "";
14314         return ExprError();
14315       }
14316     }
14317 
14318     ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
14319     if (LHS.isInvalid()) return ExprError();
14320     LHSExpr = LHS.get();
14321   }
14322 
14323   // Handle pseudo-objects in the RHS.
14324   if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
14325     // An overload in the RHS can potentially be resolved by the type
14326     // being assigned to.
14327     if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
14328       if (getLangOpts().CPlusPlus &&
14329           (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
14330            LHSExpr->getType()->isOverloadableType()))
14331         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14332 
14333       return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
14334     }
14335 
14336     // Don't resolve overloads if the other type is overloadable.
14337     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
14338         LHSExpr->getType()->isOverloadableType())
14339       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14340 
14341     ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
14342     if (!resolvedRHS.isUsable()) return ExprError();
14343     RHSExpr = resolvedRHS.get();
14344   }
14345 
14346   if (getLangOpts().CPlusPlus) {
14347     // If either expression is type-dependent, always build an
14348     // overloaded op.
14349     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
14350       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14351 
14352     // Otherwise, build an overloaded op if either expression has an
14353     // overloadable type.
14354     if (LHSExpr->getType()->isOverloadableType() ||
14355         RHSExpr->getType()->isOverloadableType())
14356       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14357   }
14358 
14359   // Build a built-in binary operation.
14360   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
14361 }
14362 
14363 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
14364   if (T.isNull() || T->isDependentType())
14365     return false;
14366 
14367   if (!T->isPromotableIntegerType())
14368     return true;
14369 
14370   return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
14371 }
14372 
14373 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
14374                                       UnaryOperatorKind Opc,
14375                                       Expr *InputExpr) {
14376   ExprResult Input = InputExpr;
14377   ExprValueKind VK = VK_RValue;
14378   ExprObjectKind OK = OK_Ordinary;
14379   QualType resultType;
14380   bool CanOverflow = false;
14381 
14382   bool ConvertHalfVec = false;
14383   if (getLangOpts().OpenCL) {
14384     QualType Ty = InputExpr->getType();
14385     // The only legal unary operation for atomics is '&'.
14386     if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
14387     // OpenCL special types - image, sampler, pipe, and blocks are to be used
14388     // only with a builtin functions and therefore should be disallowed here.
14389         (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
14390         || Ty->isBlockPointerType())) {
14391       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14392                        << InputExpr->getType()
14393                        << Input.get()->getSourceRange());
14394     }
14395   }
14396 
14397   switch (Opc) {
14398   case UO_PreInc:
14399   case UO_PreDec:
14400   case UO_PostInc:
14401   case UO_PostDec:
14402     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
14403                                                 OpLoc,
14404                                                 Opc == UO_PreInc ||
14405                                                 Opc == UO_PostInc,
14406                                                 Opc == UO_PreInc ||
14407                                                 Opc == UO_PreDec);
14408     CanOverflow = isOverflowingIntegerType(Context, resultType);
14409     break;
14410   case UO_AddrOf:
14411     resultType = CheckAddressOfOperand(Input, OpLoc);
14412     CheckAddressOfNoDeref(InputExpr);
14413     RecordModifiableNonNullParam(*this, InputExpr);
14414     break;
14415   case UO_Deref: {
14416     Input = DefaultFunctionArrayLvalueConversion(Input.get());
14417     if (Input.isInvalid()) return ExprError();
14418     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
14419     break;
14420   }
14421   case UO_Plus:
14422   case UO_Minus:
14423     CanOverflow = Opc == UO_Minus &&
14424                   isOverflowingIntegerType(Context, Input.get()->getType());
14425     Input = UsualUnaryConversions(Input.get());
14426     if (Input.isInvalid()) return ExprError();
14427     // Unary plus and minus require promoting an operand of half vector to a
14428     // float vector and truncating the result back to a half vector. For now, we
14429     // do this only when HalfArgsAndReturns is set (that is, when the target is
14430     // arm or arm64).
14431     ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get());
14432 
14433     // If the operand is a half vector, promote it to a float vector.
14434     if (ConvertHalfVec)
14435       Input = convertVector(Input.get(), Context.FloatTy, *this);
14436     resultType = Input.get()->getType();
14437     if (resultType->isDependentType())
14438       break;
14439     if (resultType->isArithmeticType()) // C99 6.5.3.3p1
14440       break;
14441     else if (resultType->isVectorType() &&
14442              // The z vector extensions don't allow + or - with bool vectors.
14443              (!Context.getLangOpts().ZVector ||
14444               resultType->castAs<VectorType>()->getVectorKind() !=
14445               VectorType::AltiVecBool))
14446       break;
14447     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
14448              Opc == UO_Plus &&
14449              resultType->isPointerType())
14450       break;
14451 
14452     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14453       << resultType << Input.get()->getSourceRange());
14454 
14455   case UO_Not: // bitwise complement
14456     Input = UsualUnaryConversions(Input.get());
14457     if (Input.isInvalid())
14458       return ExprError();
14459     resultType = Input.get()->getType();
14460     if (resultType->isDependentType())
14461       break;
14462     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
14463     if (resultType->isComplexType() || resultType->isComplexIntegerType())
14464       // C99 does not support '~' for complex conjugation.
14465       Diag(OpLoc, diag::ext_integer_complement_complex)
14466           << resultType << Input.get()->getSourceRange();
14467     else if (resultType->hasIntegerRepresentation())
14468       break;
14469     else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
14470       // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
14471       // on vector float types.
14472       QualType T = resultType->castAs<ExtVectorType>()->getElementType();
14473       if (!T->isIntegerType())
14474         return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14475                           << resultType << Input.get()->getSourceRange());
14476     } else {
14477       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14478                        << resultType << Input.get()->getSourceRange());
14479     }
14480     break;
14481 
14482   case UO_LNot: // logical negation
14483     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
14484     Input = DefaultFunctionArrayLvalueConversion(Input.get());
14485     if (Input.isInvalid()) return ExprError();
14486     resultType = Input.get()->getType();
14487 
14488     // Though we still have to promote half FP to float...
14489     if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
14490       Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
14491       resultType = Context.FloatTy;
14492     }
14493 
14494     if (resultType->isDependentType())
14495       break;
14496     if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
14497       // C99 6.5.3.3p1: ok, fallthrough;
14498       if (Context.getLangOpts().CPlusPlus) {
14499         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
14500         // operand contextually converted to bool.
14501         Input = ImpCastExprToType(Input.get(), Context.BoolTy,
14502                                   ScalarTypeToBooleanCastKind(resultType));
14503       } else if (Context.getLangOpts().OpenCL &&
14504                  Context.getLangOpts().OpenCLVersion < 120) {
14505         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
14506         // operate on scalar float types.
14507         if (!resultType->isIntegerType() && !resultType->isPointerType())
14508           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14509                            << resultType << Input.get()->getSourceRange());
14510       }
14511     } else if (resultType->isExtVectorType()) {
14512       if (Context.getLangOpts().OpenCL &&
14513           Context.getLangOpts().OpenCLVersion < 120 &&
14514           !Context.getLangOpts().OpenCLCPlusPlus) {
14515         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
14516         // operate on vector float types.
14517         QualType T = resultType->castAs<ExtVectorType>()->getElementType();
14518         if (!T->isIntegerType())
14519           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14520                            << resultType << Input.get()->getSourceRange());
14521       }
14522       // Vector logical not returns the signed variant of the operand type.
14523       resultType = GetSignedVectorType(resultType);
14524       break;
14525     } else if (Context.getLangOpts().CPlusPlus && resultType->isVectorType()) {
14526       const VectorType *VTy = resultType->castAs<VectorType>();
14527       if (VTy->getVectorKind() != VectorType::GenericVector)
14528         return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14529                          << resultType << Input.get()->getSourceRange());
14530 
14531       // Vector logical not returns the signed variant of the operand type.
14532       resultType = GetSignedVectorType(resultType);
14533       break;
14534     } else {
14535       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14536         << resultType << Input.get()->getSourceRange());
14537     }
14538 
14539     // LNot always has type int. C99 6.5.3.3p5.
14540     // In C++, it's bool. C++ 5.3.1p8
14541     resultType = Context.getLogicalOperationType();
14542     break;
14543   case UO_Real:
14544   case UO_Imag:
14545     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
14546     // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
14547     // complex l-values to ordinary l-values and all other values to r-values.
14548     if (Input.isInvalid()) return ExprError();
14549     if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
14550       if (Input.get()->getValueKind() != VK_RValue &&
14551           Input.get()->getObjectKind() == OK_Ordinary)
14552         VK = Input.get()->getValueKind();
14553     } else if (!getLangOpts().CPlusPlus) {
14554       // In C, a volatile scalar is read by __imag. In C++, it is not.
14555       Input = DefaultLvalueConversion(Input.get());
14556     }
14557     break;
14558   case UO_Extension:
14559     resultType = Input.get()->getType();
14560     VK = Input.get()->getValueKind();
14561     OK = Input.get()->getObjectKind();
14562     break;
14563   case UO_Coawait:
14564     // It's unnecessary to represent the pass-through operator co_await in the
14565     // AST; just return the input expression instead.
14566     assert(!Input.get()->getType()->isDependentType() &&
14567                    "the co_await expression must be non-dependant before "
14568                    "building operator co_await");
14569     return Input;
14570   }
14571   if (resultType.isNull() || Input.isInvalid())
14572     return ExprError();
14573 
14574   // Check for array bounds violations in the operand of the UnaryOperator,
14575   // except for the '*' and '&' operators that have to be handled specially
14576   // by CheckArrayAccess (as there are special cases like &array[arraysize]
14577   // that are explicitly defined as valid by the standard).
14578   if (Opc != UO_AddrOf && Opc != UO_Deref)
14579     CheckArrayAccess(Input.get());
14580 
14581   auto *UO =
14582       UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK,
14583                             OpLoc, CanOverflow, CurFPFeatureOverrides());
14584 
14585   if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) &&
14586       !isa<ArrayType>(UO->getType().getDesugaredType(Context)))
14587     ExprEvalContexts.back().PossibleDerefs.insert(UO);
14588 
14589   // Convert the result back to a half vector.
14590   if (ConvertHalfVec)
14591     return convertVector(UO, Context.HalfTy, *this);
14592   return UO;
14593 }
14594 
14595 /// Determine whether the given expression is a qualified member
14596 /// access expression, of a form that could be turned into a pointer to member
14597 /// with the address-of operator.
14598 bool Sema::isQualifiedMemberAccess(Expr *E) {
14599   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
14600     if (!DRE->getQualifier())
14601       return false;
14602 
14603     ValueDecl *VD = DRE->getDecl();
14604     if (!VD->isCXXClassMember())
14605       return false;
14606 
14607     if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
14608       return true;
14609     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
14610       return Method->isInstance();
14611 
14612     return false;
14613   }
14614 
14615   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
14616     if (!ULE->getQualifier())
14617       return false;
14618 
14619     for (NamedDecl *D : ULE->decls()) {
14620       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
14621         if (Method->isInstance())
14622           return true;
14623       } else {
14624         // Overload set does not contain methods.
14625         break;
14626       }
14627     }
14628 
14629     return false;
14630   }
14631 
14632   return false;
14633 }
14634 
14635 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
14636                               UnaryOperatorKind Opc, Expr *Input) {
14637   // First things first: handle placeholders so that the
14638   // overloaded-operator check considers the right type.
14639   if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
14640     // Increment and decrement of pseudo-object references.
14641     if (pty->getKind() == BuiltinType::PseudoObject &&
14642         UnaryOperator::isIncrementDecrementOp(Opc))
14643       return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
14644 
14645     // extension is always a builtin operator.
14646     if (Opc == UO_Extension)
14647       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
14648 
14649     // & gets special logic for several kinds of placeholder.
14650     // The builtin code knows what to do.
14651     if (Opc == UO_AddrOf &&
14652         (pty->getKind() == BuiltinType::Overload ||
14653          pty->getKind() == BuiltinType::UnknownAny ||
14654          pty->getKind() == BuiltinType::BoundMember))
14655       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
14656 
14657     // Anything else needs to be handled now.
14658     ExprResult Result = CheckPlaceholderExpr(Input);
14659     if (Result.isInvalid()) return ExprError();
14660     Input = Result.get();
14661   }
14662 
14663   if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
14664       UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
14665       !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
14666     // Find all of the overloaded operators visible from this point.
14667     UnresolvedSet<16> Functions;
14668     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
14669     if (S && OverOp != OO_None)
14670       LookupOverloadedOperatorName(OverOp, S, Functions);
14671 
14672     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
14673   }
14674 
14675   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
14676 }
14677 
14678 // Unary Operators.  'Tok' is the token for the operator.
14679 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
14680                               tok::TokenKind Op, Expr *Input) {
14681   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
14682 }
14683 
14684 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
14685 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
14686                                 LabelDecl *TheDecl) {
14687   TheDecl->markUsed(Context);
14688   // Create the AST node.  The address of a label always has type 'void*'.
14689   return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
14690                                      Context.getPointerType(Context.VoidTy));
14691 }
14692 
14693 void Sema::ActOnStartStmtExpr() {
14694   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
14695 }
14696 
14697 void Sema::ActOnStmtExprError() {
14698   // Note that function is also called by TreeTransform when leaving a
14699   // StmtExpr scope without rebuilding anything.
14700 
14701   DiscardCleanupsInEvaluationContext();
14702   PopExpressionEvaluationContext();
14703 }
14704 
14705 ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt,
14706                                SourceLocation RPLoc) {
14707   return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S));
14708 }
14709 
14710 ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
14711                                SourceLocation RPLoc, unsigned TemplateDepth) {
14712   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
14713   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
14714 
14715   if (hasAnyUnrecoverableErrorsInThisFunction())
14716     DiscardCleanupsInEvaluationContext();
14717   assert(!Cleanup.exprNeedsCleanups() &&
14718          "cleanups within StmtExpr not correctly bound!");
14719   PopExpressionEvaluationContext();
14720 
14721   // FIXME: there are a variety of strange constraints to enforce here, for
14722   // example, it is not possible to goto into a stmt expression apparently.
14723   // More semantic analysis is needed.
14724 
14725   // If there are sub-stmts in the compound stmt, take the type of the last one
14726   // as the type of the stmtexpr.
14727   QualType Ty = Context.VoidTy;
14728   bool StmtExprMayBindToTemp = false;
14729   if (!Compound->body_empty()) {
14730     // For GCC compatibility we get the last Stmt excluding trailing NullStmts.
14731     if (const auto *LastStmt =
14732             dyn_cast<ValueStmt>(Compound->getStmtExprResult())) {
14733       if (const Expr *Value = LastStmt->getExprStmt()) {
14734         StmtExprMayBindToTemp = true;
14735         Ty = Value->getType();
14736       }
14737     }
14738   }
14739 
14740   // FIXME: Check that expression type is complete/non-abstract; statement
14741   // expressions are not lvalues.
14742   Expr *ResStmtExpr =
14743       new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth);
14744   if (StmtExprMayBindToTemp)
14745     return MaybeBindToTemporary(ResStmtExpr);
14746   return ResStmtExpr;
14747 }
14748 
14749 ExprResult Sema::ActOnStmtExprResult(ExprResult ER) {
14750   if (ER.isInvalid())
14751     return ExprError();
14752 
14753   // Do function/array conversion on the last expression, but not
14754   // lvalue-to-rvalue.  However, initialize an unqualified type.
14755   ER = DefaultFunctionArrayConversion(ER.get());
14756   if (ER.isInvalid())
14757     return ExprError();
14758   Expr *E = ER.get();
14759 
14760   if (E->isTypeDependent())
14761     return E;
14762 
14763   // In ARC, if the final expression ends in a consume, splice
14764   // the consume out and bind it later.  In the alternate case
14765   // (when dealing with a retainable type), the result
14766   // initialization will create a produce.  In both cases the
14767   // result will be +1, and we'll need to balance that out with
14768   // a bind.
14769   auto *Cast = dyn_cast<ImplicitCastExpr>(E);
14770   if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
14771     return Cast->getSubExpr();
14772 
14773   // FIXME: Provide a better location for the initialization.
14774   return PerformCopyInitialization(
14775       InitializedEntity::InitializeStmtExprResult(
14776           E->getBeginLoc(), E->getType().getUnqualifiedType()),
14777       SourceLocation(), E);
14778 }
14779 
14780 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
14781                                       TypeSourceInfo *TInfo,
14782                                       ArrayRef<OffsetOfComponent> Components,
14783                                       SourceLocation RParenLoc) {
14784   QualType ArgTy = TInfo->getType();
14785   bool Dependent = ArgTy->isDependentType();
14786   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
14787 
14788   // We must have at least one component that refers to the type, and the first
14789   // one is known to be a field designator.  Verify that the ArgTy represents
14790   // a struct/union/class.
14791   if (!Dependent && !ArgTy->isRecordType())
14792     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
14793                        << ArgTy << TypeRange);
14794 
14795   // Type must be complete per C99 7.17p3 because a declaring a variable
14796   // with an incomplete type would be ill-formed.
14797   if (!Dependent
14798       && RequireCompleteType(BuiltinLoc, ArgTy,
14799                              diag::err_offsetof_incomplete_type, TypeRange))
14800     return ExprError();
14801 
14802   bool DidWarnAboutNonPOD = false;
14803   QualType CurrentType = ArgTy;
14804   SmallVector<OffsetOfNode, 4> Comps;
14805   SmallVector<Expr*, 4> Exprs;
14806   for (const OffsetOfComponent &OC : Components) {
14807     if (OC.isBrackets) {
14808       // Offset of an array sub-field.  TODO: Should we allow vector elements?
14809       if (!CurrentType->isDependentType()) {
14810         const ArrayType *AT = Context.getAsArrayType(CurrentType);
14811         if(!AT)
14812           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
14813                            << CurrentType);
14814         CurrentType = AT->getElementType();
14815       } else
14816         CurrentType = Context.DependentTy;
14817 
14818       ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
14819       if (IdxRval.isInvalid())
14820         return ExprError();
14821       Expr *Idx = IdxRval.get();
14822 
14823       // The expression must be an integral expression.
14824       // FIXME: An integral constant expression?
14825       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
14826           !Idx->getType()->isIntegerType())
14827         return ExprError(
14828             Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer)
14829             << Idx->getSourceRange());
14830 
14831       // Record this array index.
14832       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
14833       Exprs.push_back(Idx);
14834       continue;
14835     }
14836 
14837     // Offset of a field.
14838     if (CurrentType->isDependentType()) {
14839       // We have the offset of a field, but we can't look into the dependent
14840       // type. Just record the identifier of the field.
14841       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
14842       CurrentType = Context.DependentTy;
14843       continue;
14844     }
14845 
14846     // We need to have a complete type to look into.
14847     if (RequireCompleteType(OC.LocStart, CurrentType,
14848                             diag::err_offsetof_incomplete_type))
14849       return ExprError();
14850 
14851     // Look for the designated field.
14852     const RecordType *RC = CurrentType->getAs<RecordType>();
14853     if (!RC)
14854       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
14855                        << CurrentType);
14856     RecordDecl *RD = RC->getDecl();
14857 
14858     // C++ [lib.support.types]p5:
14859     //   The macro offsetof accepts a restricted set of type arguments in this
14860     //   International Standard. type shall be a POD structure or a POD union
14861     //   (clause 9).
14862     // C++11 [support.types]p4:
14863     //   If type is not a standard-layout class (Clause 9), the results are
14864     //   undefined.
14865     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
14866       bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
14867       unsigned DiagID =
14868         LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
14869                             : diag::ext_offsetof_non_pod_type;
14870 
14871       if (!IsSafe && !DidWarnAboutNonPOD &&
14872           DiagRuntimeBehavior(BuiltinLoc, nullptr,
14873                               PDiag(DiagID)
14874                               << SourceRange(Components[0].LocStart, OC.LocEnd)
14875                               << CurrentType))
14876         DidWarnAboutNonPOD = true;
14877     }
14878 
14879     // Look for the field.
14880     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
14881     LookupQualifiedName(R, RD);
14882     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
14883     IndirectFieldDecl *IndirectMemberDecl = nullptr;
14884     if (!MemberDecl) {
14885       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
14886         MemberDecl = IndirectMemberDecl->getAnonField();
14887     }
14888 
14889     if (!MemberDecl)
14890       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
14891                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
14892                                                               OC.LocEnd));
14893 
14894     // C99 7.17p3:
14895     //   (If the specified member is a bit-field, the behavior is undefined.)
14896     //
14897     // We diagnose this as an error.
14898     if (MemberDecl->isBitField()) {
14899       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
14900         << MemberDecl->getDeclName()
14901         << SourceRange(BuiltinLoc, RParenLoc);
14902       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
14903       return ExprError();
14904     }
14905 
14906     RecordDecl *Parent = MemberDecl->getParent();
14907     if (IndirectMemberDecl)
14908       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
14909 
14910     // If the member was found in a base class, introduce OffsetOfNodes for
14911     // the base class indirections.
14912     CXXBasePaths Paths;
14913     if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
14914                       Paths)) {
14915       if (Paths.getDetectedVirtual()) {
14916         Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
14917           << MemberDecl->getDeclName()
14918           << SourceRange(BuiltinLoc, RParenLoc);
14919         return ExprError();
14920       }
14921 
14922       CXXBasePath &Path = Paths.front();
14923       for (const CXXBasePathElement &B : Path)
14924         Comps.push_back(OffsetOfNode(B.Base));
14925     }
14926 
14927     if (IndirectMemberDecl) {
14928       for (auto *FI : IndirectMemberDecl->chain()) {
14929         assert(isa<FieldDecl>(FI));
14930         Comps.push_back(OffsetOfNode(OC.LocStart,
14931                                      cast<FieldDecl>(FI), OC.LocEnd));
14932       }
14933     } else
14934       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
14935 
14936     CurrentType = MemberDecl->getType().getNonReferenceType();
14937   }
14938 
14939   return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
14940                               Comps, Exprs, RParenLoc);
14941 }
14942 
14943 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
14944                                       SourceLocation BuiltinLoc,
14945                                       SourceLocation TypeLoc,
14946                                       ParsedType ParsedArgTy,
14947                                       ArrayRef<OffsetOfComponent> Components,
14948                                       SourceLocation RParenLoc) {
14949 
14950   TypeSourceInfo *ArgTInfo;
14951   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
14952   if (ArgTy.isNull())
14953     return ExprError();
14954 
14955   if (!ArgTInfo)
14956     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
14957 
14958   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
14959 }
14960 
14961 
14962 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
14963                                  Expr *CondExpr,
14964                                  Expr *LHSExpr, Expr *RHSExpr,
14965                                  SourceLocation RPLoc) {
14966   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
14967 
14968   ExprValueKind VK = VK_RValue;
14969   ExprObjectKind OK = OK_Ordinary;
14970   QualType resType;
14971   bool CondIsTrue = false;
14972   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
14973     resType = Context.DependentTy;
14974   } else {
14975     // The conditional expression is required to be a constant expression.
14976     llvm::APSInt condEval(32);
14977     ExprResult CondICE
14978       = VerifyIntegerConstantExpression(CondExpr, &condEval,
14979           diag::err_typecheck_choose_expr_requires_constant, false);
14980     if (CondICE.isInvalid())
14981       return ExprError();
14982     CondExpr = CondICE.get();
14983     CondIsTrue = condEval.getZExtValue();
14984 
14985     // If the condition is > zero, then the AST type is the same as the LHSExpr.
14986     Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
14987 
14988     resType = ActiveExpr->getType();
14989     VK = ActiveExpr->getValueKind();
14990     OK = ActiveExpr->getObjectKind();
14991   }
14992 
14993   return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
14994                                   resType, VK, OK, RPLoc, CondIsTrue);
14995 }
14996 
14997 //===----------------------------------------------------------------------===//
14998 // Clang Extensions.
14999 //===----------------------------------------------------------------------===//
15000 
15001 /// ActOnBlockStart - This callback is invoked when a block literal is started.
15002 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
15003   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
15004 
15005   if (LangOpts.CPlusPlus) {
15006     MangleNumberingContext *MCtx;
15007     Decl *ManglingContextDecl;
15008     std::tie(MCtx, ManglingContextDecl) =
15009         getCurrentMangleNumberContext(Block->getDeclContext());
15010     if (MCtx) {
15011       unsigned ManglingNumber = MCtx->getManglingNumber(Block);
15012       Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
15013     }
15014   }
15015 
15016   PushBlockScope(CurScope, Block);
15017   CurContext->addDecl(Block);
15018   if (CurScope)
15019     PushDeclContext(CurScope, Block);
15020   else
15021     CurContext = Block;
15022 
15023   getCurBlock()->HasImplicitReturnType = true;
15024 
15025   // Enter a new evaluation context to insulate the block from any
15026   // cleanups from the enclosing full-expression.
15027   PushExpressionEvaluationContext(
15028       ExpressionEvaluationContext::PotentiallyEvaluated);
15029 }
15030 
15031 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
15032                                Scope *CurScope) {
15033   assert(ParamInfo.getIdentifier() == nullptr &&
15034          "block-id should have no identifier!");
15035   assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteralContext);
15036   BlockScopeInfo *CurBlock = getCurBlock();
15037 
15038   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
15039   QualType T = Sig->getType();
15040 
15041   // FIXME: We should allow unexpanded parameter packs here, but that would,
15042   // in turn, make the block expression contain unexpanded parameter packs.
15043   if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
15044     // Drop the parameters.
15045     FunctionProtoType::ExtProtoInfo EPI;
15046     EPI.HasTrailingReturn = false;
15047     EPI.TypeQuals.addConst();
15048     T = Context.getFunctionType(Context.DependentTy, None, EPI);
15049     Sig = Context.getTrivialTypeSourceInfo(T);
15050   }
15051 
15052   // GetTypeForDeclarator always produces a function type for a block
15053   // literal signature.  Furthermore, it is always a FunctionProtoType
15054   // unless the function was written with a typedef.
15055   assert(T->isFunctionType() &&
15056          "GetTypeForDeclarator made a non-function block signature");
15057 
15058   // Look for an explicit signature in that function type.
15059   FunctionProtoTypeLoc ExplicitSignature;
15060 
15061   if ((ExplicitSignature = Sig->getTypeLoc()
15062                                .getAsAdjusted<FunctionProtoTypeLoc>())) {
15063 
15064     // Check whether that explicit signature was synthesized by
15065     // GetTypeForDeclarator.  If so, don't save that as part of the
15066     // written signature.
15067     if (ExplicitSignature.getLocalRangeBegin() ==
15068         ExplicitSignature.getLocalRangeEnd()) {
15069       // This would be much cheaper if we stored TypeLocs instead of
15070       // TypeSourceInfos.
15071       TypeLoc Result = ExplicitSignature.getReturnLoc();
15072       unsigned Size = Result.getFullDataSize();
15073       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
15074       Sig->getTypeLoc().initializeFullCopy(Result, Size);
15075 
15076       ExplicitSignature = FunctionProtoTypeLoc();
15077     }
15078   }
15079 
15080   CurBlock->TheDecl->setSignatureAsWritten(Sig);
15081   CurBlock->FunctionType = T;
15082 
15083   const FunctionType *Fn = T->getAs<FunctionType>();
15084   QualType RetTy = Fn->getReturnType();
15085   bool isVariadic =
15086     (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
15087 
15088   CurBlock->TheDecl->setIsVariadic(isVariadic);
15089 
15090   // Context.DependentTy is used as a placeholder for a missing block
15091   // return type.  TODO:  what should we do with declarators like:
15092   //   ^ * { ... }
15093   // If the answer is "apply template argument deduction"....
15094   if (RetTy != Context.DependentTy) {
15095     CurBlock->ReturnType = RetTy;
15096     CurBlock->TheDecl->setBlockMissingReturnType(false);
15097     CurBlock->HasImplicitReturnType = false;
15098   }
15099 
15100   // Push block parameters from the declarator if we had them.
15101   SmallVector<ParmVarDecl*, 8> Params;
15102   if (ExplicitSignature) {
15103     for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
15104       ParmVarDecl *Param = ExplicitSignature.getParam(I);
15105       if (Param->getIdentifier() == nullptr && !Param->isImplicit() &&
15106           !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) {
15107         // Diagnose this as an extension in C17 and earlier.
15108         if (!getLangOpts().C2x)
15109           Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x);
15110       }
15111       Params.push_back(Param);
15112     }
15113 
15114   // Fake up parameter variables if we have a typedef, like
15115   //   ^ fntype { ... }
15116   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
15117     for (const auto &I : Fn->param_types()) {
15118       ParmVarDecl *Param = BuildParmVarDeclForTypedef(
15119           CurBlock->TheDecl, ParamInfo.getBeginLoc(), I);
15120       Params.push_back(Param);
15121     }
15122   }
15123 
15124   // Set the parameters on the block decl.
15125   if (!Params.empty()) {
15126     CurBlock->TheDecl->setParams(Params);
15127     CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
15128                              /*CheckParameterNames=*/false);
15129   }
15130 
15131   // Finally we can process decl attributes.
15132   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
15133 
15134   // Put the parameter variables in scope.
15135   for (auto AI : CurBlock->TheDecl->parameters()) {
15136     AI->setOwningFunction(CurBlock->TheDecl);
15137 
15138     // If this has an identifier, add it to the scope stack.
15139     if (AI->getIdentifier()) {
15140       CheckShadow(CurBlock->TheScope, AI);
15141 
15142       PushOnScopeChains(AI, CurBlock->TheScope);
15143     }
15144   }
15145 }
15146 
15147 /// ActOnBlockError - If there is an error parsing a block, this callback
15148 /// is invoked to pop the information about the block from the action impl.
15149 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
15150   // Leave the expression-evaluation context.
15151   DiscardCleanupsInEvaluationContext();
15152   PopExpressionEvaluationContext();
15153 
15154   // Pop off CurBlock, handle nested blocks.
15155   PopDeclContext();
15156   PopFunctionScopeInfo();
15157 }
15158 
15159 /// ActOnBlockStmtExpr - This is called when the body of a block statement
15160 /// literal was successfully completed.  ^(int x){...}
15161 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
15162                                     Stmt *Body, Scope *CurScope) {
15163   // If blocks are disabled, emit an error.
15164   if (!LangOpts.Blocks)
15165     Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
15166 
15167   // Leave the expression-evaluation context.
15168   if (hasAnyUnrecoverableErrorsInThisFunction())
15169     DiscardCleanupsInEvaluationContext();
15170   assert(!Cleanup.exprNeedsCleanups() &&
15171          "cleanups within block not correctly bound!");
15172   PopExpressionEvaluationContext();
15173 
15174   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
15175   BlockDecl *BD = BSI->TheDecl;
15176 
15177   if (BSI->HasImplicitReturnType)
15178     deduceClosureReturnType(*BSI);
15179 
15180   QualType RetTy = Context.VoidTy;
15181   if (!BSI->ReturnType.isNull())
15182     RetTy = BSI->ReturnType;
15183 
15184   bool NoReturn = BD->hasAttr<NoReturnAttr>();
15185   QualType BlockTy;
15186 
15187   // If the user wrote a function type in some form, try to use that.
15188   if (!BSI->FunctionType.isNull()) {
15189     const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>();
15190 
15191     FunctionType::ExtInfo Ext = FTy->getExtInfo();
15192     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
15193 
15194     // Turn protoless block types into nullary block types.
15195     if (isa<FunctionNoProtoType>(FTy)) {
15196       FunctionProtoType::ExtProtoInfo EPI;
15197       EPI.ExtInfo = Ext;
15198       BlockTy = Context.getFunctionType(RetTy, None, EPI);
15199 
15200     // Otherwise, if we don't need to change anything about the function type,
15201     // preserve its sugar structure.
15202     } else if (FTy->getReturnType() == RetTy &&
15203                (!NoReturn || FTy->getNoReturnAttr())) {
15204       BlockTy = BSI->FunctionType;
15205 
15206     // Otherwise, make the minimal modifications to the function type.
15207     } else {
15208       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
15209       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
15210       EPI.TypeQuals = Qualifiers();
15211       EPI.ExtInfo = Ext;
15212       BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
15213     }
15214 
15215   // If we don't have a function type, just build one from nothing.
15216   } else {
15217     FunctionProtoType::ExtProtoInfo EPI;
15218     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
15219     BlockTy = Context.getFunctionType(RetTy, None, EPI);
15220   }
15221 
15222   DiagnoseUnusedParameters(BD->parameters());
15223   BlockTy = Context.getBlockPointerType(BlockTy);
15224 
15225   // If needed, diagnose invalid gotos and switches in the block.
15226   if (getCurFunction()->NeedsScopeChecking() &&
15227       !PP.isCodeCompletionEnabled())
15228     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
15229 
15230   BD->setBody(cast<CompoundStmt>(Body));
15231 
15232   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
15233     DiagnoseUnguardedAvailabilityViolations(BD);
15234 
15235   // Try to apply the named return value optimization. We have to check again
15236   // if we can do this, though, because blocks keep return statements around
15237   // to deduce an implicit return type.
15238   if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
15239       !BD->isDependentContext())
15240     computeNRVO(Body, BSI);
15241 
15242   if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() ||
15243       RetTy.hasNonTrivialToPrimitiveCopyCUnion())
15244     checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn,
15245                           NTCUK_Destruct|NTCUK_Copy);
15246 
15247   PopDeclContext();
15248 
15249   // Pop the block scope now but keep it alive to the end of this function.
15250   AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
15251   PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy);
15252 
15253   // Set the captured variables on the block.
15254   SmallVector<BlockDecl::Capture, 4> Captures;
15255   for (Capture &Cap : BSI->Captures) {
15256     if (Cap.isInvalid() || Cap.isThisCapture())
15257       continue;
15258 
15259     VarDecl *Var = Cap.getVariable();
15260     Expr *CopyExpr = nullptr;
15261     if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) {
15262       if (const RecordType *Record =
15263               Cap.getCaptureType()->getAs<RecordType>()) {
15264         // The capture logic needs the destructor, so make sure we mark it.
15265         // Usually this is unnecessary because most local variables have
15266         // their destructors marked at declaration time, but parameters are
15267         // an exception because it's technically only the call site that
15268         // actually requires the destructor.
15269         if (isa<ParmVarDecl>(Var))
15270           FinalizeVarWithDestructor(Var, Record);
15271 
15272         // Enter a separate potentially-evaluated context while building block
15273         // initializers to isolate their cleanups from those of the block
15274         // itself.
15275         // FIXME: Is this appropriate even when the block itself occurs in an
15276         // unevaluated operand?
15277         EnterExpressionEvaluationContext EvalContext(
15278             *this, ExpressionEvaluationContext::PotentiallyEvaluated);
15279 
15280         SourceLocation Loc = Cap.getLocation();
15281 
15282         ExprResult Result = BuildDeclarationNameExpr(
15283             CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
15284 
15285         // According to the blocks spec, the capture of a variable from
15286         // the stack requires a const copy constructor.  This is not true
15287         // of the copy/move done to move a __block variable to the heap.
15288         if (!Result.isInvalid() &&
15289             !Result.get()->getType().isConstQualified()) {
15290           Result = ImpCastExprToType(Result.get(),
15291                                      Result.get()->getType().withConst(),
15292                                      CK_NoOp, VK_LValue);
15293         }
15294 
15295         if (!Result.isInvalid()) {
15296           Result = PerformCopyInitialization(
15297               InitializedEntity::InitializeBlock(Var->getLocation(),
15298                                                  Cap.getCaptureType(), false),
15299               Loc, Result.get());
15300         }
15301 
15302         // Build a full-expression copy expression if initialization
15303         // succeeded and used a non-trivial constructor.  Recover from
15304         // errors by pretending that the copy isn't necessary.
15305         if (!Result.isInvalid() &&
15306             !cast<CXXConstructExpr>(Result.get())->getConstructor()
15307                 ->isTrivial()) {
15308           Result = MaybeCreateExprWithCleanups(Result);
15309           CopyExpr = Result.get();
15310         }
15311       }
15312     }
15313 
15314     BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(),
15315                               CopyExpr);
15316     Captures.push_back(NewCap);
15317   }
15318   BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
15319 
15320   BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy);
15321 
15322   // If the block isn't obviously global, i.e. it captures anything at
15323   // all, then we need to do a few things in the surrounding context:
15324   if (Result->getBlockDecl()->hasCaptures()) {
15325     // First, this expression has a new cleanup object.
15326     ExprCleanupObjects.push_back(Result->getBlockDecl());
15327     Cleanup.setExprNeedsCleanups(true);
15328 
15329     // It also gets a branch-protected scope if any of the captured
15330     // variables needs destruction.
15331     for (const auto &CI : Result->getBlockDecl()->captures()) {
15332       const VarDecl *var = CI.getVariable();
15333       if (var->getType().isDestructedType() != QualType::DK_none) {
15334         setFunctionHasBranchProtectedScope();
15335         break;
15336       }
15337     }
15338   }
15339 
15340   if (getCurFunction())
15341     getCurFunction()->addBlock(BD);
15342 
15343   return Result;
15344 }
15345 
15346 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
15347                             SourceLocation RPLoc) {
15348   TypeSourceInfo *TInfo;
15349   GetTypeFromParser(Ty, &TInfo);
15350   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
15351 }
15352 
15353 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
15354                                 Expr *E, TypeSourceInfo *TInfo,
15355                                 SourceLocation RPLoc) {
15356   Expr *OrigExpr = E;
15357   bool IsMS = false;
15358 
15359   // CUDA device code does not support varargs.
15360   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
15361     if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
15362       CUDAFunctionTarget T = IdentifyCUDATarget(F);
15363       if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
15364         return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device));
15365     }
15366   }
15367 
15368   // NVPTX does not support va_arg expression.
15369   if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
15370       Context.getTargetInfo().getTriple().isNVPTX())
15371     targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device);
15372 
15373   // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
15374   // as Microsoft ABI on an actual Microsoft platform, where
15375   // __builtin_ms_va_list and __builtin_va_list are the same.)
15376   if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
15377       Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
15378     QualType MSVaListType = Context.getBuiltinMSVaListType();
15379     if (Context.hasSameType(MSVaListType, E->getType())) {
15380       if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
15381         return ExprError();
15382       IsMS = true;
15383     }
15384   }
15385 
15386   // Get the va_list type
15387   QualType VaListType = Context.getBuiltinVaListType();
15388   if (!IsMS) {
15389     if (VaListType->isArrayType()) {
15390       // Deal with implicit array decay; for example, on x86-64,
15391       // va_list is an array, but it's supposed to decay to
15392       // a pointer for va_arg.
15393       VaListType = Context.getArrayDecayedType(VaListType);
15394       // Make sure the input expression also decays appropriately.
15395       ExprResult Result = UsualUnaryConversions(E);
15396       if (Result.isInvalid())
15397         return ExprError();
15398       E = Result.get();
15399     } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
15400       // If va_list is a record type and we are compiling in C++ mode,
15401       // check the argument using reference binding.
15402       InitializedEntity Entity = InitializedEntity::InitializeParameter(
15403           Context, Context.getLValueReferenceType(VaListType), false);
15404       ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
15405       if (Init.isInvalid())
15406         return ExprError();
15407       E = Init.getAs<Expr>();
15408     } else {
15409       // Otherwise, the va_list argument must be an l-value because
15410       // it is modified by va_arg.
15411       if (!E->isTypeDependent() &&
15412           CheckForModifiableLvalue(E, BuiltinLoc, *this))
15413         return ExprError();
15414     }
15415   }
15416 
15417   if (!IsMS && !E->isTypeDependent() &&
15418       !Context.hasSameType(VaListType, E->getType()))
15419     return ExprError(
15420         Diag(E->getBeginLoc(),
15421              diag::err_first_argument_to_va_arg_not_of_type_va_list)
15422         << OrigExpr->getType() << E->getSourceRange());
15423 
15424   if (!TInfo->getType()->isDependentType()) {
15425     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
15426                             diag::err_second_parameter_to_va_arg_incomplete,
15427                             TInfo->getTypeLoc()))
15428       return ExprError();
15429 
15430     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
15431                                TInfo->getType(),
15432                                diag::err_second_parameter_to_va_arg_abstract,
15433                                TInfo->getTypeLoc()))
15434       return ExprError();
15435 
15436     if (!TInfo->getType().isPODType(Context)) {
15437       Diag(TInfo->getTypeLoc().getBeginLoc(),
15438            TInfo->getType()->isObjCLifetimeType()
15439              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
15440              : diag::warn_second_parameter_to_va_arg_not_pod)
15441         << TInfo->getType()
15442         << TInfo->getTypeLoc().getSourceRange();
15443     }
15444 
15445     // Check for va_arg where arguments of the given type will be promoted
15446     // (i.e. this va_arg is guaranteed to have undefined behavior).
15447     QualType PromoteType;
15448     if (TInfo->getType()->isPromotableIntegerType()) {
15449       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
15450       if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
15451         PromoteType = QualType();
15452     }
15453     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
15454       PromoteType = Context.DoubleTy;
15455     if (!PromoteType.isNull())
15456       DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
15457                   PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
15458                           << TInfo->getType()
15459                           << PromoteType
15460                           << TInfo->getTypeLoc().getSourceRange());
15461   }
15462 
15463   QualType T = TInfo->getType().getNonLValueExprType(Context);
15464   return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
15465 }
15466 
15467 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
15468   // The type of __null will be int or long, depending on the size of
15469   // pointers on the target.
15470   QualType Ty;
15471   unsigned pw = Context.getTargetInfo().getPointerWidth(0);
15472   if (pw == Context.getTargetInfo().getIntWidth())
15473     Ty = Context.IntTy;
15474   else if (pw == Context.getTargetInfo().getLongWidth())
15475     Ty = Context.LongTy;
15476   else if (pw == Context.getTargetInfo().getLongLongWidth())
15477     Ty = Context.LongLongTy;
15478   else {
15479     llvm_unreachable("I don't know size of pointer!");
15480   }
15481 
15482   return new (Context) GNUNullExpr(Ty, TokenLoc);
15483 }
15484 
15485 ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind,
15486                                     SourceLocation BuiltinLoc,
15487                                     SourceLocation RPLoc) {
15488   return BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, CurContext);
15489 }
15490 
15491 ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind,
15492                                     SourceLocation BuiltinLoc,
15493                                     SourceLocation RPLoc,
15494                                     DeclContext *ParentContext) {
15495   return new (Context)
15496       SourceLocExpr(Context, Kind, BuiltinLoc, RPLoc, ParentContext);
15497 }
15498 
15499 bool Sema::CheckConversionToObjCLiteral(QualType DstType, Expr *&Exp,
15500                                         bool Diagnose) {
15501   if (!getLangOpts().ObjC)
15502     return false;
15503 
15504   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
15505   if (!PT)
15506     return false;
15507   const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
15508 
15509   // Ignore any parens, implicit casts (should only be
15510   // array-to-pointer decays), and not-so-opaque values.  The last is
15511   // important for making this trigger for property assignments.
15512   Expr *SrcExpr = Exp->IgnoreParenImpCasts();
15513   if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
15514     if (OV->getSourceExpr())
15515       SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
15516 
15517   if (auto *SL = dyn_cast<StringLiteral>(SrcExpr)) {
15518     if (!PT->isObjCIdType() &&
15519         !(ID && ID->getIdentifier()->isStr("NSString")))
15520       return false;
15521     if (!SL->isAscii())
15522       return false;
15523 
15524     if (Diagnose) {
15525       Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix)
15526           << /*string*/0 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@");
15527       Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get();
15528     }
15529     return true;
15530   }
15531 
15532   if ((isa<IntegerLiteral>(SrcExpr) || isa<CharacterLiteral>(SrcExpr) ||
15533       isa<FloatingLiteral>(SrcExpr) || isa<ObjCBoolLiteralExpr>(SrcExpr) ||
15534       isa<CXXBoolLiteralExpr>(SrcExpr)) &&
15535       !SrcExpr->isNullPointerConstant(
15536           getASTContext(), Expr::NPC_NeverValueDependent)) {
15537     if (!ID || !ID->getIdentifier()->isStr("NSNumber"))
15538       return false;
15539     if (Diagnose) {
15540       Diag(SrcExpr->getBeginLoc(), diag::err_missing_atsign_prefix)
15541           << /*number*/1
15542           << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(), "@");
15543       Expr *NumLit =
15544           BuildObjCNumericLiteral(SrcExpr->getBeginLoc(), SrcExpr).get();
15545       if (NumLit)
15546         Exp = NumLit;
15547     }
15548     return true;
15549   }
15550 
15551   return false;
15552 }
15553 
15554 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
15555                                               const Expr *SrcExpr) {
15556   if (!DstType->isFunctionPointerType() ||
15557       !SrcExpr->getType()->isFunctionType())
15558     return false;
15559 
15560   auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
15561   if (!DRE)
15562     return false;
15563 
15564   auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
15565   if (!FD)
15566     return false;
15567 
15568   return !S.checkAddressOfFunctionIsAvailable(FD,
15569                                               /*Complain=*/true,
15570                                               SrcExpr->getBeginLoc());
15571 }
15572 
15573 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
15574                                     SourceLocation Loc,
15575                                     QualType DstType, QualType SrcType,
15576                                     Expr *SrcExpr, AssignmentAction Action,
15577                                     bool *Complained) {
15578   if (Complained)
15579     *Complained = false;
15580 
15581   // Decode the result (notice that AST's are still created for extensions).
15582   bool CheckInferredResultType = false;
15583   bool isInvalid = false;
15584   unsigned DiagKind = 0;
15585   ConversionFixItGenerator ConvHints;
15586   bool MayHaveConvFixit = false;
15587   bool MayHaveFunctionDiff = false;
15588   const ObjCInterfaceDecl *IFace = nullptr;
15589   const ObjCProtocolDecl *PDecl = nullptr;
15590 
15591   switch (ConvTy) {
15592   case Compatible:
15593       DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
15594       return false;
15595 
15596   case PointerToInt:
15597     if (getLangOpts().CPlusPlus) {
15598       DiagKind = diag::err_typecheck_convert_pointer_int;
15599       isInvalid = true;
15600     } else {
15601       DiagKind = diag::ext_typecheck_convert_pointer_int;
15602     }
15603     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15604     MayHaveConvFixit = true;
15605     break;
15606   case IntToPointer:
15607     if (getLangOpts().CPlusPlus) {
15608       DiagKind = diag::err_typecheck_convert_int_pointer;
15609       isInvalid = true;
15610     } else {
15611       DiagKind = diag::ext_typecheck_convert_int_pointer;
15612     }
15613     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15614     MayHaveConvFixit = true;
15615     break;
15616   case IncompatibleFunctionPointer:
15617     if (getLangOpts().CPlusPlus) {
15618       DiagKind = diag::err_typecheck_convert_incompatible_function_pointer;
15619       isInvalid = true;
15620     } else {
15621       DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
15622     }
15623     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15624     MayHaveConvFixit = true;
15625     break;
15626   case IncompatiblePointer:
15627     if (Action == AA_Passing_CFAudited) {
15628       DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
15629     } else if (getLangOpts().CPlusPlus) {
15630       DiagKind = diag::err_typecheck_convert_incompatible_pointer;
15631       isInvalid = true;
15632     } else {
15633       DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
15634     }
15635     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
15636       SrcType->isObjCObjectPointerType();
15637     if (!CheckInferredResultType) {
15638       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15639     } else if (CheckInferredResultType) {
15640       SrcType = SrcType.getUnqualifiedType();
15641       DstType = DstType.getUnqualifiedType();
15642     }
15643     MayHaveConvFixit = true;
15644     break;
15645   case IncompatiblePointerSign:
15646     if (getLangOpts().CPlusPlus) {
15647       DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign;
15648       isInvalid = true;
15649     } else {
15650       DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
15651     }
15652     break;
15653   case FunctionVoidPointer:
15654     if (getLangOpts().CPlusPlus) {
15655       DiagKind = diag::err_typecheck_convert_pointer_void_func;
15656       isInvalid = true;
15657     } else {
15658       DiagKind = diag::ext_typecheck_convert_pointer_void_func;
15659     }
15660     break;
15661   case IncompatiblePointerDiscardsQualifiers: {
15662     // Perform array-to-pointer decay if necessary.
15663     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
15664 
15665     isInvalid = true;
15666 
15667     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
15668     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
15669     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
15670       DiagKind = diag::err_typecheck_incompatible_address_space;
15671       break;
15672 
15673     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
15674       DiagKind = diag::err_typecheck_incompatible_ownership;
15675       break;
15676     }
15677 
15678     llvm_unreachable("unknown error case for discarding qualifiers!");
15679     // fallthrough
15680   }
15681   case CompatiblePointerDiscardsQualifiers:
15682     // If the qualifiers lost were because we were applying the
15683     // (deprecated) C++ conversion from a string literal to a char*
15684     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
15685     // Ideally, this check would be performed in
15686     // checkPointerTypesForAssignment. However, that would require a
15687     // bit of refactoring (so that the second argument is an
15688     // expression, rather than a type), which should be done as part
15689     // of a larger effort to fix checkPointerTypesForAssignment for
15690     // C++ semantics.
15691     if (getLangOpts().CPlusPlus &&
15692         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
15693       return false;
15694     if (getLangOpts().CPlusPlus) {
15695       DiagKind =  diag::err_typecheck_convert_discards_qualifiers;
15696       isInvalid = true;
15697     } else {
15698       DiagKind =  diag::ext_typecheck_convert_discards_qualifiers;
15699     }
15700 
15701     break;
15702   case IncompatibleNestedPointerQualifiers:
15703     if (getLangOpts().CPlusPlus) {
15704       isInvalid = true;
15705       DiagKind = diag::err_nested_pointer_qualifier_mismatch;
15706     } else {
15707       DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
15708     }
15709     break;
15710   case IncompatibleNestedPointerAddressSpaceMismatch:
15711     DiagKind = diag::err_typecheck_incompatible_nested_address_space;
15712     isInvalid = true;
15713     break;
15714   case IntToBlockPointer:
15715     DiagKind = diag::err_int_to_block_pointer;
15716     isInvalid = true;
15717     break;
15718   case IncompatibleBlockPointer:
15719     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
15720     isInvalid = true;
15721     break;
15722   case IncompatibleObjCQualifiedId: {
15723     if (SrcType->isObjCQualifiedIdType()) {
15724       const ObjCObjectPointerType *srcOPT =
15725                 SrcType->castAs<ObjCObjectPointerType>();
15726       for (auto *srcProto : srcOPT->quals()) {
15727         PDecl = srcProto;
15728         break;
15729       }
15730       if (const ObjCInterfaceType *IFaceT =
15731             DstType->castAs<ObjCObjectPointerType>()->getInterfaceType())
15732         IFace = IFaceT->getDecl();
15733     }
15734     else if (DstType->isObjCQualifiedIdType()) {
15735       const ObjCObjectPointerType *dstOPT =
15736         DstType->castAs<ObjCObjectPointerType>();
15737       for (auto *dstProto : dstOPT->quals()) {
15738         PDecl = dstProto;
15739         break;
15740       }
15741       if (const ObjCInterfaceType *IFaceT =
15742             SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType())
15743         IFace = IFaceT->getDecl();
15744     }
15745     if (getLangOpts().CPlusPlus) {
15746       DiagKind = diag::err_incompatible_qualified_id;
15747       isInvalid = true;
15748     } else {
15749       DiagKind = diag::warn_incompatible_qualified_id;
15750     }
15751     break;
15752   }
15753   case IncompatibleVectors:
15754     if (getLangOpts().CPlusPlus) {
15755       DiagKind = diag::err_incompatible_vectors;
15756       isInvalid = true;
15757     } else {
15758       DiagKind = diag::warn_incompatible_vectors;
15759     }
15760     break;
15761   case IncompatibleObjCWeakRef:
15762     DiagKind = diag::err_arc_weak_unavailable_assign;
15763     isInvalid = true;
15764     break;
15765   case Incompatible:
15766     if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
15767       if (Complained)
15768         *Complained = true;
15769       return true;
15770     }
15771 
15772     DiagKind = diag::err_typecheck_convert_incompatible;
15773     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15774     MayHaveConvFixit = true;
15775     isInvalid = true;
15776     MayHaveFunctionDiff = true;
15777     break;
15778   }
15779 
15780   QualType FirstType, SecondType;
15781   switch (Action) {
15782   case AA_Assigning:
15783   case AA_Initializing:
15784     // The destination type comes first.
15785     FirstType = DstType;
15786     SecondType = SrcType;
15787     break;
15788 
15789   case AA_Returning:
15790   case AA_Passing:
15791   case AA_Passing_CFAudited:
15792   case AA_Converting:
15793   case AA_Sending:
15794   case AA_Casting:
15795     // The source type comes first.
15796     FirstType = SrcType;
15797     SecondType = DstType;
15798     break;
15799   }
15800 
15801   PartialDiagnostic FDiag = PDiag(DiagKind);
15802   if (Action == AA_Passing_CFAudited)
15803     FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
15804   else
15805     FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
15806 
15807   // If we can fix the conversion, suggest the FixIts.
15808   if (!ConvHints.isNull()) {
15809     for (FixItHint &H : ConvHints.Hints)
15810       FDiag << H;
15811   }
15812 
15813   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
15814 
15815   if (MayHaveFunctionDiff)
15816     HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
15817 
15818   Diag(Loc, FDiag);
15819   if ((DiagKind == diag::warn_incompatible_qualified_id ||
15820        DiagKind == diag::err_incompatible_qualified_id) &&
15821       PDecl && IFace && !IFace->hasDefinition())
15822     Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
15823         << IFace << PDecl;
15824 
15825   if (SecondType == Context.OverloadTy)
15826     NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
15827                               FirstType, /*TakingAddress=*/true);
15828 
15829   if (CheckInferredResultType)
15830     EmitRelatedResultTypeNote(SrcExpr);
15831 
15832   if (Action == AA_Returning && ConvTy == IncompatiblePointer)
15833     EmitRelatedResultTypeNoteForReturn(DstType);
15834 
15835   if (Complained)
15836     *Complained = true;
15837   return isInvalid;
15838 }
15839 
15840 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
15841                                                  llvm::APSInt *Result) {
15842   class SimpleICEDiagnoser : public VerifyICEDiagnoser {
15843   public:
15844     SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc,
15845                                              QualType T) override {
15846       return S.Diag(Loc, diag::err_ice_not_integral)
15847              << T << S.LangOpts.CPlusPlus;
15848     }
15849     SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
15850       return S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus;
15851     }
15852   } Diagnoser;
15853 
15854   return VerifyIntegerConstantExpression(E, Result, Diagnoser);
15855 }
15856 
15857 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
15858                                                  llvm::APSInt *Result,
15859                                                  unsigned DiagID,
15860                                                  bool AllowFold) {
15861   class IDDiagnoser : public VerifyICEDiagnoser {
15862     unsigned DiagID;
15863 
15864   public:
15865     IDDiagnoser(unsigned DiagID)
15866       : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
15867 
15868     SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
15869       return S.Diag(Loc, DiagID);
15870     }
15871   } Diagnoser(DiagID);
15872 
15873   return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
15874 }
15875 
15876 Sema::SemaDiagnosticBuilder
15877 Sema::VerifyICEDiagnoser::diagnoseNotICEType(Sema &S, SourceLocation Loc,
15878                                              QualType T) {
15879   return diagnoseNotICE(S, Loc);
15880 }
15881 
15882 Sema::SemaDiagnosticBuilder
15883 Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc) {
15884   return S.Diag(Loc, diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus;
15885 }
15886 
15887 ExprResult
15888 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
15889                                       VerifyICEDiagnoser &Diagnoser,
15890                                       bool AllowFold) {
15891   SourceLocation DiagLoc = E->getBeginLoc();
15892 
15893   if (getLangOpts().CPlusPlus11) {
15894     // C++11 [expr.const]p5:
15895     //   If an expression of literal class type is used in a context where an
15896     //   integral constant expression is required, then that class type shall
15897     //   have a single non-explicit conversion function to an integral or
15898     //   unscoped enumeration type
15899     ExprResult Converted;
15900     class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
15901       VerifyICEDiagnoser &BaseDiagnoser;
15902     public:
15903       CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser)
15904           : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false,
15905                                 BaseDiagnoser.Suppress, true),
15906             BaseDiagnoser(BaseDiagnoser) {}
15907 
15908       SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
15909                                            QualType T) override {
15910         return BaseDiagnoser.diagnoseNotICEType(S, Loc, T);
15911       }
15912 
15913       SemaDiagnosticBuilder diagnoseIncomplete(
15914           Sema &S, SourceLocation Loc, QualType T) override {
15915         return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
15916       }
15917 
15918       SemaDiagnosticBuilder diagnoseExplicitConv(
15919           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
15920         return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
15921       }
15922 
15923       SemaDiagnosticBuilder noteExplicitConv(
15924           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
15925         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
15926                  << ConvTy->isEnumeralType() << ConvTy;
15927       }
15928 
15929       SemaDiagnosticBuilder diagnoseAmbiguous(
15930           Sema &S, SourceLocation Loc, QualType T) override {
15931         return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
15932       }
15933 
15934       SemaDiagnosticBuilder noteAmbiguous(
15935           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
15936         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
15937                  << ConvTy->isEnumeralType() << ConvTy;
15938       }
15939 
15940       SemaDiagnosticBuilder diagnoseConversion(
15941           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
15942         llvm_unreachable("conversion functions are permitted");
15943       }
15944     } ConvertDiagnoser(Diagnoser);
15945 
15946     Converted = PerformContextualImplicitConversion(DiagLoc, E,
15947                                                     ConvertDiagnoser);
15948     if (Converted.isInvalid())
15949       return Converted;
15950     E = Converted.get();
15951     if (!E->getType()->isIntegralOrUnscopedEnumerationType())
15952       return ExprError();
15953   } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
15954     // An ICE must be of integral or unscoped enumeration type.
15955     if (!Diagnoser.Suppress)
15956       Diagnoser.diagnoseNotICEType(*this, DiagLoc, E->getType())
15957           << E->getSourceRange();
15958     return ExprError();
15959   }
15960 
15961   ExprResult RValueExpr = DefaultLvalueConversion(E);
15962   if (RValueExpr.isInvalid())
15963     return ExprError();
15964 
15965   E = RValueExpr.get();
15966 
15967   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
15968   // in the non-ICE case.
15969   if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
15970     if (Result)
15971       *Result = E->EvaluateKnownConstIntCheckOverflow(Context);
15972     if (!isa<ConstantExpr>(E))
15973       E = ConstantExpr::Create(Context, E);
15974     return E;
15975   }
15976 
15977   Expr::EvalResult EvalResult;
15978   SmallVector<PartialDiagnosticAt, 8> Notes;
15979   EvalResult.Diag = &Notes;
15980 
15981   // Try to evaluate the expression, and produce diagnostics explaining why it's
15982   // not a constant expression as a side-effect.
15983   bool Folded =
15984       E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) &&
15985       EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
15986 
15987   if (!isa<ConstantExpr>(E))
15988     E = ConstantExpr::Create(Context, E, EvalResult.Val);
15989 
15990   // In C++11, we can rely on diagnostics being produced for any expression
15991   // which is not a constant expression. If no diagnostics were produced, then
15992   // this is a constant expression.
15993   if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
15994     if (Result)
15995       *Result = EvalResult.Val.getInt();
15996     return E;
15997   }
15998 
15999   // If our only note is the usual "invalid subexpression" note, just point
16000   // the caret at its location rather than producing an essentially
16001   // redundant note.
16002   if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
16003         diag::note_invalid_subexpr_in_const_expr) {
16004     DiagLoc = Notes[0].first;
16005     Notes.clear();
16006   }
16007 
16008   if (!Folded || !AllowFold) {
16009     if (!Diagnoser.Suppress) {
16010       Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange();
16011       for (const PartialDiagnosticAt &Note : Notes)
16012         Diag(Note.first, Note.second);
16013     }
16014 
16015     return ExprError();
16016   }
16017 
16018   Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange();
16019   for (const PartialDiagnosticAt &Note : Notes)
16020     Diag(Note.first, Note.second);
16021 
16022   if (Result)
16023     *Result = EvalResult.Val.getInt();
16024   return E;
16025 }
16026 
16027 namespace {
16028   // Handle the case where we conclude a expression which we speculatively
16029   // considered to be unevaluated is actually evaluated.
16030   class TransformToPE : public TreeTransform<TransformToPE> {
16031     typedef TreeTransform<TransformToPE> BaseTransform;
16032 
16033   public:
16034     TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
16035 
16036     // Make sure we redo semantic analysis
16037     bool AlwaysRebuild() { return true; }
16038     bool ReplacingOriginal() { return true; }
16039 
16040     // We need to special-case DeclRefExprs referring to FieldDecls which
16041     // are not part of a member pointer formation; normal TreeTransforming
16042     // doesn't catch this case because of the way we represent them in the AST.
16043     // FIXME: This is a bit ugly; is it really the best way to handle this
16044     // case?
16045     //
16046     // Error on DeclRefExprs referring to FieldDecls.
16047     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
16048       if (isa<FieldDecl>(E->getDecl()) &&
16049           !SemaRef.isUnevaluatedContext())
16050         return SemaRef.Diag(E->getLocation(),
16051                             diag::err_invalid_non_static_member_use)
16052             << E->getDecl() << E->getSourceRange();
16053 
16054       return BaseTransform::TransformDeclRefExpr(E);
16055     }
16056 
16057     // Exception: filter out member pointer formation
16058     ExprResult TransformUnaryOperator(UnaryOperator *E) {
16059       if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
16060         return E;
16061 
16062       return BaseTransform::TransformUnaryOperator(E);
16063     }
16064 
16065     // The body of a lambda-expression is in a separate expression evaluation
16066     // context so never needs to be transformed.
16067     // FIXME: Ideally we wouldn't transform the closure type either, and would
16068     // just recreate the capture expressions and lambda expression.
16069     StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
16070       return SkipLambdaBody(E, Body);
16071     }
16072   };
16073 }
16074 
16075 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
16076   assert(isUnevaluatedContext() &&
16077          "Should only transform unevaluated expressions");
16078   ExprEvalContexts.back().Context =
16079       ExprEvalContexts[ExprEvalContexts.size()-2].Context;
16080   if (isUnevaluatedContext())
16081     return E;
16082   return TransformToPE(*this).TransformExpr(E);
16083 }
16084 
16085 void
16086 Sema::PushExpressionEvaluationContext(
16087     ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
16088     ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
16089   ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
16090                                 LambdaContextDecl, ExprContext);
16091   Cleanup.reset();
16092   if (!MaybeODRUseExprs.empty())
16093     std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
16094 }
16095 
16096 void
16097 Sema::PushExpressionEvaluationContext(
16098     ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
16099     ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
16100   Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
16101   PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);
16102 }
16103 
16104 namespace {
16105 
16106 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
16107   PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
16108   if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) {
16109     if (E->getOpcode() == UO_Deref)
16110       return CheckPossibleDeref(S, E->getSubExpr());
16111   } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) {
16112     return CheckPossibleDeref(S, E->getBase());
16113   } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) {
16114     return CheckPossibleDeref(S, E->getBase());
16115   } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) {
16116     QualType Inner;
16117     QualType Ty = E->getType();
16118     if (const auto *Ptr = Ty->getAs<PointerType>())
16119       Inner = Ptr->getPointeeType();
16120     else if (const auto *Arr = S.Context.getAsArrayType(Ty))
16121       Inner = Arr->getElementType();
16122     else
16123       return nullptr;
16124 
16125     if (Inner->hasAttr(attr::NoDeref))
16126       return E;
16127   }
16128   return nullptr;
16129 }
16130 
16131 } // namespace
16132 
16133 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) {
16134   for (const Expr *E : Rec.PossibleDerefs) {
16135     const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E);
16136     if (DeclRef) {
16137       const ValueDecl *Decl = DeclRef->getDecl();
16138       Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type)
16139           << Decl->getName() << E->getSourceRange();
16140       Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName();
16141     } else {
16142       Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl)
16143           << E->getSourceRange();
16144     }
16145   }
16146   Rec.PossibleDerefs.clear();
16147 }
16148 
16149 /// Check whether E, which is either a discarded-value expression or an
16150 /// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue,
16151 /// and if so, remove it from the list of volatile-qualified assignments that
16152 /// we are going to warn are deprecated.
16153 void Sema::CheckUnusedVolatileAssignment(Expr *E) {
16154   if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20)
16155     return;
16156 
16157   // Note: ignoring parens here is not justified by the standard rules, but
16158   // ignoring parentheses seems like a more reasonable approach, and this only
16159   // drives a deprecation warning so doesn't affect conformance.
16160   if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) {
16161     if (BO->getOpcode() == BO_Assign) {
16162       auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs;
16163       LHSs.erase(std::remove(LHSs.begin(), LHSs.end(), BO->getLHS()),
16164                  LHSs.end());
16165     }
16166   }
16167 }
16168 
16169 ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) {
16170   if (!E.isUsable() || !Decl || !Decl->isConsteval() || isConstantEvaluated() ||
16171       RebuildingImmediateInvocation)
16172     return E;
16173 
16174   /// Opportunistically remove the callee from ReferencesToConsteval if we can.
16175   /// It's OK if this fails; we'll also remove this in
16176   /// HandleImmediateInvocations, but catching it here allows us to avoid
16177   /// walking the AST looking for it in simple cases.
16178   if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit()))
16179     if (auto *DeclRef =
16180             dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()))
16181       ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef);
16182 
16183   E = MaybeCreateExprWithCleanups(E);
16184 
16185   ConstantExpr *Res = ConstantExpr::Create(
16186       getASTContext(), E.get(),
16187       ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(),
16188                                    getASTContext()),
16189       /*IsImmediateInvocation*/ true);
16190   ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0);
16191   return Res;
16192 }
16193 
16194 static void EvaluateAndDiagnoseImmediateInvocation(
16195     Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) {
16196   llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
16197   Expr::EvalResult Eval;
16198   Eval.Diag = &Notes;
16199   ConstantExpr *CE = Candidate.getPointer();
16200   bool Result = CE->EvaluateAsConstantExpr(Eval, Expr::EvaluateForCodeGen,
16201                                            SemaRef.getASTContext(), true);
16202   if (!Result || !Notes.empty()) {
16203     Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit();
16204     if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr))
16205       InnerExpr = FunctionalCast->getSubExpr();
16206     FunctionDecl *FD = nullptr;
16207     if (auto *Call = dyn_cast<CallExpr>(InnerExpr))
16208       FD = cast<FunctionDecl>(Call->getCalleeDecl());
16209     else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr))
16210       FD = Call->getConstructor();
16211     else
16212       llvm_unreachable("unhandled decl kind");
16213     assert(FD->isConsteval());
16214     SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call) << FD;
16215     for (auto &Note : Notes)
16216       SemaRef.Diag(Note.first, Note.second);
16217     return;
16218   }
16219   CE->MoveIntoResult(Eval.Val, SemaRef.getASTContext());
16220 }
16221 
16222 static void RemoveNestedImmediateInvocation(
16223     Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec,
16224     SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) {
16225   struct ComplexRemove : TreeTransform<ComplexRemove> {
16226     using Base = TreeTransform<ComplexRemove>;
16227     llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
16228     SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet;
16229     SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator
16230         CurrentII;
16231     ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR,
16232                   SmallVector<Sema::ImmediateInvocationCandidate, 4> &II,
16233                   SmallVector<Sema::ImmediateInvocationCandidate,
16234                               4>::reverse_iterator Current)
16235         : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {}
16236     void RemoveImmediateInvocation(ConstantExpr* E) {
16237       auto It = std::find_if(CurrentII, IISet.rend(),
16238                              [E](Sema::ImmediateInvocationCandidate Elem) {
16239                                return Elem.getPointer() == E;
16240                              });
16241       assert(It != IISet.rend() &&
16242              "ConstantExpr marked IsImmediateInvocation should "
16243              "be present");
16244       It->setInt(1); // Mark as deleted
16245     }
16246     ExprResult TransformConstantExpr(ConstantExpr *E) {
16247       if (!E->isImmediateInvocation())
16248         return Base::TransformConstantExpr(E);
16249       RemoveImmediateInvocation(E);
16250       return Base::TransformExpr(E->getSubExpr());
16251     }
16252     /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so
16253     /// we need to remove its DeclRefExpr from the DRSet.
16254     ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
16255       DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit()));
16256       return Base::TransformCXXOperatorCallExpr(E);
16257     }
16258     /// Base::TransformInitializer skip ConstantExpr so we need to visit them
16259     /// here.
16260     ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) {
16261       if (!Init)
16262         return Init;
16263       /// ConstantExpr are the first layer of implicit node to be removed so if
16264       /// Init isn't a ConstantExpr, no ConstantExpr will be skipped.
16265       if (auto *CE = dyn_cast<ConstantExpr>(Init))
16266         if (CE->isImmediateInvocation())
16267           RemoveImmediateInvocation(CE);
16268       return Base::TransformInitializer(Init, NotCopyInit);
16269     }
16270     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
16271       DRSet.erase(E);
16272       return E;
16273     }
16274     bool AlwaysRebuild() { return false; }
16275     bool ReplacingOriginal() { return true; }
16276     bool AllowSkippingCXXConstructExpr() {
16277       bool Res = AllowSkippingFirstCXXConstructExpr;
16278       AllowSkippingFirstCXXConstructExpr = true;
16279       return Res;
16280     }
16281     bool AllowSkippingFirstCXXConstructExpr = true;
16282   } Transformer(SemaRef, Rec.ReferenceToConsteval,
16283                 Rec.ImmediateInvocationCandidates, It);
16284 
16285   /// CXXConstructExpr with a single argument are getting skipped by
16286   /// TreeTransform in some situtation because they could be implicit. This
16287   /// can only occur for the top-level CXXConstructExpr because it is used
16288   /// nowhere in the expression being transformed therefore will not be rebuilt.
16289   /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from
16290   /// skipping the first CXXConstructExpr.
16291   if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit()))
16292     Transformer.AllowSkippingFirstCXXConstructExpr = false;
16293 
16294   ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr());
16295   assert(Res.isUsable());
16296   Res = SemaRef.MaybeCreateExprWithCleanups(Res);
16297   It->getPointer()->setSubExpr(Res.get());
16298 }
16299 
16300 static void
16301 HandleImmediateInvocations(Sema &SemaRef,
16302                            Sema::ExpressionEvaluationContextRecord &Rec) {
16303   if ((Rec.ImmediateInvocationCandidates.size() == 0 &&
16304        Rec.ReferenceToConsteval.size() == 0) ||
16305       SemaRef.RebuildingImmediateInvocation)
16306     return;
16307 
16308   /// When we have more then 1 ImmediateInvocationCandidates we need to check
16309   /// for nested ImmediateInvocationCandidates. when we have only 1 we only
16310   /// need to remove ReferenceToConsteval in the immediate invocation.
16311   if (Rec.ImmediateInvocationCandidates.size() > 1) {
16312 
16313     /// Prevent sema calls during the tree transform from adding pointers that
16314     /// are already in the sets.
16315     llvm::SaveAndRestore<bool> DisableIITracking(
16316         SemaRef.RebuildingImmediateInvocation, true);
16317 
16318     /// Prevent diagnostic during tree transfrom as they are duplicates
16319     Sema::TentativeAnalysisScope DisableDiag(SemaRef);
16320 
16321     for (auto It = Rec.ImmediateInvocationCandidates.rbegin();
16322          It != Rec.ImmediateInvocationCandidates.rend(); It++)
16323       if (!It->getInt())
16324         RemoveNestedImmediateInvocation(SemaRef, Rec, It);
16325   } else if (Rec.ImmediateInvocationCandidates.size() == 1 &&
16326              Rec.ReferenceToConsteval.size()) {
16327     struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> {
16328       llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
16329       SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {}
16330       bool VisitDeclRefExpr(DeclRefExpr *E) {
16331         DRSet.erase(E);
16332         return DRSet.size();
16333       }
16334     } Visitor(Rec.ReferenceToConsteval);
16335     Visitor.TraverseStmt(
16336         Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr());
16337   }
16338   for (auto CE : Rec.ImmediateInvocationCandidates)
16339     if (!CE.getInt())
16340       EvaluateAndDiagnoseImmediateInvocation(SemaRef, CE);
16341   for (auto DR : Rec.ReferenceToConsteval) {
16342     auto *FD = cast<FunctionDecl>(DR->getDecl());
16343     SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address)
16344         << FD;
16345     SemaRef.Diag(FD->getLocation(), diag::note_declared_at);
16346   }
16347 }
16348 
16349 void Sema::PopExpressionEvaluationContext() {
16350   ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
16351   unsigned NumTypos = Rec.NumTypos;
16352 
16353   if (!Rec.Lambdas.empty()) {
16354     using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind;
16355     if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || Rec.isUnevaluated() ||
16356         (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17)) {
16357       unsigned D;
16358       if (Rec.isUnevaluated()) {
16359         // C++11 [expr.prim.lambda]p2:
16360         //   A lambda-expression shall not appear in an unevaluated operand
16361         //   (Clause 5).
16362         D = diag::err_lambda_unevaluated_operand;
16363       } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
16364         // C++1y [expr.const]p2:
16365         //   A conditional-expression e is a core constant expression unless the
16366         //   evaluation of e, following the rules of the abstract machine, would
16367         //   evaluate [...] a lambda-expression.
16368         D = diag::err_lambda_in_constant_expression;
16369       } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
16370         // C++17 [expr.prim.lamda]p2:
16371         // A lambda-expression shall not appear [...] in a template-argument.
16372         D = diag::err_lambda_in_invalid_context;
16373       } else
16374         llvm_unreachable("Couldn't infer lambda error message.");
16375 
16376       for (const auto *L : Rec.Lambdas)
16377         Diag(L->getBeginLoc(), D);
16378     }
16379   }
16380 
16381   WarnOnPendingNoDerefs(Rec);
16382   HandleImmediateInvocations(*this, Rec);
16383 
16384   // Warn on any volatile-qualified simple-assignments that are not discarded-
16385   // value expressions nor unevaluated operands (those cases get removed from
16386   // this list by CheckUnusedVolatileAssignment).
16387   for (auto *BO : Rec.VolatileAssignmentLHSs)
16388     Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile)
16389         << BO->getType();
16390 
16391   // When are coming out of an unevaluated context, clear out any
16392   // temporaries that we may have created as part of the evaluation of
16393   // the expression in that context: they aren't relevant because they
16394   // will never be constructed.
16395   if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
16396     ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
16397                              ExprCleanupObjects.end());
16398     Cleanup = Rec.ParentCleanup;
16399     CleanupVarDeclMarking();
16400     std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
16401   // Otherwise, merge the contexts together.
16402   } else {
16403     Cleanup.mergeFrom(Rec.ParentCleanup);
16404     MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
16405                             Rec.SavedMaybeODRUseExprs.end());
16406   }
16407 
16408   // Pop the current expression evaluation context off the stack.
16409   ExprEvalContexts.pop_back();
16410 
16411   // The global expression evaluation context record is never popped.
16412   ExprEvalContexts.back().NumTypos += NumTypos;
16413 }
16414 
16415 void Sema::DiscardCleanupsInEvaluationContext() {
16416   ExprCleanupObjects.erase(
16417          ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
16418          ExprCleanupObjects.end());
16419   Cleanup.reset();
16420   MaybeODRUseExprs.clear();
16421 }
16422 
16423 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
16424   ExprResult Result = CheckPlaceholderExpr(E);
16425   if (Result.isInvalid())
16426     return ExprError();
16427   E = Result.get();
16428   if (!E->getType()->isVariablyModifiedType())
16429     return E;
16430   return TransformToPotentiallyEvaluated(E);
16431 }
16432 
16433 /// Are we in a context that is potentially constant evaluated per C++20
16434 /// [expr.const]p12?
16435 static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) {
16436   /// C++2a [expr.const]p12:
16437   //   An expression or conversion is potentially constant evaluated if it is
16438   switch (SemaRef.ExprEvalContexts.back().Context) {
16439     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
16440       // -- a manifestly constant-evaluated expression,
16441     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
16442     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
16443     case Sema::ExpressionEvaluationContext::DiscardedStatement:
16444       // -- a potentially-evaluated expression,
16445     case Sema::ExpressionEvaluationContext::UnevaluatedList:
16446       // -- an immediate subexpression of a braced-init-list,
16447 
16448       // -- [FIXME] an expression of the form & cast-expression that occurs
16449       //    within a templated entity
16450       // -- a subexpression of one of the above that is not a subexpression of
16451       // a nested unevaluated operand.
16452       return true;
16453 
16454     case Sema::ExpressionEvaluationContext::Unevaluated:
16455     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
16456       // Expressions in this context are never evaluated.
16457       return false;
16458   }
16459   llvm_unreachable("Invalid context");
16460 }
16461 
16462 /// Return true if this function has a calling convention that requires mangling
16463 /// in the size of the parameter pack.
16464 static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) {
16465   // These manglings don't do anything on non-Windows or non-x86 platforms, so
16466   // we don't need parameter type sizes.
16467   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
16468   if (!TT.isOSWindows() || !TT.isX86())
16469     return false;
16470 
16471   // If this is C++ and this isn't an extern "C" function, parameters do not
16472   // need to be complete. In this case, C++ mangling will apply, which doesn't
16473   // use the size of the parameters.
16474   if (S.getLangOpts().CPlusPlus && !FD->isExternC())
16475     return false;
16476 
16477   // Stdcall, fastcall, and vectorcall need this special treatment.
16478   CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
16479   switch (CC) {
16480   case CC_X86StdCall:
16481   case CC_X86FastCall:
16482   case CC_X86VectorCall:
16483     return true;
16484   default:
16485     break;
16486   }
16487   return false;
16488 }
16489 
16490 /// Require that all of the parameter types of function be complete. Normally,
16491 /// parameter types are only required to be complete when a function is called
16492 /// or defined, but to mangle functions with certain calling conventions, the
16493 /// mangler needs to know the size of the parameter list. In this situation,
16494 /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles
16495 /// the function as _foo@0, i.e. zero bytes of parameters, which will usually
16496 /// result in a linker error. Clang doesn't implement this behavior, and instead
16497 /// attempts to error at compile time.
16498 static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD,
16499                                                   SourceLocation Loc) {
16500   class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser {
16501     FunctionDecl *FD;
16502     ParmVarDecl *Param;
16503 
16504   public:
16505     ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param)
16506         : FD(FD), Param(Param) {}
16507 
16508     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
16509       CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
16510       StringRef CCName;
16511       switch (CC) {
16512       case CC_X86StdCall:
16513         CCName = "stdcall";
16514         break;
16515       case CC_X86FastCall:
16516         CCName = "fastcall";
16517         break;
16518       case CC_X86VectorCall:
16519         CCName = "vectorcall";
16520         break;
16521       default:
16522         llvm_unreachable("CC does not need mangling");
16523       }
16524 
16525       S.Diag(Loc, diag::err_cconv_incomplete_param_type)
16526           << Param->getDeclName() << FD->getDeclName() << CCName;
16527     }
16528   };
16529 
16530   for (ParmVarDecl *Param : FD->parameters()) {
16531     ParamIncompleteTypeDiagnoser Diagnoser(FD, Param);
16532     S.RequireCompleteType(Loc, Param->getType(), Diagnoser);
16533   }
16534 }
16535 
16536 namespace {
16537 enum class OdrUseContext {
16538   /// Declarations in this context are not odr-used.
16539   None,
16540   /// Declarations in this context are formally odr-used, but this is a
16541   /// dependent context.
16542   Dependent,
16543   /// Declarations in this context are odr-used but not actually used (yet).
16544   FormallyOdrUsed,
16545   /// Declarations in this context are used.
16546   Used
16547 };
16548 }
16549 
16550 /// Are we within a context in which references to resolved functions or to
16551 /// variables result in odr-use?
16552 static OdrUseContext isOdrUseContext(Sema &SemaRef) {
16553   OdrUseContext Result;
16554 
16555   switch (SemaRef.ExprEvalContexts.back().Context) {
16556     case Sema::ExpressionEvaluationContext::Unevaluated:
16557     case Sema::ExpressionEvaluationContext::UnevaluatedList:
16558     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
16559       return OdrUseContext::None;
16560 
16561     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
16562     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
16563       Result = OdrUseContext::Used;
16564       break;
16565 
16566     case Sema::ExpressionEvaluationContext::DiscardedStatement:
16567       Result = OdrUseContext::FormallyOdrUsed;
16568       break;
16569 
16570     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
16571       // A default argument formally results in odr-use, but doesn't actually
16572       // result in a use in any real sense until it itself is used.
16573       Result = OdrUseContext::FormallyOdrUsed;
16574       break;
16575   }
16576 
16577   if (SemaRef.CurContext->isDependentContext())
16578     return OdrUseContext::Dependent;
16579 
16580   return Result;
16581 }
16582 
16583 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
16584   if (!Func->isConstexpr())
16585     return false;
16586 
16587   if (Func->isImplicitlyInstantiable() || !Func->isUserProvided())
16588     return true;
16589   auto *CCD = dyn_cast<CXXConstructorDecl>(Func);
16590   return CCD && CCD->getInheritedConstructor();
16591 }
16592 
16593 /// Mark a function referenced, and check whether it is odr-used
16594 /// (C++ [basic.def.odr]p2, C99 6.9p3)
16595 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
16596                                   bool MightBeOdrUse) {
16597   assert(Func && "No function?");
16598 
16599   Func->setReferenced();
16600 
16601   // Recursive functions aren't really used until they're used from some other
16602   // context.
16603   bool IsRecursiveCall = CurContext == Func;
16604 
16605   // C++11 [basic.def.odr]p3:
16606   //   A function whose name appears as a potentially-evaluated expression is
16607   //   odr-used if it is the unique lookup result or the selected member of a
16608   //   set of overloaded functions [...].
16609   //
16610   // We (incorrectly) mark overload resolution as an unevaluated context, so we
16611   // can just check that here.
16612   OdrUseContext OdrUse =
16613       MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None;
16614   if (IsRecursiveCall && OdrUse == OdrUseContext::Used)
16615     OdrUse = OdrUseContext::FormallyOdrUsed;
16616 
16617   // Trivial default constructors and destructors are never actually used.
16618   // FIXME: What about other special members?
16619   if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() &&
16620       OdrUse == OdrUseContext::Used) {
16621     if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func))
16622       if (Constructor->isDefaultConstructor())
16623         OdrUse = OdrUseContext::FormallyOdrUsed;
16624     if (isa<CXXDestructorDecl>(Func))
16625       OdrUse = OdrUseContext::FormallyOdrUsed;
16626   }
16627 
16628   // C++20 [expr.const]p12:
16629   //   A function [...] is needed for constant evaluation if it is [...] a
16630   //   constexpr function that is named by an expression that is potentially
16631   //   constant evaluated
16632   bool NeededForConstantEvaluation =
16633       isPotentiallyConstantEvaluatedContext(*this) &&
16634       isImplicitlyDefinableConstexprFunction(Func);
16635 
16636   // Determine whether we require a function definition to exist, per
16637   // C++11 [temp.inst]p3:
16638   //   Unless a function template specialization has been explicitly
16639   //   instantiated or explicitly specialized, the function template
16640   //   specialization is implicitly instantiated when the specialization is
16641   //   referenced in a context that requires a function definition to exist.
16642   // C++20 [temp.inst]p7:
16643   //   The existence of a definition of a [...] function is considered to
16644   //   affect the semantics of the program if the [...] function is needed for
16645   //   constant evaluation by an expression
16646   // C++20 [basic.def.odr]p10:
16647   //   Every program shall contain exactly one definition of every non-inline
16648   //   function or variable that is odr-used in that program outside of a
16649   //   discarded statement
16650   // C++20 [special]p1:
16651   //   The implementation will implicitly define [defaulted special members]
16652   //   if they are odr-used or needed for constant evaluation.
16653   //
16654   // Note that we skip the implicit instantiation of templates that are only
16655   // used in unused default arguments or by recursive calls to themselves.
16656   // This is formally non-conforming, but seems reasonable in practice.
16657   bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used ||
16658                                              NeededForConstantEvaluation);
16659 
16660   // C++14 [temp.expl.spec]p6:
16661   //   If a template [...] is explicitly specialized then that specialization
16662   //   shall be declared before the first use of that specialization that would
16663   //   cause an implicit instantiation to take place, in every translation unit
16664   //   in which such a use occurs
16665   if (NeedDefinition &&
16666       (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
16667        Func->getMemberSpecializationInfo()))
16668     checkSpecializationVisibility(Loc, Func);
16669 
16670   if (getLangOpts().CUDA)
16671     CheckCUDACall(Loc, Func);
16672 
16673   if (getLangOpts().SYCLIsDevice)
16674     checkSYCLDeviceFunction(Loc, Func);
16675 
16676   // If we need a definition, try to create one.
16677   if (NeedDefinition && !Func->getBody()) {
16678     runWithSufficientStackSpace(Loc, [&] {
16679       if (CXXConstructorDecl *Constructor =
16680               dyn_cast<CXXConstructorDecl>(Func)) {
16681         Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
16682         if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
16683           if (Constructor->isDefaultConstructor()) {
16684             if (Constructor->isTrivial() &&
16685                 !Constructor->hasAttr<DLLExportAttr>())
16686               return;
16687             DefineImplicitDefaultConstructor(Loc, Constructor);
16688           } else if (Constructor->isCopyConstructor()) {
16689             DefineImplicitCopyConstructor(Loc, Constructor);
16690           } else if (Constructor->isMoveConstructor()) {
16691             DefineImplicitMoveConstructor(Loc, Constructor);
16692           }
16693         } else if (Constructor->getInheritedConstructor()) {
16694           DefineInheritingConstructor(Loc, Constructor);
16695         }
16696       } else if (CXXDestructorDecl *Destructor =
16697                      dyn_cast<CXXDestructorDecl>(Func)) {
16698         Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
16699         if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
16700           if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
16701             return;
16702           DefineImplicitDestructor(Loc, Destructor);
16703         }
16704         if (Destructor->isVirtual() && getLangOpts().AppleKext)
16705           MarkVTableUsed(Loc, Destructor->getParent());
16706       } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
16707         if (MethodDecl->isOverloadedOperator() &&
16708             MethodDecl->getOverloadedOperator() == OO_Equal) {
16709           MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
16710           if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
16711             if (MethodDecl->isCopyAssignmentOperator())
16712               DefineImplicitCopyAssignment(Loc, MethodDecl);
16713             else if (MethodDecl->isMoveAssignmentOperator())
16714               DefineImplicitMoveAssignment(Loc, MethodDecl);
16715           }
16716         } else if (isa<CXXConversionDecl>(MethodDecl) &&
16717                    MethodDecl->getParent()->isLambda()) {
16718           CXXConversionDecl *Conversion =
16719               cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
16720           if (Conversion->isLambdaToBlockPointerConversion())
16721             DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
16722           else
16723             DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
16724         } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
16725           MarkVTableUsed(Loc, MethodDecl->getParent());
16726       }
16727 
16728       if (Func->isDefaulted() && !Func->isDeleted()) {
16729         DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func);
16730         if (DCK != DefaultedComparisonKind::None)
16731           DefineDefaultedComparison(Loc, Func, DCK);
16732       }
16733 
16734       // Implicit instantiation of function templates and member functions of
16735       // class templates.
16736       if (Func->isImplicitlyInstantiable()) {
16737         TemplateSpecializationKind TSK =
16738             Func->getTemplateSpecializationKindForInstantiation();
16739         SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
16740         bool FirstInstantiation = PointOfInstantiation.isInvalid();
16741         if (FirstInstantiation) {
16742           PointOfInstantiation = Loc;
16743           Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
16744         } else if (TSK != TSK_ImplicitInstantiation) {
16745           // Use the point of use as the point of instantiation, instead of the
16746           // point of explicit instantiation (which we track as the actual point
16747           // of instantiation). This gives better backtraces in diagnostics.
16748           PointOfInstantiation = Loc;
16749         }
16750 
16751         if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
16752             Func->isConstexpr()) {
16753           if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
16754               cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
16755               CodeSynthesisContexts.size())
16756             PendingLocalImplicitInstantiations.push_back(
16757                 std::make_pair(Func, PointOfInstantiation));
16758           else if (Func->isConstexpr())
16759             // Do not defer instantiations of constexpr functions, to avoid the
16760             // expression evaluator needing to call back into Sema if it sees a
16761             // call to such a function.
16762             InstantiateFunctionDefinition(PointOfInstantiation, Func);
16763           else {
16764             Func->setInstantiationIsPending(true);
16765             PendingInstantiations.push_back(
16766                 std::make_pair(Func, PointOfInstantiation));
16767             // Notify the consumer that a function was implicitly instantiated.
16768             Consumer.HandleCXXImplicitFunctionInstantiation(Func);
16769           }
16770         }
16771       } else {
16772         // Walk redefinitions, as some of them may be instantiable.
16773         for (auto i : Func->redecls()) {
16774           if (!i->isUsed(false) && i->isImplicitlyInstantiable())
16775             MarkFunctionReferenced(Loc, i, MightBeOdrUse);
16776         }
16777       }
16778     });
16779   }
16780 
16781   // C++14 [except.spec]p17:
16782   //   An exception-specification is considered to be needed when:
16783   //   - the function is odr-used or, if it appears in an unevaluated operand,
16784   //     would be odr-used if the expression were potentially-evaluated;
16785   //
16786   // Note, we do this even if MightBeOdrUse is false. That indicates that the
16787   // function is a pure virtual function we're calling, and in that case the
16788   // function was selected by overload resolution and we need to resolve its
16789   // exception specification for a different reason.
16790   const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
16791   if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
16792     ResolveExceptionSpec(Loc, FPT);
16793 
16794   // If this is the first "real" use, act on that.
16795   if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) {
16796     // Keep track of used but undefined functions.
16797     if (!Func->isDefined()) {
16798       if (mightHaveNonExternalLinkage(Func))
16799         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
16800       else if (Func->getMostRecentDecl()->isInlined() &&
16801                !LangOpts.GNUInline &&
16802                !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
16803         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
16804       else if (isExternalWithNoLinkageType(Func))
16805         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
16806     }
16807 
16808     // Some x86 Windows calling conventions mangle the size of the parameter
16809     // pack into the name. Computing the size of the parameters requires the
16810     // parameter types to be complete. Check that now.
16811     if (funcHasParameterSizeMangling(*this, Func))
16812       CheckCompleteParameterTypesForMangler(*this, Func, Loc);
16813 
16814     // In the MS C++ ABI, the compiler emits destructor variants where they are
16815     // used. If the destructor is used here but defined elsewhere, mark the
16816     // virtual base destructors referenced. If those virtual base destructors
16817     // are inline, this will ensure they are defined when emitting the complete
16818     // destructor variant. This checking may be redundant if the destructor is
16819     // provided later in this TU.
16820     if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
16821       if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) {
16822         CXXRecordDecl *Parent = Dtor->getParent();
16823         if (Parent->getNumVBases() > 0 && !Dtor->getBody())
16824           CheckCompleteDestructorVariant(Loc, Dtor);
16825       }
16826     }
16827 
16828     Func->markUsed(Context);
16829   }
16830 }
16831 
16832 /// Directly mark a variable odr-used. Given a choice, prefer to use
16833 /// MarkVariableReferenced since it does additional checks and then
16834 /// calls MarkVarDeclODRUsed.
16835 /// If the variable must be captured:
16836 ///  - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
16837 ///  - else capture it in the DeclContext that maps to the
16838 ///    *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
16839 static void
16840 MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef,
16841                    const unsigned *const FunctionScopeIndexToStopAt = nullptr) {
16842   // Keep track of used but undefined variables.
16843   // FIXME: We shouldn't suppress this warning for static data members.
16844   if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
16845       (!Var->isExternallyVisible() || Var->isInline() ||
16846        SemaRef.isExternalWithNoLinkageType(Var)) &&
16847       !(Var->isStaticDataMember() && Var->hasInit())) {
16848     SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()];
16849     if (old.isInvalid())
16850       old = Loc;
16851   }
16852   QualType CaptureType, DeclRefType;
16853   if (SemaRef.LangOpts.OpenMP)
16854     SemaRef.tryCaptureOpenMPLambdas(Var);
16855   SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit,
16856     /*EllipsisLoc*/ SourceLocation(),
16857     /*BuildAndDiagnose*/ true,
16858     CaptureType, DeclRefType,
16859     FunctionScopeIndexToStopAt);
16860 
16861   Var->markUsed(SemaRef.Context);
16862 }
16863 
16864 void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture,
16865                                              SourceLocation Loc,
16866                                              unsigned CapturingScopeIndex) {
16867   MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex);
16868 }
16869 
16870 static void
16871 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
16872                                    ValueDecl *var, DeclContext *DC) {
16873   DeclContext *VarDC = var->getDeclContext();
16874 
16875   //  If the parameter still belongs to the translation unit, then
16876   //  we're actually just using one parameter in the declaration of
16877   //  the next.
16878   if (isa<ParmVarDecl>(var) &&
16879       isa<TranslationUnitDecl>(VarDC))
16880     return;
16881 
16882   // For C code, don't diagnose about capture if we're not actually in code
16883   // right now; it's impossible to write a non-constant expression outside of
16884   // function context, so we'll get other (more useful) diagnostics later.
16885   //
16886   // For C++, things get a bit more nasty... it would be nice to suppress this
16887   // diagnostic for certain cases like using a local variable in an array bound
16888   // for a member of a local class, but the correct predicate is not obvious.
16889   if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
16890     return;
16891 
16892   unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
16893   unsigned ContextKind = 3; // unknown
16894   if (isa<CXXMethodDecl>(VarDC) &&
16895       cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
16896     ContextKind = 2;
16897   } else if (isa<FunctionDecl>(VarDC)) {
16898     ContextKind = 0;
16899   } else if (isa<BlockDecl>(VarDC)) {
16900     ContextKind = 1;
16901   }
16902 
16903   S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
16904     << var << ValueKind << ContextKind << VarDC;
16905   S.Diag(var->getLocation(), diag::note_entity_declared_at)
16906       << var;
16907 
16908   // FIXME: Add additional diagnostic info about class etc. which prevents
16909   // capture.
16910 }
16911 
16912 
16913 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
16914                                       bool &SubCapturesAreNested,
16915                                       QualType &CaptureType,
16916                                       QualType &DeclRefType) {
16917    // Check whether we've already captured it.
16918   if (CSI->CaptureMap.count(Var)) {
16919     // If we found a capture, any subcaptures are nested.
16920     SubCapturesAreNested = true;
16921 
16922     // Retrieve the capture type for this variable.
16923     CaptureType = CSI->getCapture(Var).getCaptureType();
16924 
16925     // Compute the type of an expression that refers to this variable.
16926     DeclRefType = CaptureType.getNonReferenceType();
16927 
16928     // Similarly to mutable captures in lambda, all the OpenMP captures by copy
16929     // are mutable in the sense that user can change their value - they are
16930     // private instances of the captured declarations.
16931     const Capture &Cap = CSI->getCapture(Var);
16932     if (Cap.isCopyCapture() &&
16933         !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
16934         !(isa<CapturedRegionScopeInfo>(CSI) &&
16935           cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
16936       DeclRefType.addConst();
16937     return true;
16938   }
16939   return false;
16940 }
16941 
16942 // Only block literals, captured statements, and lambda expressions can
16943 // capture; other scopes don't work.
16944 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
16945                                  SourceLocation Loc,
16946                                  const bool Diagnose, Sema &S) {
16947   if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
16948     return getLambdaAwareParentOfDeclContext(DC);
16949   else if (Var->hasLocalStorage()) {
16950     if (Diagnose)
16951        diagnoseUncapturableValueReference(S, Loc, Var, DC);
16952   }
16953   return nullptr;
16954 }
16955 
16956 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
16957 // certain types of variables (unnamed, variably modified types etc.)
16958 // so check for eligibility.
16959 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
16960                                  SourceLocation Loc,
16961                                  const bool Diagnose, Sema &S) {
16962 
16963   bool IsBlock = isa<BlockScopeInfo>(CSI);
16964   bool IsLambda = isa<LambdaScopeInfo>(CSI);
16965 
16966   // Lambdas are not allowed to capture unnamed variables
16967   // (e.g. anonymous unions).
16968   // FIXME: The C++11 rule don't actually state this explicitly, but I'm
16969   // assuming that's the intent.
16970   if (IsLambda && !Var->getDeclName()) {
16971     if (Diagnose) {
16972       S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
16973       S.Diag(Var->getLocation(), diag::note_declared_at);
16974     }
16975     return false;
16976   }
16977 
16978   // Prohibit variably-modified types in blocks; they're difficult to deal with.
16979   if (Var->getType()->isVariablyModifiedType() && IsBlock) {
16980     if (Diagnose) {
16981       S.Diag(Loc, diag::err_ref_vm_type);
16982       S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
16983     }
16984     return false;
16985   }
16986   // Prohibit structs with flexible array members too.
16987   // We cannot capture what is in the tail end of the struct.
16988   if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
16989     if (VTTy->getDecl()->hasFlexibleArrayMember()) {
16990       if (Diagnose) {
16991         if (IsBlock)
16992           S.Diag(Loc, diag::err_ref_flexarray_type);
16993         else
16994           S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var;
16995         S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
16996       }
16997       return false;
16998     }
16999   }
17000   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
17001   // Lambdas and captured statements are not allowed to capture __block
17002   // variables; they don't support the expected semantics.
17003   if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
17004     if (Diagnose) {
17005       S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda;
17006       S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17007     }
17008     return false;
17009   }
17010   // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
17011   if (S.getLangOpts().OpenCL && IsBlock &&
17012       Var->getType()->isBlockPointerType()) {
17013     if (Diagnose)
17014       S.Diag(Loc, diag::err_opencl_block_ref_block);
17015     return false;
17016   }
17017 
17018   return true;
17019 }
17020 
17021 // Returns true if the capture by block was successful.
17022 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
17023                                  SourceLocation Loc,
17024                                  const bool BuildAndDiagnose,
17025                                  QualType &CaptureType,
17026                                  QualType &DeclRefType,
17027                                  const bool Nested,
17028                                  Sema &S, bool Invalid) {
17029   bool ByRef = false;
17030 
17031   // Blocks are not allowed to capture arrays, excepting OpenCL.
17032   // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
17033   // (decayed to pointers).
17034   if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
17035     if (BuildAndDiagnose) {
17036       S.Diag(Loc, diag::err_ref_array_type);
17037       S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17038       Invalid = true;
17039     } else {
17040       return false;
17041     }
17042   }
17043 
17044   // Forbid the block-capture of autoreleasing variables.
17045   if (!Invalid &&
17046       CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
17047     if (BuildAndDiagnose) {
17048       S.Diag(Loc, diag::err_arc_autoreleasing_capture)
17049         << /*block*/ 0;
17050       S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17051       Invalid = true;
17052     } else {
17053       return false;
17054     }
17055   }
17056 
17057   // Warn about implicitly autoreleasing indirect parameters captured by blocks.
17058   if (const auto *PT = CaptureType->getAs<PointerType>()) {
17059     QualType PointeeTy = PT->getPointeeType();
17060 
17061     if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() &&
17062         PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
17063         !S.Context.hasDirectOwnershipQualifier(PointeeTy)) {
17064       if (BuildAndDiagnose) {
17065         SourceLocation VarLoc = Var->getLocation();
17066         S.Diag(Loc, diag::warn_block_capture_autoreleasing);
17067         S.Diag(VarLoc, diag::note_declare_parameter_strong);
17068       }
17069     }
17070   }
17071 
17072   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
17073   if (HasBlocksAttr || CaptureType->isReferenceType() ||
17074       (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) {
17075     // Block capture by reference does not change the capture or
17076     // declaration reference types.
17077     ByRef = true;
17078   } else {
17079     // Block capture by copy introduces 'const'.
17080     CaptureType = CaptureType.getNonReferenceType().withConst();
17081     DeclRefType = CaptureType;
17082   }
17083 
17084   // Actually capture the variable.
17085   if (BuildAndDiagnose)
17086     BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(),
17087                     CaptureType, Invalid);
17088 
17089   return !Invalid;
17090 }
17091 
17092 
17093 /// Capture the given variable in the captured region.
17094 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
17095                                     VarDecl *Var,
17096                                     SourceLocation Loc,
17097                                     const bool BuildAndDiagnose,
17098                                     QualType &CaptureType,
17099                                     QualType &DeclRefType,
17100                                     const bool RefersToCapturedVariable,
17101                                     Sema &S, bool Invalid) {
17102   // By default, capture variables by reference.
17103   bool ByRef = true;
17104   // Using an LValue reference type is consistent with Lambdas (see below).
17105   if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
17106     if (S.isOpenMPCapturedDecl(Var)) {
17107       bool HasConst = DeclRefType.isConstQualified();
17108       DeclRefType = DeclRefType.getUnqualifiedType();
17109       // Don't lose diagnostics about assignments to const.
17110       if (HasConst)
17111         DeclRefType.addConst();
17112     }
17113     // Do not capture firstprivates in tasks.
17114     if (S.isOpenMPPrivateDecl(Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel) !=
17115         OMPC_unknown)
17116       return true;
17117     ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel,
17118                                     RSI->OpenMPCaptureLevel);
17119   }
17120 
17121   if (ByRef)
17122     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
17123   else
17124     CaptureType = DeclRefType;
17125 
17126   // Actually capture the variable.
17127   if (BuildAndDiagnose)
17128     RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable,
17129                     Loc, SourceLocation(), CaptureType, Invalid);
17130 
17131   return !Invalid;
17132 }
17133 
17134 /// Capture the given variable in the lambda.
17135 static bool captureInLambda(LambdaScopeInfo *LSI,
17136                             VarDecl *Var,
17137                             SourceLocation Loc,
17138                             const bool BuildAndDiagnose,
17139                             QualType &CaptureType,
17140                             QualType &DeclRefType,
17141                             const bool RefersToCapturedVariable,
17142                             const Sema::TryCaptureKind Kind,
17143                             SourceLocation EllipsisLoc,
17144                             const bool IsTopScope,
17145                             Sema &S, bool Invalid) {
17146   // Determine whether we are capturing by reference or by value.
17147   bool ByRef = false;
17148   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
17149     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
17150   } else {
17151     ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
17152   }
17153 
17154   // Compute the type of the field that will capture this variable.
17155   if (ByRef) {
17156     // C++11 [expr.prim.lambda]p15:
17157     //   An entity is captured by reference if it is implicitly or
17158     //   explicitly captured but not captured by copy. It is
17159     //   unspecified whether additional unnamed non-static data
17160     //   members are declared in the closure type for entities
17161     //   captured by reference.
17162     //
17163     // FIXME: It is not clear whether we want to build an lvalue reference
17164     // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
17165     // to do the former, while EDG does the latter. Core issue 1249 will
17166     // clarify, but for now we follow GCC because it's a more permissive and
17167     // easily defensible position.
17168     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
17169   } else {
17170     // C++11 [expr.prim.lambda]p14:
17171     //   For each entity captured by copy, an unnamed non-static
17172     //   data member is declared in the closure type. The
17173     //   declaration order of these members is unspecified. The type
17174     //   of such a data member is the type of the corresponding
17175     //   captured entity if the entity is not a reference to an
17176     //   object, or the referenced type otherwise. [Note: If the
17177     //   captured entity is a reference to a function, the
17178     //   corresponding data member is also a reference to a
17179     //   function. - end note ]
17180     if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
17181       if (!RefType->getPointeeType()->isFunctionType())
17182         CaptureType = RefType->getPointeeType();
17183     }
17184 
17185     // Forbid the lambda copy-capture of autoreleasing variables.
17186     if (!Invalid &&
17187         CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
17188       if (BuildAndDiagnose) {
17189         S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
17190         S.Diag(Var->getLocation(), diag::note_previous_decl)
17191           << Var->getDeclName();
17192         Invalid = true;
17193       } else {
17194         return false;
17195       }
17196     }
17197 
17198     // Make sure that by-copy captures are of a complete and non-abstract type.
17199     if (!Invalid && BuildAndDiagnose) {
17200       if (!CaptureType->isDependentType() &&
17201           S.RequireCompleteSizedType(
17202               Loc, CaptureType,
17203               diag::err_capture_of_incomplete_or_sizeless_type,
17204               Var->getDeclName()))
17205         Invalid = true;
17206       else if (S.RequireNonAbstractType(Loc, CaptureType,
17207                                         diag::err_capture_of_abstract_type))
17208         Invalid = true;
17209     }
17210   }
17211 
17212   // Compute the type of a reference to this captured variable.
17213   if (ByRef)
17214     DeclRefType = CaptureType.getNonReferenceType();
17215   else {
17216     // C++ [expr.prim.lambda]p5:
17217     //   The closure type for a lambda-expression has a public inline
17218     //   function call operator [...]. This function call operator is
17219     //   declared const (9.3.1) if and only if the lambda-expression's
17220     //   parameter-declaration-clause is not followed by mutable.
17221     DeclRefType = CaptureType.getNonReferenceType();
17222     if (!LSI->Mutable && !CaptureType->isReferenceType())
17223       DeclRefType.addConst();
17224   }
17225 
17226   // Add the capture.
17227   if (BuildAndDiagnose)
17228     LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable,
17229                     Loc, EllipsisLoc, CaptureType, Invalid);
17230 
17231   return !Invalid;
17232 }
17233 
17234 bool Sema::tryCaptureVariable(
17235     VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
17236     SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
17237     QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
17238   // An init-capture is notionally from the context surrounding its
17239   // declaration, but its parent DC is the lambda class.
17240   DeclContext *VarDC = Var->getDeclContext();
17241   if (Var->isInitCapture())
17242     VarDC = VarDC->getParent();
17243 
17244   DeclContext *DC = CurContext;
17245   const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
17246       ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
17247   // We need to sync up the Declaration Context with the
17248   // FunctionScopeIndexToStopAt
17249   if (FunctionScopeIndexToStopAt) {
17250     unsigned FSIndex = FunctionScopes.size() - 1;
17251     while (FSIndex != MaxFunctionScopesIndex) {
17252       DC = getLambdaAwareParentOfDeclContext(DC);
17253       --FSIndex;
17254     }
17255   }
17256 
17257 
17258   // If the variable is declared in the current context, there is no need to
17259   // capture it.
17260   if (VarDC == DC) return true;
17261 
17262   // Capture global variables if it is required to use private copy of this
17263   // variable.
17264   bool IsGlobal = !Var->hasLocalStorage();
17265   if (IsGlobal &&
17266       !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true,
17267                                                 MaxFunctionScopesIndex)))
17268     return true;
17269   Var = Var->getCanonicalDecl();
17270 
17271   // Walk up the stack to determine whether we can capture the variable,
17272   // performing the "simple" checks that don't depend on type. We stop when
17273   // we've either hit the declared scope of the variable or find an existing
17274   // capture of that variable.  We start from the innermost capturing-entity
17275   // (the DC) and ensure that all intervening capturing-entities
17276   // (blocks/lambdas etc.) between the innermost capturer and the variable`s
17277   // declcontext can either capture the variable or have already captured
17278   // the variable.
17279   CaptureType = Var->getType();
17280   DeclRefType = CaptureType.getNonReferenceType();
17281   bool Nested = false;
17282   bool Explicit = (Kind != TryCapture_Implicit);
17283   unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
17284   do {
17285     // Only block literals, captured statements, and lambda expressions can
17286     // capture; other scopes don't work.
17287     DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
17288                                                               ExprLoc,
17289                                                               BuildAndDiagnose,
17290                                                               *this);
17291     // We need to check for the parent *first* because, if we *have*
17292     // private-captured a global variable, we need to recursively capture it in
17293     // intermediate blocks, lambdas, etc.
17294     if (!ParentDC) {
17295       if (IsGlobal) {
17296         FunctionScopesIndex = MaxFunctionScopesIndex - 1;
17297         break;
17298       }
17299       return true;
17300     }
17301 
17302     FunctionScopeInfo  *FSI = FunctionScopes[FunctionScopesIndex];
17303     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
17304 
17305 
17306     // Check whether we've already captured it.
17307     if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
17308                                              DeclRefType)) {
17309       CSI->getCapture(Var).markUsed(BuildAndDiagnose);
17310       break;
17311     }
17312     // If we are instantiating a generic lambda call operator body,
17313     // we do not want to capture new variables.  What was captured
17314     // during either a lambdas transformation or initial parsing
17315     // should be used.
17316     if (isGenericLambdaCallOperatorSpecialization(DC)) {
17317       if (BuildAndDiagnose) {
17318         LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
17319         if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
17320           Diag(ExprLoc, diag::err_lambda_impcap) << Var;
17321           Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17322           Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
17323         } else
17324           diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
17325       }
17326       return true;
17327     }
17328 
17329     // Try to capture variable-length arrays types.
17330     if (Var->getType()->isVariablyModifiedType()) {
17331       // We're going to walk down into the type and look for VLA
17332       // expressions.
17333       QualType QTy = Var->getType();
17334       if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
17335         QTy = PVD->getOriginalType();
17336       captureVariablyModifiedType(Context, QTy, CSI);
17337     }
17338 
17339     if (getLangOpts().OpenMP) {
17340       if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
17341         // OpenMP private variables should not be captured in outer scope, so
17342         // just break here. Similarly, global variables that are captured in a
17343         // target region should not be captured outside the scope of the region.
17344         if (RSI->CapRegionKind == CR_OpenMP) {
17345           OpenMPClauseKind IsOpenMPPrivateDecl = isOpenMPPrivateDecl(
17346               Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel);
17347           // If the variable is private (i.e. not captured) and has variably
17348           // modified type, we still need to capture the type for correct
17349           // codegen in all regions, associated with the construct. Currently,
17350           // it is captured in the innermost captured region only.
17351           if (IsOpenMPPrivateDecl != OMPC_unknown &&
17352               Var->getType()->isVariablyModifiedType()) {
17353             QualType QTy = Var->getType();
17354             if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
17355               QTy = PVD->getOriginalType();
17356             for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel);
17357                  I < E; ++I) {
17358               auto *OuterRSI = cast<CapturedRegionScopeInfo>(
17359                   FunctionScopes[FunctionScopesIndex - I]);
17360               assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel &&
17361                      "Wrong number of captured regions associated with the "
17362                      "OpenMP construct.");
17363               captureVariablyModifiedType(Context, QTy, OuterRSI);
17364             }
17365           }
17366           bool IsTargetCap =
17367               IsOpenMPPrivateDecl != OMPC_private &&
17368               isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel,
17369                                          RSI->OpenMPCaptureLevel);
17370           // Do not capture global if it is not privatized in outer regions.
17371           bool IsGlobalCap =
17372               IsGlobal && isOpenMPGlobalCapturedDecl(Var, RSI->OpenMPLevel,
17373                                                      RSI->OpenMPCaptureLevel);
17374 
17375           // When we detect target captures we are looking from inside the
17376           // target region, therefore we need to propagate the capture from the
17377           // enclosing region. Therefore, the capture is not initially nested.
17378           if (IsTargetCap)
17379             adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel);
17380 
17381           if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private ||
17382               (IsGlobal && !IsGlobalCap)) {
17383             Nested = !IsTargetCap;
17384             DeclRefType = DeclRefType.getUnqualifiedType();
17385             CaptureType = Context.getLValueReferenceType(DeclRefType);
17386             break;
17387           }
17388         }
17389       }
17390     }
17391     if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
17392       // No capture-default, and this is not an explicit capture
17393       // so cannot capture this variable.
17394       if (BuildAndDiagnose) {
17395         Diag(ExprLoc, diag::err_lambda_impcap) << Var;
17396         Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17397         if (cast<LambdaScopeInfo>(CSI)->Lambda)
17398           Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getBeginLoc(),
17399                diag::note_lambda_decl);
17400         // FIXME: If we error out because an outer lambda can not implicitly
17401         // capture a variable that an inner lambda explicitly captures, we
17402         // should have the inner lambda do the explicit capture - because
17403         // it makes for cleaner diagnostics later.  This would purely be done
17404         // so that the diagnostic does not misleadingly claim that a variable
17405         // can not be captured by a lambda implicitly even though it is captured
17406         // explicitly.  Suggestion:
17407         //  - create const bool VariableCaptureWasInitiallyExplicit = Explicit
17408         //    at the function head
17409         //  - cache the StartingDeclContext - this must be a lambda
17410         //  - captureInLambda in the innermost lambda the variable.
17411       }
17412       return true;
17413     }
17414 
17415     FunctionScopesIndex--;
17416     DC = ParentDC;
17417     Explicit = false;
17418   } while (!VarDC->Equals(DC));
17419 
17420   // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
17421   // computing the type of the capture at each step, checking type-specific
17422   // requirements, and adding captures if requested.
17423   // If the variable had already been captured previously, we start capturing
17424   // at the lambda nested within that one.
17425   bool Invalid = false;
17426   for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
17427        ++I) {
17428     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
17429 
17430     // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
17431     // certain types of variables (unnamed, variably modified types etc.)
17432     // so check for eligibility.
17433     if (!Invalid)
17434       Invalid =
17435           !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this);
17436 
17437     // After encountering an error, if we're actually supposed to capture, keep
17438     // capturing in nested contexts to suppress any follow-on diagnostics.
17439     if (Invalid && !BuildAndDiagnose)
17440       return true;
17441 
17442     if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
17443       Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
17444                                DeclRefType, Nested, *this, Invalid);
17445       Nested = true;
17446     } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
17447       Invalid = !captureInCapturedRegion(RSI, Var, ExprLoc, BuildAndDiagnose,
17448                                          CaptureType, DeclRefType, Nested,
17449                                          *this, Invalid);
17450       Nested = true;
17451     } else {
17452       LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
17453       Invalid =
17454           !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
17455                            DeclRefType, Nested, Kind, EllipsisLoc,
17456                            /*IsTopScope*/ I == N - 1, *this, Invalid);
17457       Nested = true;
17458     }
17459 
17460     if (Invalid && !BuildAndDiagnose)
17461       return true;
17462   }
17463   return Invalid;
17464 }
17465 
17466 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
17467                               TryCaptureKind Kind, SourceLocation EllipsisLoc) {
17468   QualType CaptureType;
17469   QualType DeclRefType;
17470   return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
17471                             /*BuildAndDiagnose=*/true, CaptureType,
17472                             DeclRefType, nullptr);
17473 }
17474 
17475 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
17476   QualType CaptureType;
17477   QualType DeclRefType;
17478   return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
17479                              /*BuildAndDiagnose=*/false, CaptureType,
17480                              DeclRefType, nullptr);
17481 }
17482 
17483 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
17484   QualType CaptureType;
17485   QualType DeclRefType;
17486 
17487   // Determine whether we can capture this variable.
17488   if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
17489                          /*BuildAndDiagnose=*/false, CaptureType,
17490                          DeclRefType, nullptr))
17491     return QualType();
17492 
17493   return DeclRefType;
17494 }
17495 
17496 namespace {
17497 // Helper to copy the template arguments from a DeclRefExpr or MemberExpr.
17498 // The produced TemplateArgumentListInfo* points to data stored within this
17499 // object, so should only be used in contexts where the pointer will not be
17500 // used after the CopiedTemplateArgs object is destroyed.
17501 class CopiedTemplateArgs {
17502   bool HasArgs;
17503   TemplateArgumentListInfo TemplateArgStorage;
17504 public:
17505   template<typename RefExpr>
17506   CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) {
17507     if (HasArgs)
17508       E->copyTemplateArgumentsInto(TemplateArgStorage);
17509   }
17510   operator TemplateArgumentListInfo*()
17511 #ifdef __has_cpp_attribute
17512 #if __has_cpp_attribute(clang::lifetimebound)
17513   [[clang::lifetimebound]]
17514 #endif
17515 #endif
17516   {
17517     return HasArgs ? &TemplateArgStorage : nullptr;
17518   }
17519 };
17520 }
17521 
17522 /// Walk the set of potential results of an expression and mark them all as
17523 /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason.
17524 ///
17525 /// \return A new expression if we found any potential results, ExprEmpty() if
17526 ///         not, and ExprError() if we diagnosed an error.
17527 static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E,
17528                                                       NonOdrUseReason NOUR) {
17529   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
17530   // an object that satisfies the requirements for appearing in a
17531   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
17532   // is immediately applied."  This function handles the lvalue-to-rvalue
17533   // conversion part.
17534   //
17535   // If we encounter a node that claims to be an odr-use but shouldn't be, we
17536   // transform it into the relevant kind of non-odr-use node and rebuild the
17537   // tree of nodes leading to it.
17538   //
17539   // This is a mini-TreeTransform that only transforms a restricted subset of
17540   // nodes (and only certain operands of them).
17541 
17542   // Rebuild a subexpression.
17543   auto Rebuild = [&](Expr *Sub) {
17544     return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR);
17545   };
17546 
17547   // Check whether a potential result satisfies the requirements of NOUR.
17548   auto IsPotentialResultOdrUsed = [&](NamedDecl *D) {
17549     // Any entity other than a VarDecl is always odr-used whenever it's named
17550     // in a potentially-evaluated expression.
17551     auto *VD = dyn_cast<VarDecl>(D);
17552     if (!VD)
17553       return true;
17554 
17555     // C++2a [basic.def.odr]p4:
17556     //   A variable x whose name appears as a potentially-evalauted expression
17557     //   e is odr-used by e unless
17558     //   -- x is a reference that is usable in constant expressions, or
17559     //   -- x is a variable of non-reference type that is usable in constant
17560     //      expressions and has no mutable subobjects, and e is an element of
17561     //      the set of potential results of an expression of
17562     //      non-volatile-qualified non-class type to which the lvalue-to-rvalue
17563     //      conversion is applied, or
17564     //   -- x is a variable of non-reference type, and e is an element of the
17565     //      set of potential results of a discarded-value expression to which
17566     //      the lvalue-to-rvalue conversion is not applied
17567     //
17568     // We check the first bullet and the "potentially-evaluated" condition in
17569     // BuildDeclRefExpr. We check the type requirements in the second bullet
17570     // in CheckLValueToRValueConversionOperand below.
17571     switch (NOUR) {
17572     case NOUR_None:
17573     case NOUR_Unevaluated:
17574       llvm_unreachable("unexpected non-odr-use-reason");
17575 
17576     case NOUR_Constant:
17577       // Constant references were handled when they were built.
17578       if (VD->getType()->isReferenceType())
17579         return true;
17580       if (auto *RD = VD->getType()->getAsCXXRecordDecl())
17581         if (RD->hasMutableFields())
17582           return true;
17583       if (!VD->isUsableInConstantExpressions(S.Context))
17584         return true;
17585       break;
17586 
17587     case NOUR_Discarded:
17588       if (VD->getType()->isReferenceType())
17589         return true;
17590       break;
17591     }
17592     return false;
17593   };
17594 
17595   // Mark that this expression does not constitute an odr-use.
17596   auto MarkNotOdrUsed = [&] {
17597     S.MaybeODRUseExprs.remove(E);
17598     if (LambdaScopeInfo *LSI = S.getCurLambda())
17599       LSI->markVariableExprAsNonODRUsed(E);
17600   };
17601 
17602   // C++2a [basic.def.odr]p2:
17603   //   The set of potential results of an expression e is defined as follows:
17604   switch (E->getStmtClass()) {
17605   //   -- If e is an id-expression, ...
17606   case Expr::DeclRefExprClass: {
17607     auto *DRE = cast<DeclRefExpr>(E);
17608     if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl()))
17609       break;
17610 
17611     // Rebuild as a non-odr-use DeclRefExpr.
17612     MarkNotOdrUsed();
17613     return DeclRefExpr::Create(
17614         S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(),
17615         DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(),
17616         DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(),
17617         DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR);
17618   }
17619 
17620   case Expr::FunctionParmPackExprClass: {
17621     auto *FPPE = cast<FunctionParmPackExpr>(E);
17622     // If any of the declarations in the pack is odr-used, then the expression
17623     // as a whole constitutes an odr-use.
17624     for (VarDecl *D : *FPPE)
17625       if (IsPotentialResultOdrUsed(D))
17626         return ExprEmpty();
17627 
17628     // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice,
17629     // nothing cares about whether we marked this as an odr-use, but it might
17630     // be useful for non-compiler tools.
17631     MarkNotOdrUsed();
17632     break;
17633   }
17634 
17635   //   -- If e is a subscripting operation with an array operand...
17636   case Expr::ArraySubscriptExprClass: {
17637     auto *ASE = cast<ArraySubscriptExpr>(E);
17638     Expr *OldBase = ASE->getBase()->IgnoreImplicit();
17639     if (!OldBase->getType()->isArrayType())
17640       break;
17641     ExprResult Base = Rebuild(OldBase);
17642     if (!Base.isUsable())
17643       return Base;
17644     Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS();
17645     Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS();
17646     SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored.
17647     return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS,
17648                                      ASE->getRBracketLoc());
17649   }
17650 
17651   case Expr::MemberExprClass: {
17652     auto *ME = cast<MemberExpr>(E);
17653     // -- If e is a class member access expression [...] naming a non-static
17654     //    data member...
17655     if (isa<FieldDecl>(ME->getMemberDecl())) {
17656       ExprResult Base = Rebuild(ME->getBase());
17657       if (!Base.isUsable())
17658         return Base;
17659       return MemberExpr::Create(
17660           S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(),
17661           ME->getQualifierLoc(), ME->getTemplateKeywordLoc(),
17662           ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(),
17663           CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(),
17664           ME->getObjectKind(), ME->isNonOdrUse());
17665     }
17666 
17667     if (ME->getMemberDecl()->isCXXInstanceMember())
17668       break;
17669 
17670     // -- If e is a class member access expression naming a static data member,
17671     //    ...
17672     if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl()))
17673       break;
17674 
17675     // Rebuild as a non-odr-use MemberExpr.
17676     MarkNotOdrUsed();
17677     return MemberExpr::Create(
17678         S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(),
17679         ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(),
17680         ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME),
17681         ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR);
17682     return ExprEmpty();
17683   }
17684 
17685   case Expr::BinaryOperatorClass: {
17686     auto *BO = cast<BinaryOperator>(E);
17687     Expr *LHS = BO->getLHS();
17688     Expr *RHS = BO->getRHS();
17689     // -- If e is a pointer-to-member expression of the form e1 .* e2 ...
17690     if (BO->getOpcode() == BO_PtrMemD) {
17691       ExprResult Sub = Rebuild(LHS);
17692       if (!Sub.isUsable())
17693         return Sub;
17694       LHS = Sub.get();
17695     //   -- If e is a comma expression, ...
17696     } else if (BO->getOpcode() == BO_Comma) {
17697       ExprResult Sub = Rebuild(RHS);
17698       if (!Sub.isUsable())
17699         return Sub;
17700       RHS = Sub.get();
17701     } else {
17702       break;
17703     }
17704     return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(),
17705                         LHS, RHS);
17706   }
17707 
17708   //   -- If e has the form (e1)...
17709   case Expr::ParenExprClass: {
17710     auto *PE = cast<ParenExpr>(E);
17711     ExprResult Sub = Rebuild(PE->getSubExpr());
17712     if (!Sub.isUsable())
17713       return Sub;
17714     return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get());
17715   }
17716 
17717   //   -- If e is a glvalue conditional expression, ...
17718   // We don't apply this to a binary conditional operator. FIXME: Should we?
17719   case Expr::ConditionalOperatorClass: {
17720     auto *CO = cast<ConditionalOperator>(E);
17721     ExprResult LHS = Rebuild(CO->getLHS());
17722     if (LHS.isInvalid())
17723       return ExprError();
17724     ExprResult RHS = Rebuild(CO->getRHS());
17725     if (RHS.isInvalid())
17726       return ExprError();
17727     if (!LHS.isUsable() && !RHS.isUsable())
17728       return ExprEmpty();
17729     if (!LHS.isUsable())
17730       LHS = CO->getLHS();
17731     if (!RHS.isUsable())
17732       RHS = CO->getRHS();
17733     return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(),
17734                                 CO->getCond(), LHS.get(), RHS.get());
17735   }
17736 
17737   // [Clang extension]
17738   //   -- If e has the form __extension__ e1...
17739   case Expr::UnaryOperatorClass: {
17740     auto *UO = cast<UnaryOperator>(E);
17741     if (UO->getOpcode() != UO_Extension)
17742       break;
17743     ExprResult Sub = Rebuild(UO->getSubExpr());
17744     if (!Sub.isUsable())
17745       return Sub;
17746     return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension,
17747                           Sub.get());
17748   }
17749 
17750   // [Clang extension]
17751   //   -- If e has the form _Generic(...), the set of potential results is the
17752   //      union of the sets of potential results of the associated expressions.
17753   case Expr::GenericSelectionExprClass: {
17754     auto *GSE = cast<GenericSelectionExpr>(E);
17755 
17756     SmallVector<Expr *, 4> AssocExprs;
17757     bool AnyChanged = false;
17758     for (Expr *OrigAssocExpr : GSE->getAssocExprs()) {
17759       ExprResult AssocExpr = Rebuild(OrigAssocExpr);
17760       if (AssocExpr.isInvalid())
17761         return ExprError();
17762       if (AssocExpr.isUsable()) {
17763         AssocExprs.push_back(AssocExpr.get());
17764         AnyChanged = true;
17765       } else {
17766         AssocExprs.push_back(OrigAssocExpr);
17767       }
17768     }
17769 
17770     return AnyChanged ? S.CreateGenericSelectionExpr(
17771                             GSE->getGenericLoc(), GSE->getDefaultLoc(),
17772                             GSE->getRParenLoc(), GSE->getControllingExpr(),
17773                             GSE->getAssocTypeSourceInfos(), AssocExprs)
17774                       : ExprEmpty();
17775   }
17776 
17777   // [Clang extension]
17778   //   -- If e has the form __builtin_choose_expr(...), the set of potential
17779   //      results is the union of the sets of potential results of the
17780   //      second and third subexpressions.
17781   case Expr::ChooseExprClass: {
17782     auto *CE = cast<ChooseExpr>(E);
17783 
17784     ExprResult LHS = Rebuild(CE->getLHS());
17785     if (LHS.isInvalid())
17786       return ExprError();
17787 
17788     ExprResult RHS = Rebuild(CE->getLHS());
17789     if (RHS.isInvalid())
17790       return ExprError();
17791 
17792     if (!LHS.get() && !RHS.get())
17793       return ExprEmpty();
17794     if (!LHS.isUsable())
17795       LHS = CE->getLHS();
17796     if (!RHS.isUsable())
17797       RHS = CE->getRHS();
17798 
17799     return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(),
17800                              RHS.get(), CE->getRParenLoc());
17801   }
17802 
17803   // Step through non-syntactic nodes.
17804   case Expr::ConstantExprClass: {
17805     auto *CE = cast<ConstantExpr>(E);
17806     ExprResult Sub = Rebuild(CE->getSubExpr());
17807     if (!Sub.isUsable())
17808       return Sub;
17809     return ConstantExpr::Create(S.Context, Sub.get());
17810   }
17811 
17812   // We could mostly rely on the recursive rebuilding to rebuild implicit
17813   // casts, but not at the top level, so rebuild them here.
17814   case Expr::ImplicitCastExprClass: {
17815     auto *ICE = cast<ImplicitCastExpr>(E);
17816     // Only step through the narrow set of cast kinds we expect to encounter.
17817     // Anything else suggests we've left the region in which potential results
17818     // can be found.
17819     switch (ICE->getCastKind()) {
17820     case CK_NoOp:
17821     case CK_DerivedToBase:
17822     case CK_UncheckedDerivedToBase: {
17823       ExprResult Sub = Rebuild(ICE->getSubExpr());
17824       if (!Sub.isUsable())
17825         return Sub;
17826       CXXCastPath Path(ICE->path());
17827       return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(),
17828                                  ICE->getValueKind(), &Path);
17829     }
17830 
17831     default:
17832       break;
17833     }
17834     break;
17835   }
17836 
17837   default:
17838     break;
17839   }
17840 
17841   // Can't traverse through this node. Nothing to do.
17842   return ExprEmpty();
17843 }
17844 
17845 ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) {
17846   // Check whether the operand is or contains an object of non-trivial C union
17847   // type.
17848   if (E->getType().isVolatileQualified() &&
17849       (E->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
17850        E->getType().hasNonTrivialToPrimitiveCopyCUnion()))
17851     checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
17852                           Sema::NTCUC_LValueToRValueVolatile,
17853                           NTCUK_Destruct|NTCUK_Copy);
17854 
17855   // C++2a [basic.def.odr]p4:
17856   //   [...] an expression of non-volatile-qualified non-class type to which
17857   //   the lvalue-to-rvalue conversion is applied [...]
17858   if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>())
17859     return E;
17860 
17861   ExprResult Result =
17862       rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant);
17863   if (Result.isInvalid())
17864     return ExprError();
17865   return Result.get() ? Result : E;
17866 }
17867 
17868 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
17869   Res = CorrectDelayedTyposInExpr(Res);
17870 
17871   if (!Res.isUsable())
17872     return Res;
17873 
17874   // If a constant-expression is a reference to a variable where we delay
17875   // deciding whether it is an odr-use, just assume we will apply the
17876   // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
17877   // (a non-type template argument), we have special handling anyway.
17878   return CheckLValueToRValueConversionOperand(Res.get());
17879 }
17880 
17881 void Sema::CleanupVarDeclMarking() {
17882   // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
17883   // call.
17884   MaybeODRUseExprSet LocalMaybeODRUseExprs;
17885   std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs);
17886 
17887   for (Expr *E : LocalMaybeODRUseExprs) {
17888     if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
17889       MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()),
17890                          DRE->getLocation(), *this);
17891     } else if (auto *ME = dyn_cast<MemberExpr>(E)) {
17892       MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(),
17893                          *this);
17894     } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) {
17895       for (VarDecl *VD : *FP)
17896         MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this);
17897     } else {
17898       llvm_unreachable("Unexpected expression");
17899     }
17900   }
17901 
17902   assert(MaybeODRUseExprs.empty() &&
17903          "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?");
17904 }
17905 
17906 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
17907                                     VarDecl *Var, Expr *E) {
17908   assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||
17909           isa<FunctionParmPackExpr>(E)) &&
17910          "Invalid Expr argument to DoMarkVarDeclReferenced");
17911   Var->setReferenced();
17912 
17913   if (Var->isInvalidDecl())
17914     return;
17915 
17916   // Record a CUDA/HIP static device/constant variable if it is referenced
17917   // by host code. This is done conservatively, when the variable is referenced
17918   // in any of the following contexts:
17919   //   - a non-function context
17920   //   - a host function
17921   //   - a host device function
17922   // This also requires the reference of the static device/constant variable by
17923   // host code to be visible in the device compilation for the compiler to be
17924   // able to externalize the static device/constant variable.
17925   if (SemaRef.getASTContext().mayExternalizeStaticVar(Var)) {
17926     auto *CurContext = SemaRef.CurContext;
17927     if (!CurContext || !isa<FunctionDecl>(CurContext) ||
17928         cast<FunctionDecl>(CurContext)->hasAttr<CUDAHostAttr>() ||
17929         (!cast<FunctionDecl>(CurContext)->hasAttr<CUDADeviceAttr>() &&
17930          !cast<FunctionDecl>(CurContext)->hasAttr<CUDAGlobalAttr>()))
17931       SemaRef.getASTContext().CUDAStaticDeviceVarReferencedByHost.insert(Var);
17932   }
17933 
17934   auto *MSI = Var->getMemberSpecializationInfo();
17935   TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind()
17936                                        : Var->getTemplateSpecializationKind();
17937 
17938   OdrUseContext OdrUse = isOdrUseContext(SemaRef);
17939   bool UsableInConstantExpr =
17940       Var->mightBeUsableInConstantExpressions(SemaRef.Context);
17941 
17942   // C++20 [expr.const]p12:
17943   //   A variable [...] is needed for constant evaluation if it is [...] a
17944   //   variable whose name appears as a potentially constant evaluated
17945   //   expression that is either a contexpr variable or is of non-volatile
17946   //   const-qualified integral type or of reference type
17947   bool NeededForConstantEvaluation =
17948       isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr;
17949 
17950   bool NeedDefinition =
17951       OdrUse == OdrUseContext::Used || NeededForConstantEvaluation;
17952 
17953   assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
17954          "Can't instantiate a partial template specialization.");
17955 
17956   // If this might be a member specialization of a static data member, check
17957   // the specialization is visible. We already did the checks for variable
17958   // template specializations when we created them.
17959   if (NeedDefinition && TSK != TSK_Undeclared &&
17960       !isa<VarTemplateSpecializationDecl>(Var))
17961     SemaRef.checkSpecializationVisibility(Loc, Var);
17962 
17963   // Perform implicit instantiation of static data members, static data member
17964   // templates of class templates, and variable template specializations. Delay
17965   // instantiations of variable templates, except for those that could be used
17966   // in a constant expression.
17967   if (NeedDefinition && isTemplateInstantiation(TSK)) {
17968     // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
17969     // instantiation declaration if a variable is usable in a constant
17970     // expression (among other cases).
17971     bool TryInstantiating =
17972         TSK == TSK_ImplicitInstantiation ||
17973         (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
17974 
17975     if (TryInstantiating) {
17976       SourceLocation PointOfInstantiation =
17977           MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation();
17978       bool FirstInstantiation = PointOfInstantiation.isInvalid();
17979       if (FirstInstantiation) {
17980         PointOfInstantiation = Loc;
17981         if (MSI)
17982           MSI->setPointOfInstantiation(PointOfInstantiation);
17983         else
17984           Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
17985       }
17986 
17987       if (UsableInConstantExpr) {
17988         // Do not defer instantiations of variables that could be used in a
17989         // constant expression.
17990         SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] {
17991           SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
17992         });
17993       } else if (FirstInstantiation ||
17994                  isa<VarTemplateSpecializationDecl>(Var)) {
17995         // FIXME: For a specialization of a variable template, we don't
17996         // distinguish between "declaration and type implicitly instantiated"
17997         // and "implicit instantiation of definition requested", so we have
17998         // no direct way to avoid enqueueing the pending instantiation
17999         // multiple times.
18000         SemaRef.PendingInstantiations
18001             .push_back(std::make_pair(Var, PointOfInstantiation));
18002       }
18003     }
18004   }
18005 
18006   // C++2a [basic.def.odr]p4:
18007   //   A variable x whose name appears as a potentially-evaluated expression e
18008   //   is odr-used by e unless
18009   //   -- x is a reference that is usable in constant expressions
18010   //   -- x is a variable of non-reference type that is usable in constant
18011   //      expressions and has no mutable subobjects [FIXME], and e is an
18012   //      element of the set of potential results of an expression of
18013   //      non-volatile-qualified non-class type to which the lvalue-to-rvalue
18014   //      conversion is applied
18015   //   -- x is a variable of non-reference type, and e is an element of the set
18016   //      of potential results of a discarded-value expression to which the
18017   //      lvalue-to-rvalue conversion is not applied [FIXME]
18018   //
18019   // We check the first part of the second bullet here, and
18020   // Sema::CheckLValueToRValueConversionOperand deals with the second part.
18021   // FIXME: To get the third bullet right, we need to delay this even for
18022   // variables that are not usable in constant expressions.
18023 
18024   // If we already know this isn't an odr-use, there's nothing more to do.
18025   if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E))
18026     if (DRE->isNonOdrUse())
18027       return;
18028   if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E))
18029     if (ME->isNonOdrUse())
18030       return;
18031 
18032   switch (OdrUse) {
18033   case OdrUseContext::None:
18034     assert((!E || isa<FunctionParmPackExpr>(E)) &&
18035            "missing non-odr-use marking for unevaluated decl ref");
18036     break;
18037 
18038   case OdrUseContext::FormallyOdrUsed:
18039     // FIXME: Ignoring formal odr-uses results in incorrect lambda capture
18040     // behavior.
18041     break;
18042 
18043   case OdrUseContext::Used:
18044     // If we might later find that this expression isn't actually an odr-use,
18045     // delay the marking.
18046     if (E && Var->isUsableInConstantExpressions(SemaRef.Context))
18047       SemaRef.MaybeODRUseExprs.insert(E);
18048     else
18049       MarkVarDeclODRUsed(Var, Loc, SemaRef);
18050     break;
18051 
18052   case OdrUseContext::Dependent:
18053     // If this is a dependent context, we don't need to mark variables as
18054     // odr-used, but we may still need to track them for lambda capture.
18055     // FIXME: Do we also need to do this inside dependent typeid expressions
18056     // (which are modeled as unevaluated at this point)?
18057     const bool RefersToEnclosingScope =
18058         (SemaRef.CurContext != Var->getDeclContext() &&
18059          Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
18060     if (RefersToEnclosingScope) {
18061       LambdaScopeInfo *const LSI =
18062           SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
18063       if (LSI && (!LSI->CallOperator ||
18064                   !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
18065         // If a variable could potentially be odr-used, defer marking it so
18066         // until we finish analyzing the full expression for any
18067         // lvalue-to-rvalue
18068         // or discarded value conversions that would obviate odr-use.
18069         // Add it to the list of potential captures that will be analyzed
18070         // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
18071         // unless the variable is a reference that was initialized by a constant
18072         // expression (this will never need to be captured or odr-used).
18073         //
18074         // FIXME: We can simplify this a lot after implementing P0588R1.
18075         assert(E && "Capture variable should be used in an expression.");
18076         if (!Var->getType()->isReferenceType() ||
18077             !Var->isUsableInConstantExpressions(SemaRef.Context))
18078           LSI->addPotentialCapture(E->IgnoreParens());
18079       }
18080     }
18081     break;
18082   }
18083 }
18084 
18085 /// Mark a variable referenced, and check whether it is odr-used
18086 /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
18087 /// used directly for normal expressions referring to VarDecl.
18088 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
18089   DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
18090 }
18091 
18092 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
18093                                Decl *D, Expr *E, bool MightBeOdrUse) {
18094   if (SemaRef.isInOpenMPDeclareTargetContext())
18095     SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
18096 
18097   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
18098     DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
18099     return;
18100   }
18101 
18102   SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
18103 
18104   // If this is a call to a method via a cast, also mark the method in the
18105   // derived class used in case codegen can devirtualize the call.
18106   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
18107   if (!ME)
18108     return;
18109   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
18110   if (!MD)
18111     return;
18112   // Only attempt to devirtualize if this is truly a virtual call.
18113   bool IsVirtualCall = MD->isVirtual() &&
18114                           ME->performsVirtualDispatch(SemaRef.getLangOpts());
18115   if (!IsVirtualCall)
18116     return;
18117 
18118   // If it's possible to devirtualize the call, mark the called function
18119   // referenced.
18120   CXXMethodDecl *DM = MD->getDevirtualizedMethod(
18121       ME->getBase(), SemaRef.getLangOpts().AppleKext);
18122   if (DM)
18123     SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
18124 }
18125 
18126 /// Perform reference-marking and odr-use handling for a DeclRefExpr.
18127 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) {
18128   // TODO: update this with DR# once a defect report is filed.
18129   // C++11 defect. The address of a pure member should not be an ODR use, even
18130   // if it's a qualified reference.
18131   bool OdrUse = true;
18132   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
18133     if (Method->isVirtual() &&
18134         !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
18135       OdrUse = false;
18136 
18137   if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl()))
18138     if (!isConstantEvaluated() && FD->isConsteval() &&
18139         !RebuildingImmediateInvocation)
18140       ExprEvalContexts.back().ReferenceToConsteval.insert(E);
18141   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
18142 }
18143 
18144 /// Perform reference-marking and odr-use handling for a MemberExpr.
18145 void Sema::MarkMemberReferenced(MemberExpr *E) {
18146   // C++11 [basic.def.odr]p2:
18147   //   A non-overloaded function whose name appears as a potentially-evaluated
18148   //   expression or a member of a set of candidate functions, if selected by
18149   //   overload resolution when referred to from a potentially-evaluated
18150   //   expression, is odr-used, unless it is a pure virtual function and its
18151   //   name is not explicitly qualified.
18152   bool MightBeOdrUse = true;
18153   if (E->performsVirtualDispatch(getLangOpts())) {
18154     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
18155       if (Method->isPure())
18156         MightBeOdrUse = false;
18157   }
18158   SourceLocation Loc =
18159       E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
18160   MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse);
18161 }
18162 
18163 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr.
18164 void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) {
18165   for (VarDecl *VD : *E)
18166     MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true);
18167 }
18168 
18169 /// Perform marking for a reference to an arbitrary declaration.  It
18170 /// marks the declaration referenced, and performs odr-use checking for
18171 /// functions and variables. This method should not be used when building a
18172 /// normal expression which refers to a variable.
18173 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
18174                                  bool MightBeOdrUse) {
18175   if (MightBeOdrUse) {
18176     if (auto *VD = dyn_cast<VarDecl>(D)) {
18177       MarkVariableReferenced(Loc, VD);
18178       return;
18179     }
18180   }
18181   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
18182     MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
18183     return;
18184   }
18185   D->setReferenced();
18186 }
18187 
18188 namespace {
18189   // Mark all of the declarations used by a type as referenced.
18190   // FIXME: Not fully implemented yet! We need to have a better understanding
18191   // of when we're entering a context we should not recurse into.
18192   // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
18193   // TreeTransforms rebuilding the type in a new context. Rather than
18194   // duplicating the TreeTransform logic, we should consider reusing it here.
18195   // Currently that causes problems when rebuilding LambdaExprs.
18196   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
18197     Sema &S;
18198     SourceLocation Loc;
18199 
18200   public:
18201     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
18202 
18203     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
18204 
18205     bool TraverseTemplateArgument(const TemplateArgument &Arg);
18206   };
18207 }
18208 
18209 bool MarkReferencedDecls::TraverseTemplateArgument(
18210     const TemplateArgument &Arg) {
18211   {
18212     // A non-type template argument is a constant-evaluated context.
18213     EnterExpressionEvaluationContext Evaluated(
18214         S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
18215     if (Arg.getKind() == TemplateArgument::Declaration) {
18216       if (Decl *D = Arg.getAsDecl())
18217         S.MarkAnyDeclReferenced(Loc, D, true);
18218     } else if (Arg.getKind() == TemplateArgument::Expression) {
18219       S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false);
18220     }
18221   }
18222 
18223   return Inherited::TraverseTemplateArgument(Arg);
18224 }
18225 
18226 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
18227   MarkReferencedDecls Marker(*this, Loc);
18228   Marker.TraverseType(T);
18229 }
18230 
18231 namespace {
18232 /// Helper class that marks all of the declarations referenced by
18233 /// potentially-evaluated subexpressions as "referenced".
18234 class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> {
18235 public:
18236   typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited;
18237   bool SkipLocalVariables;
18238 
18239   EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
18240       : Inherited(S), SkipLocalVariables(SkipLocalVariables) {}
18241 
18242   void visitUsedDecl(SourceLocation Loc, Decl *D) {
18243     S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D));
18244   }
18245 
18246   void VisitDeclRefExpr(DeclRefExpr *E) {
18247     // If we were asked not to visit local variables, don't.
18248     if (SkipLocalVariables) {
18249       if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
18250         if (VD->hasLocalStorage())
18251           return;
18252     }
18253     S.MarkDeclRefReferenced(E);
18254   }
18255 
18256   void VisitMemberExpr(MemberExpr *E) {
18257     S.MarkMemberReferenced(E);
18258     Visit(E->getBase());
18259   }
18260 };
18261 } // namespace
18262 
18263 /// Mark any declarations that appear within this expression or any
18264 /// potentially-evaluated subexpressions as "referenced".
18265 ///
18266 /// \param SkipLocalVariables If true, don't mark local variables as
18267 /// 'referenced'.
18268 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
18269                                             bool SkipLocalVariables) {
18270   EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
18271 }
18272 
18273 /// Emit a diagnostic that describes an effect on the run-time behavior
18274 /// of the program being compiled.
18275 ///
18276 /// This routine emits the given diagnostic when the code currently being
18277 /// type-checked is "potentially evaluated", meaning that there is a
18278 /// possibility that the code will actually be executable. Code in sizeof()
18279 /// expressions, code used only during overload resolution, etc., are not
18280 /// potentially evaluated. This routine will suppress such diagnostics or,
18281 /// in the absolutely nutty case of potentially potentially evaluated
18282 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
18283 /// later.
18284 ///
18285 /// This routine should be used for all diagnostics that describe the run-time
18286 /// behavior of a program, such as passing a non-POD value through an ellipsis.
18287 /// Failure to do so will likely result in spurious diagnostics or failures
18288 /// during overload resolution or within sizeof/alignof/typeof/typeid.
18289 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts,
18290                                const PartialDiagnostic &PD) {
18291   switch (ExprEvalContexts.back().Context) {
18292   case ExpressionEvaluationContext::Unevaluated:
18293   case ExpressionEvaluationContext::UnevaluatedList:
18294   case ExpressionEvaluationContext::UnevaluatedAbstract:
18295   case ExpressionEvaluationContext::DiscardedStatement:
18296     // The argument will never be evaluated, so don't complain.
18297     break;
18298 
18299   case ExpressionEvaluationContext::ConstantEvaluated:
18300     // Relevant diagnostics should be produced by constant evaluation.
18301     break;
18302 
18303   case ExpressionEvaluationContext::PotentiallyEvaluated:
18304   case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
18305     if (!Stmts.empty() && getCurFunctionOrMethodDecl()) {
18306       FunctionScopes.back()->PossiblyUnreachableDiags.
18307         push_back(sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
18308       return true;
18309     }
18310 
18311     // The initializer of a constexpr variable or of the first declaration of a
18312     // static data member is not syntactically a constant evaluated constant,
18313     // but nonetheless is always required to be a constant expression, so we
18314     // can skip diagnosing.
18315     // FIXME: Using the mangling context here is a hack.
18316     if (auto *VD = dyn_cast_or_null<VarDecl>(
18317             ExprEvalContexts.back().ManglingContextDecl)) {
18318       if (VD->isConstexpr() ||
18319           (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline()))
18320         break;
18321       // FIXME: For any other kind of variable, we should build a CFG for its
18322       // initializer and check whether the context in question is reachable.
18323     }
18324 
18325     Diag(Loc, PD);
18326     return true;
18327   }
18328 
18329   return false;
18330 }
18331 
18332 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
18333                                const PartialDiagnostic &PD) {
18334   return DiagRuntimeBehavior(
18335       Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD);
18336 }
18337 
18338 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
18339                                CallExpr *CE, FunctionDecl *FD) {
18340   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
18341     return false;
18342 
18343   // If we're inside a decltype's expression, don't check for a valid return
18344   // type or construct temporaries until we know whether this is the last call.
18345   if (ExprEvalContexts.back().ExprContext ==
18346       ExpressionEvaluationContextRecord::EK_Decltype) {
18347     ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
18348     return false;
18349   }
18350 
18351   class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
18352     FunctionDecl *FD;
18353     CallExpr *CE;
18354 
18355   public:
18356     CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
18357       : FD(FD), CE(CE) { }
18358 
18359     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
18360       if (!FD) {
18361         S.Diag(Loc, diag::err_call_incomplete_return)
18362           << T << CE->getSourceRange();
18363         return;
18364       }
18365 
18366       S.Diag(Loc, diag::err_call_function_incomplete_return)
18367           << CE->getSourceRange() << FD << T;
18368       S.Diag(FD->getLocation(), diag::note_entity_declared_at)
18369           << FD->getDeclName();
18370     }
18371   } Diagnoser(FD, CE);
18372 
18373   if (RequireCompleteType(Loc, ReturnType, Diagnoser))
18374     return true;
18375 
18376   return false;
18377 }
18378 
18379 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
18380 // will prevent this condition from triggering, which is what we want.
18381 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
18382   SourceLocation Loc;
18383 
18384   unsigned diagnostic = diag::warn_condition_is_assignment;
18385   bool IsOrAssign = false;
18386 
18387   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
18388     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
18389       return;
18390 
18391     IsOrAssign = Op->getOpcode() == BO_OrAssign;
18392 
18393     // Greylist some idioms by putting them into a warning subcategory.
18394     if (ObjCMessageExpr *ME
18395           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
18396       Selector Sel = ME->getSelector();
18397 
18398       // self = [<foo> init...]
18399       if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
18400         diagnostic = diag::warn_condition_is_idiomatic_assignment;
18401 
18402       // <foo> = [<bar> nextObject]
18403       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
18404         diagnostic = diag::warn_condition_is_idiomatic_assignment;
18405     }
18406 
18407     Loc = Op->getOperatorLoc();
18408   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
18409     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
18410       return;
18411 
18412     IsOrAssign = Op->getOperator() == OO_PipeEqual;
18413     Loc = Op->getOperatorLoc();
18414   } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
18415     return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
18416   else {
18417     // Not an assignment.
18418     return;
18419   }
18420 
18421   Diag(Loc, diagnostic) << E->getSourceRange();
18422 
18423   SourceLocation Open = E->getBeginLoc();
18424   SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
18425   Diag(Loc, diag::note_condition_assign_silence)
18426         << FixItHint::CreateInsertion(Open, "(")
18427         << FixItHint::CreateInsertion(Close, ")");
18428 
18429   if (IsOrAssign)
18430     Diag(Loc, diag::note_condition_or_assign_to_comparison)
18431       << FixItHint::CreateReplacement(Loc, "!=");
18432   else
18433     Diag(Loc, diag::note_condition_assign_to_comparison)
18434       << FixItHint::CreateReplacement(Loc, "==");
18435 }
18436 
18437 /// Redundant parentheses over an equality comparison can indicate
18438 /// that the user intended an assignment used as condition.
18439 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
18440   // Don't warn if the parens came from a macro.
18441   SourceLocation parenLoc = ParenE->getBeginLoc();
18442   if (parenLoc.isInvalid() || parenLoc.isMacroID())
18443     return;
18444   // Don't warn for dependent expressions.
18445   if (ParenE->isTypeDependent())
18446     return;
18447 
18448   Expr *E = ParenE->IgnoreParens();
18449 
18450   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
18451     if (opE->getOpcode() == BO_EQ &&
18452         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
18453                                                            == Expr::MLV_Valid) {
18454       SourceLocation Loc = opE->getOperatorLoc();
18455 
18456       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
18457       SourceRange ParenERange = ParenE->getSourceRange();
18458       Diag(Loc, diag::note_equality_comparison_silence)
18459         << FixItHint::CreateRemoval(ParenERange.getBegin())
18460         << FixItHint::CreateRemoval(ParenERange.getEnd());
18461       Diag(Loc, diag::note_equality_comparison_to_assign)
18462         << FixItHint::CreateReplacement(Loc, "=");
18463     }
18464 }
18465 
18466 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
18467                                        bool IsConstexpr) {
18468   DiagnoseAssignmentAsCondition(E);
18469   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
18470     DiagnoseEqualityWithExtraParens(parenE);
18471 
18472   ExprResult result = CheckPlaceholderExpr(E);
18473   if (result.isInvalid()) return ExprError();
18474   E = result.get();
18475 
18476   if (!E->isTypeDependent()) {
18477     if (getLangOpts().CPlusPlus)
18478       return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
18479 
18480     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
18481     if (ERes.isInvalid())
18482       return ExprError();
18483     E = ERes.get();
18484 
18485     QualType T = E->getType();
18486     if (!T->isScalarType()) { // C99 6.8.4.1p1
18487       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
18488         << T << E->getSourceRange();
18489       return ExprError();
18490     }
18491     CheckBoolLikeConversion(E, Loc);
18492   }
18493 
18494   return E;
18495 }
18496 
18497 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
18498                                            Expr *SubExpr, ConditionKind CK) {
18499   // Empty conditions are valid in for-statements.
18500   if (!SubExpr)
18501     return ConditionResult();
18502 
18503   ExprResult Cond;
18504   switch (CK) {
18505   case ConditionKind::Boolean:
18506     Cond = CheckBooleanCondition(Loc, SubExpr);
18507     break;
18508 
18509   case ConditionKind::ConstexprIf:
18510     Cond = CheckBooleanCondition(Loc, SubExpr, true);
18511     break;
18512 
18513   case ConditionKind::Switch:
18514     Cond = CheckSwitchCondition(Loc, SubExpr);
18515     break;
18516   }
18517   if (Cond.isInvalid()) {
18518     Cond = CreateRecoveryExpr(SubExpr->getBeginLoc(), SubExpr->getEndLoc(),
18519                               {SubExpr});
18520     if (!Cond.get())
18521       return ConditionError();
18522   }
18523   // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
18524   FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
18525   if (!FullExpr.get())
18526     return ConditionError();
18527 
18528   return ConditionResult(*this, nullptr, FullExpr,
18529                          CK == ConditionKind::ConstexprIf);
18530 }
18531 
18532 namespace {
18533   /// A visitor for rebuilding a call to an __unknown_any expression
18534   /// to have an appropriate type.
18535   struct RebuildUnknownAnyFunction
18536     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
18537 
18538     Sema &S;
18539 
18540     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
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_call)
18548         << E->getSourceRange();
18549       return ExprError();
18550     }
18551 
18552     /// Rebuild an expression which simply semantically wraps another
18553     /// expression which it shares the type and value kind of.
18554     template <class T> ExprResult rebuildSugarExpr(T *E) {
18555       ExprResult SubResult = Visit(E->getSubExpr());
18556       if (SubResult.isInvalid()) return ExprError();
18557 
18558       Expr *SubExpr = SubResult.get();
18559       E->setSubExpr(SubExpr);
18560       E->setType(SubExpr->getType());
18561       E->setValueKind(SubExpr->getValueKind());
18562       assert(E->getObjectKind() == OK_Ordinary);
18563       return E;
18564     }
18565 
18566     ExprResult VisitParenExpr(ParenExpr *E) {
18567       return rebuildSugarExpr(E);
18568     }
18569 
18570     ExprResult VisitUnaryExtension(UnaryOperator *E) {
18571       return rebuildSugarExpr(E);
18572     }
18573 
18574     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
18575       ExprResult SubResult = Visit(E->getSubExpr());
18576       if (SubResult.isInvalid()) return ExprError();
18577 
18578       Expr *SubExpr = SubResult.get();
18579       E->setSubExpr(SubExpr);
18580       E->setType(S.Context.getPointerType(SubExpr->getType()));
18581       assert(E->getValueKind() == VK_RValue);
18582       assert(E->getObjectKind() == OK_Ordinary);
18583       return E;
18584     }
18585 
18586     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
18587       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
18588 
18589       E->setType(VD->getType());
18590 
18591       assert(E->getValueKind() == VK_RValue);
18592       if (S.getLangOpts().CPlusPlus &&
18593           !(isa<CXXMethodDecl>(VD) &&
18594             cast<CXXMethodDecl>(VD)->isInstance()))
18595         E->setValueKind(VK_LValue);
18596 
18597       return E;
18598     }
18599 
18600     ExprResult VisitMemberExpr(MemberExpr *E) {
18601       return resolveDecl(E, E->getMemberDecl());
18602     }
18603 
18604     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
18605       return resolveDecl(E, E->getDecl());
18606     }
18607   };
18608 }
18609 
18610 /// Given a function expression of unknown-any type, try to rebuild it
18611 /// to have a function type.
18612 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
18613   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
18614   if (Result.isInvalid()) return ExprError();
18615   return S.DefaultFunctionArrayConversion(Result.get());
18616 }
18617 
18618 namespace {
18619   /// A visitor for rebuilding an expression of type __unknown_anytype
18620   /// into one which resolves the type directly on the referring
18621   /// expression.  Strict preservation of the original source
18622   /// structure is not a goal.
18623   struct RebuildUnknownAnyExpr
18624     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
18625 
18626     Sema &S;
18627 
18628     /// The current destination type.
18629     QualType DestType;
18630 
18631     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
18632       : S(S), DestType(CastType) {}
18633 
18634     ExprResult VisitStmt(Stmt *S) {
18635       llvm_unreachable("unexpected statement!");
18636     }
18637 
18638     ExprResult VisitExpr(Expr *E) {
18639       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
18640         << E->getSourceRange();
18641       return ExprError();
18642     }
18643 
18644     ExprResult VisitCallExpr(CallExpr *E);
18645     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
18646 
18647     /// Rebuild an expression which simply semantically wraps another
18648     /// expression which it shares the type and value kind of.
18649     template <class T> ExprResult rebuildSugarExpr(T *E) {
18650       ExprResult SubResult = Visit(E->getSubExpr());
18651       if (SubResult.isInvalid()) return ExprError();
18652       Expr *SubExpr = SubResult.get();
18653       E->setSubExpr(SubExpr);
18654       E->setType(SubExpr->getType());
18655       E->setValueKind(SubExpr->getValueKind());
18656       assert(E->getObjectKind() == OK_Ordinary);
18657       return E;
18658     }
18659 
18660     ExprResult VisitParenExpr(ParenExpr *E) {
18661       return rebuildSugarExpr(E);
18662     }
18663 
18664     ExprResult VisitUnaryExtension(UnaryOperator *E) {
18665       return rebuildSugarExpr(E);
18666     }
18667 
18668     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
18669       const PointerType *Ptr = DestType->getAs<PointerType>();
18670       if (!Ptr) {
18671         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
18672           << E->getSourceRange();
18673         return ExprError();
18674       }
18675 
18676       if (isa<CallExpr>(E->getSubExpr())) {
18677         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
18678           << E->getSourceRange();
18679         return ExprError();
18680       }
18681 
18682       assert(E->getValueKind() == VK_RValue);
18683       assert(E->getObjectKind() == OK_Ordinary);
18684       E->setType(DestType);
18685 
18686       // Build the sub-expression as if it were an object of the pointee type.
18687       DestType = Ptr->getPointeeType();
18688       ExprResult SubResult = Visit(E->getSubExpr());
18689       if (SubResult.isInvalid()) return ExprError();
18690       E->setSubExpr(SubResult.get());
18691       return E;
18692     }
18693 
18694     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
18695 
18696     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
18697 
18698     ExprResult VisitMemberExpr(MemberExpr *E) {
18699       return resolveDecl(E, E->getMemberDecl());
18700     }
18701 
18702     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
18703       return resolveDecl(E, E->getDecl());
18704     }
18705   };
18706 }
18707 
18708 /// Rebuilds a call expression which yielded __unknown_anytype.
18709 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
18710   Expr *CalleeExpr = E->getCallee();
18711 
18712   enum FnKind {
18713     FK_MemberFunction,
18714     FK_FunctionPointer,
18715     FK_BlockPointer
18716   };
18717 
18718   FnKind Kind;
18719   QualType CalleeType = CalleeExpr->getType();
18720   if (CalleeType == S.Context.BoundMemberTy) {
18721     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
18722     Kind = FK_MemberFunction;
18723     CalleeType = Expr::findBoundMemberType(CalleeExpr);
18724   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
18725     CalleeType = Ptr->getPointeeType();
18726     Kind = FK_FunctionPointer;
18727   } else {
18728     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
18729     Kind = FK_BlockPointer;
18730   }
18731   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
18732 
18733   // Verify that this is a legal result type of a function.
18734   if (DestType->isArrayType() || DestType->isFunctionType()) {
18735     unsigned diagID = diag::err_func_returning_array_function;
18736     if (Kind == FK_BlockPointer)
18737       diagID = diag::err_block_returning_array_function;
18738 
18739     S.Diag(E->getExprLoc(), diagID)
18740       << DestType->isFunctionType() << DestType;
18741     return ExprError();
18742   }
18743 
18744   // Otherwise, go ahead and set DestType as the call's result.
18745   E->setType(DestType.getNonLValueExprType(S.Context));
18746   E->setValueKind(Expr::getValueKindForType(DestType));
18747   assert(E->getObjectKind() == OK_Ordinary);
18748 
18749   // Rebuild the function type, replacing the result type with DestType.
18750   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
18751   if (Proto) {
18752     // __unknown_anytype(...) is a special case used by the debugger when
18753     // it has no idea what a function's signature is.
18754     //
18755     // We want to build this call essentially under the K&R
18756     // unprototyped rules, but making a FunctionNoProtoType in C++
18757     // would foul up all sorts of assumptions.  However, we cannot
18758     // simply pass all arguments as variadic arguments, nor can we
18759     // portably just call the function under a non-variadic type; see
18760     // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
18761     // However, it turns out that in practice it is generally safe to
18762     // call a function declared as "A foo(B,C,D);" under the prototype
18763     // "A foo(B,C,D,...);".  The only known exception is with the
18764     // Windows ABI, where any variadic function is implicitly cdecl
18765     // regardless of its normal CC.  Therefore we change the parameter
18766     // types to match the types of the arguments.
18767     //
18768     // This is a hack, but it is far superior to moving the
18769     // corresponding target-specific code from IR-gen to Sema/AST.
18770 
18771     ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
18772     SmallVector<QualType, 8> ArgTypes;
18773     if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
18774       ArgTypes.reserve(E->getNumArgs());
18775       for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
18776         Expr *Arg = E->getArg(i);
18777         QualType ArgType = Arg->getType();
18778         if (E->isLValue()) {
18779           ArgType = S.Context.getLValueReferenceType(ArgType);
18780         } else if (E->isXValue()) {
18781           ArgType = S.Context.getRValueReferenceType(ArgType);
18782         }
18783         ArgTypes.push_back(ArgType);
18784       }
18785       ParamTypes = ArgTypes;
18786     }
18787     DestType = S.Context.getFunctionType(DestType, ParamTypes,
18788                                          Proto->getExtProtoInfo());
18789   } else {
18790     DestType = S.Context.getFunctionNoProtoType(DestType,
18791                                                 FnType->getExtInfo());
18792   }
18793 
18794   // Rebuild the appropriate pointer-to-function type.
18795   switch (Kind) {
18796   case FK_MemberFunction:
18797     // Nothing to do.
18798     break;
18799 
18800   case FK_FunctionPointer:
18801     DestType = S.Context.getPointerType(DestType);
18802     break;
18803 
18804   case FK_BlockPointer:
18805     DestType = S.Context.getBlockPointerType(DestType);
18806     break;
18807   }
18808 
18809   // Finally, we can recurse.
18810   ExprResult CalleeResult = Visit(CalleeExpr);
18811   if (!CalleeResult.isUsable()) return ExprError();
18812   E->setCallee(CalleeResult.get());
18813 
18814   // Bind a temporary if necessary.
18815   return S.MaybeBindToTemporary(E);
18816 }
18817 
18818 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
18819   // Verify that this is a legal result type of a call.
18820   if (DestType->isArrayType() || DestType->isFunctionType()) {
18821     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
18822       << DestType->isFunctionType() << DestType;
18823     return ExprError();
18824   }
18825 
18826   // Rewrite the method result type if available.
18827   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
18828     assert(Method->getReturnType() == S.Context.UnknownAnyTy);
18829     Method->setReturnType(DestType);
18830   }
18831 
18832   // Change the type of the message.
18833   E->setType(DestType.getNonReferenceType());
18834   E->setValueKind(Expr::getValueKindForType(DestType));
18835 
18836   return S.MaybeBindToTemporary(E);
18837 }
18838 
18839 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
18840   // The only case we should ever see here is a function-to-pointer decay.
18841   if (E->getCastKind() == CK_FunctionToPointerDecay) {
18842     assert(E->getValueKind() == VK_RValue);
18843     assert(E->getObjectKind() == OK_Ordinary);
18844 
18845     E->setType(DestType);
18846 
18847     // Rebuild the sub-expression as the pointee (function) type.
18848     DestType = DestType->castAs<PointerType>()->getPointeeType();
18849 
18850     ExprResult Result = Visit(E->getSubExpr());
18851     if (!Result.isUsable()) return ExprError();
18852 
18853     E->setSubExpr(Result.get());
18854     return E;
18855   } else if (E->getCastKind() == CK_LValueToRValue) {
18856     assert(E->getValueKind() == VK_RValue);
18857     assert(E->getObjectKind() == OK_Ordinary);
18858 
18859     assert(isa<BlockPointerType>(E->getType()));
18860 
18861     E->setType(DestType);
18862 
18863     // The sub-expression has to be a lvalue reference, so rebuild it as such.
18864     DestType = S.Context.getLValueReferenceType(DestType);
18865 
18866     ExprResult Result = Visit(E->getSubExpr());
18867     if (!Result.isUsable()) return ExprError();
18868 
18869     E->setSubExpr(Result.get());
18870     return E;
18871   } else {
18872     llvm_unreachable("Unhandled cast type!");
18873   }
18874 }
18875 
18876 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
18877   ExprValueKind ValueKind = VK_LValue;
18878   QualType Type = DestType;
18879 
18880   // We know how to make this work for certain kinds of decls:
18881 
18882   //  - functions
18883   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
18884     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
18885       DestType = Ptr->getPointeeType();
18886       ExprResult Result = resolveDecl(E, VD);
18887       if (Result.isInvalid()) return ExprError();
18888       return S.ImpCastExprToType(Result.get(), Type,
18889                                  CK_FunctionToPointerDecay, VK_RValue);
18890     }
18891 
18892     if (!Type->isFunctionType()) {
18893       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
18894         << VD << E->getSourceRange();
18895       return ExprError();
18896     }
18897     if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
18898       // We must match the FunctionDecl's type to the hack introduced in
18899       // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
18900       // type. See the lengthy commentary in that routine.
18901       QualType FDT = FD->getType();
18902       const FunctionType *FnType = FDT->castAs<FunctionType>();
18903       const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
18904       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
18905       if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
18906         SourceLocation Loc = FD->getLocation();
18907         FunctionDecl *NewFD = FunctionDecl::Create(
18908             S.Context, FD->getDeclContext(), Loc, Loc,
18909             FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(),
18910             SC_None, false /*isInlineSpecified*/, FD->hasPrototype(),
18911             /*ConstexprKind*/ CSK_unspecified);
18912 
18913         if (FD->getQualifier())
18914           NewFD->setQualifierInfo(FD->getQualifierLoc());
18915 
18916         SmallVector<ParmVarDecl*, 16> Params;
18917         for (const auto &AI : FT->param_types()) {
18918           ParmVarDecl *Param =
18919             S.BuildParmVarDeclForTypedef(FD, Loc, AI);
18920           Param->setScopeInfo(0, Params.size());
18921           Params.push_back(Param);
18922         }
18923         NewFD->setParams(Params);
18924         DRE->setDecl(NewFD);
18925         VD = DRE->getDecl();
18926       }
18927     }
18928 
18929     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
18930       if (MD->isInstance()) {
18931         ValueKind = VK_RValue;
18932         Type = S.Context.BoundMemberTy;
18933       }
18934 
18935     // Function references aren't l-values in C.
18936     if (!S.getLangOpts().CPlusPlus)
18937       ValueKind = VK_RValue;
18938 
18939   //  - variables
18940   } else if (isa<VarDecl>(VD)) {
18941     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
18942       Type = RefTy->getPointeeType();
18943     } else if (Type->isFunctionType()) {
18944       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
18945         << VD << E->getSourceRange();
18946       return ExprError();
18947     }
18948 
18949   //  - nothing else
18950   } else {
18951     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
18952       << VD << E->getSourceRange();
18953     return ExprError();
18954   }
18955 
18956   // Modifying the declaration like this is friendly to IR-gen but
18957   // also really dangerous.
18958   VD->setType(DestType);
18959   E->setType(Type);
18960   E->setValueKind(ValueKind);
18961   return E;
18962 }
18963 
18964 /// Check a cast of an unknown-any type.  We intentionally only
18965 /// trigger this for C-style casts.
18966 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
18967                                      Expr *CastExpr, CastKind &CastKind,
18968                                      ExprValueKind &VK, CXXCastPath &Path) {
18969   // The type we're casting to must be either void or complete.
18970   if (!CastType->isVoidType() &&
18971       RequireCompleteType(TypeRange.getBegin(), CastType,
18972                           diag::err_typecheck_cast_to_incomplete))
18973     return ExprError();
18974 
18975   // Rewrite the casted expression from scratch.
18976   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
18977   if (!result.isUsable()) return ExprError();
18978 
18979   CastExpr = result.get();
18980   VK = CastExpr->getValueKind();
18981   CastKind = CK_NoOp;
18982 
18983   return CastExpr;
18984 }
18985 
18986 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
18987   return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
18988 }
18989 
18990 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
18991                                     Expr *arg, QualType &paramType) {
18992   // If the syntactic form of the argument is not an explicit cast of
18993   // any sort, just do default argument promotion.
18994   ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
18995   if (!castArg) {
18996     ExprResult result = DefaultArgumentPromotion(arg);
18997     if (result.isInvalid()) return ExprError();
18998     paramType = result.get()->getType();
18999     return result;
19000   }
19001 
19002   // Otherwise, use the type that was written in the explicit cast.
19003   assert(!arg->hasPlaceholderType());
19004   paramType = castArg->getTypeAsWritten();
19005 
19006   // Copy-initialize a parameter of that type.
19007   InitializedEntity entity =
19008     InitializedEntity::InitializeParameter(Context, paramType,
19009                                            /*consumed*/ false);
19010   return PerformCopyInitialization(entity, callLoc, arg);
19011 }
19012 
19013 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
19014   Expr *orig = E;
19015   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
19016   while (true) {
19017     E = E->IgnoreParenImpCasts();
19018     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
19019       E = call->getCallee();
19020       diagID = diag::err_uncasted_call_of_unknown_any;
19021     } else {
19022       break;
19023     }
19024   }
19025 
19026   SourceLocation loc;
19027   NamedDecl *d;
19028   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
19029     loc = ref->getLocation();
19030     d = ref->getDecl();
19031   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
19032     loc = mem->getMemberLoc();
19033     d = mem->getMemberDecl();
19034   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
19035     diagID = diag::err_uncasted_call_of_unknown_any;
19036     loc = msg->getSelectorStartLoc();
19037     d = msg->getMethodDecl();
19038     if (!d) {
19039       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
19040         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
19041         << orig->getSourceRange();
19042       return ExprError();
19043     }
19044   } else {
19045     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
19046       << E->getSourceRange();
19047     return ExprError();
19048   }
19049 
19050   S.Diag(loc, diagID) << d << orig->getSourceRange();
19051 
19052   // Never recoverable.
19053   return ExprError();
19054 }
19055 
19056 /// Check for operands with placeholder types and complain if found.
19057 /// Returns ExprError() if there was an error and no recovery was possible.
19058 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
19059   if (!getLangOpts().CPlusPlus) {
19060     // C cannot handle TypoExpr nodes on either side of a binop because it
19061     // doesn't handle dependent types properly, so make sure any TypoExprs have
19062     // been dealt with before checking the operands.
19063     ExprResult Result = CorrectDelayedTyposInExpr(E);
19064     if (!Result.isUsable()) return ExprError();
19065     E = Result.get();
19066   }
19067 
19068   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
19069   if (!placeholderType) return E;
19070 
19071   switch (placeholderType->getKind()) {
19072 
19073   // Overloaded expressions.
19074   case BuiltinType::Overload: {
19075     // Try to resolve a single function template specialization.
19076     // This is obligatory.
19077     ExprResult Result = E;
19078     if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
19079       return Result;
19080 
19081     // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
19082     // leaves Result unchanged on failure.
19083     Result = E;
19084     if (resolveAndFixAddressOfSingleOverloadCandidate(Result))
19085       return Result;
19086 
19087     // If that failed, try to recover with a call.
19088     tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
19089                          /*complain*/ true);
19090     return Result;
19091   }
19092 
19093   // Bound member functions.
19094   case BuiltinType::BoundMember: {
19095     ExprResult result = E;
19096     const Expr *BME = E->IgnoreParens();
19097     PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
19098     // Try to give a nicer diagnostic if it is a bound member that we recognize.
19099     if (isa<CXXPseudoDestructorExpr>(BME)) {
19100       PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
19101     } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
19102       if (ME->getMemberNameInfo().getName().getNameKind() ==
19103           DeclarationName::CXXDestructorName)
19104         PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
19105     }
19106     tryToRecoverWithCall(result, PD,
19107                          /*complain*/ true);
19108     return result;
19109   }
19110 
19111   // ARC unbridged casts.
19112   case BuiltinType::ARCUnbridgedCast: {
19113     Expr *realCast = stripARCUnbridgedCast(E);
19114     diagnoseARCUnbridgedCast(realCast);
19115     return realCast;
19116   }
19117 
19118   // Expressions of unknown type.
19119   case BuiltinType::UnknownAny:
19120     return diagnoseUnknownAnyExpr(*this, E);
19121 
19122   // Pseudo-objects.
19123   case BuiltinType::PseudoObject:
19124     return checkPseudoObjectRValue(E);
19125 
19126   case BuiltinType::BuiltinFn: {
19127     // Accept __noop without parens by implicitly converting it to a call expr.
19128     auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
19129     if (DRE) {
19130       auto *FD = cast<FunctionDecl>(DRE->getDecl());
19131       if (FD->getBuiltinID() == Builtin::BI__noop) {
19132         E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
19133                               CK_BuiltinFnToFnPtr)
19134                 .get();
19135         return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy,
19136                                 VK_RValue, SourceLocation(),
19137                                 FPOptionsOverride());
19138       }
19139     }
19140 
19141     Diag(E->getBeginLoc(), diag::err_builtin_fn_use);
19142     return ExprError();
19143   }
19144 
19145   case BuiltinType::IncompleteMatrixIdx:
19146     Diag(cast<MatrixSubscriptExpr>(E->IgnoreParens())
19147              ->getRowIdx()
19148              ->getBeginLoc(),
19149          diag::err_matrix_incomplete_index);
19150     return ExprError();
19151 
19152   // Expressions of unknown type.
19153   case BuiltinType::OMPArraySection:
19154     Diag(E->getBeginLoc(), diag::err_omp_array_section_use);
19155     return ExprError();
19156 
19157   // Expressions of unknown type.
19158   case BuiltinType::OMPArrayShaping:
19159     return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use));
19160 
19161   case BuiltinType::OMPIterator:
19162     return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use));
19163 
19164   // Everything else should be impossible.
19165 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
19166   case BuiltinType::Id:
19167 #include "clang/Basic/OpenCLImageTypes.def"
19168 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
19169   case BuiltinType::Id:
19170 #include "clang/Basic/OpenCLExtensionTypes.def"
19171 #define SVE_TYPE(Name, Id, SingletonId) \
19172   case BuiltinType::Id:
19173 #include "clang/Basic/AArch64SVEACLETypes.def"
19174 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
19175 #define PLACEHOLDER_TYPE(Id, SingletonId)
19176 #include "clang/AST/BuiltinTypes.def"
19177     break;
19178   }
19179 
19180   llvm_unreachable("invalid placeholder type!");
19181 }
19182 
19183 bool Sema::CheckCaseExpression(Expr *E) {
19184   if (E->isTypeDependent())
19185     return true;
19186   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
19187     return E->getType()->isIntegralOrEnumerationType();
19188   return false;
19189 }
19190 
19191 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
19192 ExprResult
19193 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
19194   assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
19195          "Unknown Objective-C Boolean value!");
19196   QualType BoolT = Context.ObjCBuiltinBoolTy;
19197   if (!Context.getBOOLDecl()) {
19198     LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
19199                         Sema::LookupOrdinaryName);
19200     if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
19201       NamedDecl *ND = Result.getFoundDecl();
19202       if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
19203         Context.setBOOLDecl(TD);
19204     }
19205   }
19206   if (Context.getBOOLDecl())
19207     BoolT = Context.getBOOLType();
19208   return new (Context)
19209       ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
19210 }
19211 
19212 ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
19213     llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
19214     SourceLocation RParen) {
19215 
19216   StringRef Platform = getASTContext().getTargetInfo().getPlatformName();
19217 
19218   auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) {
19219     return Spec.getPlatform() == Platform;
19220   });
19221 
19222   VersionTuple Version;
19223   if (Spec != AvailSpecs.end())
19224     Version = Spec->getVersion();
19225 
19226   // The use of `@available` in the enclosing function should be analyzed to
19227   // warn when it's used inappropriately (i.e. not if(@available)).
19228   if (getCurFunctionOrMethodDecl())
19229     getEnclosingFunction()->HasPotentialAvailabilityViolations = true;
19230   else if (getCurBlock() || getCurLambda())
19231     getCurFunction()->HasPotentialAvailabilityViolations = true;
19232 
19233   return new (Context)
19234       ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
19235 }
19236 
19237 ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End,
19238                                     ArrayRef<Expr *> SubExprs, QualType T) {
19239   if (!Context.getLangOpts().RecoveryAST)
19240     return ExprError();
19241 
19242   if (isSFINAEContext())
19243     return ExprError();
19244 
19245   if (T.isNull() || !Context.getLangOpts().RecoveryASTType)
19246     // We don't know the concrete type, fallback to dependent type.
19247     T = Context.DependentTy;
19248   return RecoveryExpr::Create(Context, T, Begin, End, SubExprs);
19249 }
19250