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 
700   // C11 6.3.2.1p2:
701   //   ... if the lvalue has atomic type, the value has the non-atomic version
702   //   of the type of the lvalue ...
703   if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
704     T = Atomic->getValueType().getUnqualifiedType();
705     Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
706                                    nullptr, VK_RValue);
707   }
708 
709   return Res;
710 }
711 
712 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
713   ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
714   if (Res.isInvalid())
715     return ExprError();
716   Res = DefaultLvalueConversion(Res.get());
717   if (Res.isInvalid())
718     return ExprError();
719   return Res;
720 }
721 
722 /// CallExprUnaryConversions - a special case of an unary conversion
723 /// performed on a function designator of a call expression.
724 ExprResult Sema::CallExprUnaryConversions(Expr *E) {
725   QualType Ty = E->getType();
726   ExprResult Res = E;
727   // Only do implicit cast for a function type, but not for a pointer
728   // to function type.
729   if (Ty->isFunctionType()) {
730     Res = ImpCastExprToType(E, Context.getPointerType(Ty),
731                             CK_FunctionToPointerDecay);
732     if (Res.isInvalid())
733       return ExprError();
734   }
735   Res = DefaultLvalueConversion(Res.get());
736   if (Res.isInvalid())
737     return ExprError();
738   return Res.get();
739 }
740 
741 /// UsualUnaryConversions - Performs various conversions that are common to most
742 /// operators (C99 6.3). The conversions of array and function types are
743 /// sometimes suppressed. For example, the array->pointer conversion doesn't
744 /// apply if the array is an argument to the sizeof or address (&) operators.
745 /// In these instances, this routine should *not* be called.
746 ExprResult Sema::UsualUnaryConversions(Expr *E) {
747   // First, convert to an r-value.
748   ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
749   if (Res.isInvalid())
750     return ExprError();
751   E = Res.get();
752 
753   QualType Ty = E->getType();
754   assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
755 
756   // Half FP have to be promoted to float unless it is natively supported
757   if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
758     return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
759 
760   // Try to perform integral promotions if the object has a theoretically
761   // promotable type.
762   if (Ty->isIntegralOrUnscopedEnumerationType()) {
763     // C99 6.3.1.1p2:
764     //
765     //   The following may be used in an expression wherever an int or
766     //   unsigned int may be used:
767     //     - an object or expression with an integer type whose integer
768     //       conversion rank is less than or equal to the rank of int
769     //       and unsigned int.
770     //     - A bit-field of type _Bool, int, signed int, or unsigned int.
771     //
772     //   If an int can represent all values of the original type, the
773     //   value is converted to an int; otherwise, it is converted to an
774     //   unsigned int. These are called the integer promotions. All
775     //   other types are unchanged by the integer promotions.
776 
777     QualType PTy = Context.isPromotableBitField(E);
778     if (!PTy.isNull()) {
779       E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
780       return E;
781     }
782     if (Ty->isPromotableIntegerType()) {
783       QualType PT = Context.getPromotedIntegerType(Ty);
784       E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
785       return E;
786     }
787   }
788   return E;
789 }
790 
791 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
792 /// do not have a prototype. Arguments that have type float or __fp16
793 /// are promoted to double. All other argument types are converted by
794 /// UsualUnaryConversions().
795 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
796   QualType Ty = E->getType();
797   assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
798 
799   ExprResult Res = UsualUnaryConversions(E);
800   if (Res.isInvalid())
801     return ExprError();
802   E = Res.get();
803 
804   // If this is a 'float'  or '__fp16' (CVR qualified or typedef)
805   // promote to double.
806   // Note that default argument promotion applies only to float (and
807   // half/fp16); it does not apply to _Float16.
808   const BuiltinType *BTy = Ty->getAs<BuiltinType>();
809   if (BTy && (BTy->getKind() == BuiltinType::Half ||
810               BTy->getKind() == BuiltinType::Float)) {
811     if (getLangOpts().OpenCL &&
812         !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
813         if (BTy->getKind() == BuiltinType::Half) {
814             E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
815         }
816     } else {
817       E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
818     }
819   }
820 
821   // C++ performs lvalue-to-rvalue conversion as a default argument
822   // promotion, even on class types, but note:
823   //   C++11 [conv.lval]p2:
824   //     When an lvalue-to-rvalue conversion occurs in an unevaluated
825   //     operand or a subexpression thereof the value contained in the
826   //     referenced object is not accessed. Otherwise, if the glvalue
827   //     has a class type, the conversion copy-initializes a temporary
828   //     of type T from the glvalue and the result of the conversion
829   //     is a prvalue for the temporary.
830   // FIXME: add some way to gate this entire thing for correctness in
831   // potentially potentially evaluated contexts.
832   if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
833     ExprResult Temp = PerformCopyInitialization(
834                        InitializedEntity::InitializeTemporary(E->getType()),
835                                                 E->getExprLoc(), E);
836     if (Temp.isInvalid())
837       return ExprError();
838     E = Temp.get();
839   }
840 
841   return E;
842 }
843 
844 /// Determine the degree of POD-ness for an expression.
845 /// Incomplete types are considered POD, since this check can be performed
846 /// when we're in an unevaluated context.
847 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
848   if (Ty->isIncompleteType()) {
849     // C++11 [expr.call]p7:
850     //   After these conversions, if the argument does not have arithmetic,
851     //   enumeration, pointer, pointer to member, or class type, the program
852     //   is ill-formed.
853     //
854     // Since we've already performed array-to-pointer and function-to-pointer
855     // decay, the only such type in C++ is cv void. This also handles
856     // initializer lists as variadic arguments.
857     if (Ty->isVoidType())
858       return VAK_Invalid;
859 
860     if (Ty->isObjCObjectType())
861       return VAK_Invalid;
862     return VAK_Valid;
863   }
864 
865   if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
866     return VAK_Invalid;
867 
868   if (Ty.isCXX98PODType(Context))
869     return VAK_Valid;
870 
871   // C++11 [expr.call]p7:
872   //   Passing a potentially-evaluated argument of class type (Clause 9)
873   //   having a non-trivial copy constructor, a non-trivial move constructor,
874   //   or a non-trivial destructor, with no corresponding parameter,
875   //   is conditionally-supported with implementation-defined semantics.
876   if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
877     if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
878       if (!Record->hasNonTrivialCopyConstructor() &&
879           !Record->hasNonTrivialMoveConstructor() &&
880           !Record->hasNonTrivialDestructor())
881         return VAK_ValidInCXX11;
882 
883   if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
884     return VAK_Valid;
885 
886   if (Ty->isObjCObjectType())
887     return VAK_Invalid;
888 
889   if (getLangOpts().MSVCCompat)
890     return VAK_MSVCUndefined;
891 
892   // FIXME: In C++11, these cases are conditionally-supported, meaning we're
893   // permitted to reject them. We should consider doing so.
894   return VAK_Undefined;
895 }
896 
897 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
898   // Don't allow one to pass an Objective-C interface to a vararg.
899   const QualType &Ty = E->getType();
900   VarArgKind VAK = isValidVarArgType(Ty);
901 
902   // Complain about passing non-POD types through varargs.
903   switch (VAK) {
904   case VAK_ValidInCXX11:
905     DiagRuntimeBehavior(
906         E->getBeginLoc(), nullptr,
907         PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT);
908     LLVM_FALLTHROUGH;
909   case VAK_Valid:
910     if (Ty->isRecordType()) {
911       // This is unlikely to be what the user intended. If the class has a
912       // 'c_str' member function, the user probably meant to call that.
913       DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
914                           PDiag(diag::warn_pass_class_arg_to_vararg)
915                               << Ty << CT << hasCStrMethod(E) << ".c_str()");
916     }
917     break;
918 
919   case VAK_Undefined:
920   case VAK_MSVCUndefined:
921     DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
922                         PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
923                             << getLangOpts().CPlusPlus11 << Ty << CT);
924     break;
925 
926   case VAK_Invalid:
927     if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
928       Diag(E->getBeginLoc(),
929            diag::err_cannot_pass_non_trivial_c_struct_to_vararg)
930           << Ty << CT;
931     else if (Ty->isObjCObjectType())
932       DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
933                           PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
934                               << Ty << CT);
935     else
936       Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg)
937           << isa<InitListExpr>(E) << Ty << CT;
938     break;
939   }
940 }
941 
942 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
943 /// will create a trap if the resulting type is not a POD type.
944 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
945                                                   FunctionDecl *FDecl) {
946   if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
947     // Strip the unbridged-cast placeholder expression off, if applicable.
948     if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
949         (CT == VariadicMethod ||
950          (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
951       E = stripARCUnbridgedCast(E);
952 
953     // Otherwise, do normal placeholder checking.
954     } else {
955       ExprResult ExprRes = CheckPlaceholderExpr(E);
956       if (ExprRes.isInvalid())
957         return ExprError();
958       E = ExprRes.get();
959     }
960   }
961 
962   ExprResult ExprRes = DefaultArgumentPromotion(E);
963   if (ExprRes.isInvalid())
964     return ExprError();
965 
966   // Copy blocks to the heap.
967   if (ExprRes.get()->getType()->isBlockPointerType())
968     maybeExtendBlockObject(ExprRes);
969 
970   E = ExprRes.get();
971 
972   // Diagnostics regarding non-POD argument types are
973   // emitted along with format string checking in Sema::CheckFunctionCall().
974   if (isValidVarArgType(E->getType()) == VAK_Undefined) {
975     // Turn this into a trap.
976     CXXScopeSpec SS;
977     SourceLocation TemplateKWLoc;
978     UnqualifiedId Name;
979     Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
980                        E->getBeginLoc());
981     ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name,
982                                           /*HasTrailingLParen=*/true,
983                                           /*IsAddressOfOperand=*/false);
984     if (TrapFn.isInvalid())
985       return ExprError();
986 
987     ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(),
988                                     None, E->getEndLoc());
989     if (Call.isInvalid())
990       return ExprError();
991 
992     ExprResult Comma =
993         ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E);
994     if (Comma.isInvalid())
995       return ExprError();
996     return Comma.get();
997   }
998 
999   if (!getLangOpts().CPlusPlus &&
1000       RequireCompleteType(E->getExprLoc(), E->getType(),
1001                           diag::err_call_incomplete_argument))
1002     return ExprError();
1003 
1004   return E;
1005 }
1006 
1007 /// Converts an integer to complex float type.  Helper function of
1008 /// UsualArithmeticConversions()
1009 ///
1010 /// \return false if the integer expression is an integer type and is
1011 /// successfully converted to the complex type.
1012 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
1013                                                   ExprResult &ComplexExpr,
1014                                                   QualType IntTy,
1015                                                   QualType ComplexTy,
1016                                                   bool SkipCast) {
1017   if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
1018   if (SkipCast) return false;
1019   if (IntTy->isIntegerType()) {
1020     QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
1021     IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
1022     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1023                                   CK_FloatingRealToComplex);
1024   } else {
1025     assert(IntTy->isComplexIntegerType());
1026     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1027                                   CK_IntegralComplexToFloatingComplex);
1028   }
1029   return false;
1030 }
1031 
1032 /// Handle arithmetic conversion with complex types.  Helper function of
1033 /// UsualArithmeticConversions()
1034 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
1035                                              ExprResult &RHS, QualType LHSType,
1036                                              QualType RHSType,
1037                                              bool IsCompAssign) {
1038   // if we have an integer operand, the result is the complex type.
1039   if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
1040                                              /*skipCast*/false))
1041     return LHSType;
1042   if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
1043                                              /*skipCast*/IsCompAssign))
1044     return RHSType;
1045 
1046   // This handles complex/complex, complex/float, or float/complex.
1047   // When both operands are complex, the shorter operand is converted to the
1048   // type of the longer, and that is the type of the result. This corresponds
1049   // to what is done when combining two real floating-point operands.
1050   // The fun begins when size promotion occur across type domains.
1051   // From H&S 6.3.4: When one operand is complex and the other is a real
1052   // floating-point type, the less precise type is converted, within it's
1053   // real or complex domain, to the precision of the other type. For example,
1054   // when combining a "long double" with a "double _Complex", the
1055   // "double _Complex" is promoted to "long double _Complex".
1056 
1057   // Compute the rank of the two types, regardless of whether they are complex.
1058   int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1059 
1060   auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
1061   auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
1062   QualType LHSElementType =
1063       LHSComplexType ? LHSComplexType->getElementType() : LHSType;
1064   QualType RHSElementType =
1065       RHSComplexType ? RHSComplexType->getElementType() : RHSType;
1066 
1067   QualType ResultType = S.Context.getComplexType(LHSElementType);
1068   if (Order < 0) {
1069     // Promote the precision of the LHS if not an assignment.
1070     ResultType = S.Context.getComplexType(RHSElementType);
1071     if (!IsCompAssign) {
1072       if (LHSComplexType)
1073         LHS =
1074             S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
1075       else
1076         LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
1077     }
1078   } else if (Order > 0) {
1079     // Promote the precision of the RHS.
1080     if (RHSComplexType)
1081       RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
1082     else
1083       RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
1084   }
1085   return ResultType;
1086 }
1087 
1088 /// Handle arithmetic conversion from integer to float.  Helper function
1089 /// of UsualArithmeticConversions()
1090 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1091                                            ExprResult &IntExpr,
1092                                            QualType FloatTy, QualType IntTy,
1093                                            bool ConvertFloat, bool ConvertInt) {
1094   if (IntTy->isIntegerType()) {
1095     if (ConvertInt)
1096       // Convert intExpr to the lhs floating point type.
1097       IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1098                                     CK_IntegralToFloating);
1099     return FloatTy;
1100   }
1101 
1102   // Convert both sides to the appropriate complex float.
1103   assert(IntTy->isComplexIntegerType());
1104   QualType result = S.Context.getComplexType(FloatTy);
1105 
1106   // _Complex int -> _Complex float
1107   if (ConvertInt)
1108     IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1109                                   CK_IntegralComplexToFloatingComplex);
1110 
1111   // float -> _Complex float
1112   if (ConvertFloat)
1113     FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1114                                     CK_FloatingRealToComplex);
1115 
1116   return result;
1117 }
1118 
1119 /// Handle arithmethic conversion with floating point types.  Helper
1120 /// function of UsualArithmeticConversions()
1121 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1122                                       ExprResult &RHS, QualType LHSType,
1123                                       QualType RHSType, bool IsCompAssign) {
1124   bool LHSFloat = LHSType->isRealFloatingType();
1125   bool RHSFloat = RHSType->isRealFloatingType();
1126 
1127   // FIXME: Implement floating to fixed point conversion.(Bug 46268)
1128   // Reference N1169 4.1.4 (Type conversion, usual arithmetic conversions).
1129   if ((LHSType->isFixedPointType() && RHSFloat) ||
1130       (LHSFloat && RHSType->isFixedPointType()))
1131     return QualType();
1132   // If we have two real floating types, convert the smaller operand
1133   // to the bigger result.
1134   if (LHSFloat && RHSFloat) {
1135     int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1136     if (order > 0) {
1137       RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1138       return LHSType;
1139     }
1140 
1141     assert(order < 0 && "illegal float comparison");
1142     if (!IsCompAssign)
1143       LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1144     return RHSType;
1145   }
1146 
1147   if (LHSFloat) {
1148     // Half FP has to be promoted to float unless it is natively supported
1149     if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1150       LHSType = S.Context.FloatTy;
1151 
1152     return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1153                                       /*ConvertFloat=*/!IsCompAssign,
1154                                       /*ConvertInt=*/ true);
1155   }
1156   assert(RHSFloat);
1157   return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1158                                     /*ConvertFloat=*/ true,
1159                                     /*ConvertInt=*/!IsCompAssign);
1160 }
1161 
1162 /// Diagnose attempts to convert between __float128 and long double if
1163 /// there is no support for such conversion. Helper function of
1164 /// UsualArithmeticConversions().
1165 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1166                                       QualType RHSType) {
1167   /*  No issue converting if at least one of the types is not a floating point
1168       type or the two types have the same rank.
1169   */
1170   if (!LHSType->isFloatingType() || !RHSType->isFloatingType() ||
1171       S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0)
1172     return false;
1173 
1174   assert(LHSType->isFloatingType() && RHSType->isFloatingType() &&
1175          "The remaining types must be floating point types.");
1176 
1177   auto *LHSComplex = LHSType->getAs<ComplexType>();
1178   auto *RHSComplex = RHSType->getAs<ComplexType>();
1179 
1180   QualType LHSElemType = LHSComplex ?
1181     LHSComplex->getElementType() : LHSType;
1182   QualType RHSElemType = RHSComplex ?
1183     RHSComplex->getElementType() : RHSType;
1184 
1185   // No issue if the two types have the same representation
1186   if (&S.Context.getFloatTypeSemantics(LHSElemType) ==
1187       &S.Context.getFloatTypeSemantics(RHSElemType))
1188     return false;
1189 
1190   bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty &&
1191                                 RHSElemType == S.Context.LongDoubleTy);
1192   Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy &&
1193                             RHSElemType == S.Context.Float128Ty);
1194 
1195   // We've handled the situation where __float128 and long double have the same
1196   // representation. We allow all conversions for all possible long double types
1197   // except PPC's double double.
1198   return Float128AndLongDouble &&
1199     (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) ==
1200      &llvm::APFloat::PPCDoubleDouble());
1201 }
1202 
1203 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1204 
1205 namespace {
1206 /// These helper callbacks are placed in an anonymous namespace to
1207 /// permit their use as function template parameters.
1208 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1209   return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1210 }
1211 
1212 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1213   return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1214                              CK_IntegralComplexCast);
1215 }
1216 }
1217 
1218 /// Handle integer arithmetic conversions.  Helper function of
1219 /// UsualArithmeticConversions()
1220 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1221 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1222                                         ExprResult &RHS, QualType LHSType,
1223                                         QualType RHSType, bool IsCompAssign) {
1224   // The rules for this case are in C99 6.3.1.8
1225   int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1226   bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1227   bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1228   if (LHSSigned == RHSSigned) {
1229     // Same signedness; use the higher-ranked type
1230     if (order >= 0) {
1231       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1232       return LHSType;
1233     } else if (!IsCompAssign)
1234       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1235     return RHSType;
1236   } else if (order != (LHSSigned ? 1 : -1)) {
1237     // The unsigned type has greater than or equal rank to the
1238     // signed type, so use the unsigned type
1239     if (RHSSigned) {
1240       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1241       return LHSType;
1242     } else if (!IsCompAssign)
1243       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1244     return RHSType;
1245   } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1246     // The two types are different widths; if we are here, that
1247     // means the signed type is larger than the unsigned type, so
1248     // use the signed type.
1249     if (LHSSigned) {
1250       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1251       return LHSType;
1252     } else if (!IsCompAssign)
1253       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1254     return RHSType;
1255   } else {
1256     // The signed type is higher-ranked than the unsigned type,
1257     // but isn't actually any bigger (like unsigned int and long
1258     // on most 32-bit systems).  Use the unsigned type corresponding
1259     // to the signed type.
1260     QualType result =
1261       S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1262     RHS = (*doRHSCast)(S, RHS.get(), result);
1263     if (!IsCompAssign)
1264       LHS = (*doLHSCast)(S, LHS.get(), result);
1265     return result;
1266   }
1267 }
1268 
1269 /// Handle conversions with GCC complex int extension.  Helper function
1270 /// of UsualArithmeticConversions()
1271 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1272                                            ExprResult &RHS, QualType LHSType,
1273                                            QualType RHSType,
1274                                            bool IsCompAssign) {
1275   const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1276   const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1277 
1278   if (LHSComplexInt && RHSComplexInt) {
1279     QualType LHSEltType = LHSComplexInt->getElementType();
1280     QualType RHSEltType = RHSComplexInt->getElementType();
1281     QualType ScalarType =
1282       handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1283         (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1284 
1285     return S.Context.getComplexType(ScalarType);
1286   }
1287 
1288   if (LHSComplexInt) {
1289     QualType LHSEltType = LHSComplexInt->getElementType();
1290     QualType ScalarType =
1291       handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1292         (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1293     QualType ComplexType = S.Context.getComplexType(ScalarType);
1294     RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1295                               CK_IntegralRealToComplex);
1296 
1297     return ComplexType;
1298   }
1299 
1300   assert(RHSComplexInt);
1301 
1302   QualType RHSEltType = RHSComplexInt->getElementType();
1303   QualType ScalarType =
1304     handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1305       (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1306   QualType ComplexType = S.Context.getComplexType(ScalarType);
1307 
1308   if (!IsCompAssign)
1309     LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1310                               CK_IntegralRealToComplex);
1311   return ComplexType;
1312 }
1313 
1314 /// Return the rank of a given fixed point or integer type. The value itself
1315 /// doesn't matter, but the values must be increasing with proper increasing
1316 /// rank as described in N1169 4.1.1.
1317 static unsigned GetFixedPointRank(QualType Ty) {
1318   const auto *BTy = Ty->getAs<BuiltinType>();
1319   assert(BTy && "Expected a builtin type.");
1320 
1321   switch (BTy->getKind()) {
1322   case BuiltinType::ShortFract:
1323   case BuiltinType::UShortFract:
1324   case BuiltinType::SatShortFract:
1325   case BuiltinType::SatUShortFract:
1326     return 1;
1327   case BuiltinType::Fract:
1328   case BuiltinType::UFract:
1329   case BuiltinType::SatFract:
1330   case BuiltinType::SatUFract:
1331     return 2;
1332   case BuiltinType::LongFract:
1333   case BuiltinType::ULongFract:
1334   case BuiltinType::SatLongFract:
1335   case BuiltinType::SatULongFract:
1336     return 3;
1337   case BuiltinType::ShortAccum:
1338   case BuiltinType::UShortAccum:
1339   case BuiltinType::SatShortAccum:
1340   case BuiltinType::SatUShortAccum:
1341     return 4;
1342   case BuiltinType::Accum:
1343   case BuiltinType::UAccum:
1344   case BuiltinType::SatAccum:
1345   case BuiltinType::SatUAccum:
1346     return 5;
1347   case BuiltinType::LongAccum:
1348   case BuiltinType::ULongAccum:
1349   case BuiltinType::SatLongAccum:
1350   case BuiltinType::SatULongAccum:
1351     return 6;
1352   default:
1353     if (BTy->isInteger())
1354       return 0;
1355     llvm_unreachable("Unexpected fixed point or integer type");
1356   }
1357 }
1358 
1359 /// handleFixedPointConversion - Fixed point operations between fixed
1360 /// point types and integers or other fixed point types do not fall under
1361 /// usual arithmetic conversion since these conversions could result in loss
1362 /// of precsision (N1169 4.1.4). These operations should be calculated with
1363 /// the full precision of their result type (N1169 4.1.6.2.1).
1364 static QualType handleFixedPointConversion(Sema &S, QualType LHSTy,
1365                                            QualType RHSTy) {
1366   assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) &&
1367          "Expected at least one of the operands to be a fixed point type");
1368   assert((LHSTy->isFixedPointOrIntegerType() ||
1369           RHSTy->isFixedPointOrIntegerType()) &&
1370          "Special fixed point arithmetic operation conversions are only "
1371          "applied to ints or other fixed point types");
1372 
1373   // If one operand has signed fixed-point type and the other operand has
1374   // unsigned fixed-point type, then the unsigned fixed-point operand is
1375   // converted to its corresponding signed fixed-point type and the resulting
1376   // type is the type of the converted operand.
1377   if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType())
1378     LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy);
1379   else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType())
1380     RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy);
1381 
1382   // The result type is the type with the highest rank, whereby a fixed-point
1383   // conversion rank is always greater than an integer conversion rank; if the
1384   // type of either of the operands is a saturating fixedpoint type, the result
1385   // type shall be the saturating fixed-point type corresponding to the type
1386   // with the highest rank; the resulting value is converted (taking into
1387   // account rounding and overflow) to the precision of the resulting type.
1388   // Same ranks between signed and unsigned types are resolved earlier, so both
1389   // types are either signed or both unsigned at this point.
1390   unsigned LHSTyRank = GetFixedPointRank(LHSTy);
1391   unsigned RHSTyRank = GetFixedPointRank(RHSTy);
1392 
1393   QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy;
1394 
1395   if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType())
1396     ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy);
1397 
1398   return ResultTy;
1399 }
1400 
1401 /// Check that the usual arithmetic conversions can be performed on this pair of
1402 /// expressions that might be of enumeration type.
1403 static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS,
1404                                            SourceLocation Loc,
1405                                            Sema::ArithConvKind ACK) {
1406   // C++2a [expr.arith.conv]p1:
1407   //   If one operand is of enumeration type and the other operand is of a
1408   //   different enumeration type or a floating-point type, this behavior is
1409   //   deprecated ([depr.arith.conv.enum]).
1410   //
1411   // Warn on this in all language modes. Produce a deprecation warning in C++20.
1412   // Eventually we will presumably reject these cases (in C++23 onwards?).
1413   QualType L = LHS->getType(), R = RHS->getType();
1414   bool LEnum = L->isUnscopedEnumerationType(),
1415        REnum = R->isUnscopedEnumerationType();
1416   bool IsCompAssign = ACK == Sema::ACK_CompAssign;
1417   if ((!IsCompAssign && LEnum && R->isFloatingType()) ||
1418       (REnum && L->isFloatingType())) {
1419     S.Diag(Loc, S.getLangOpts().CPlusPlus20
1420                     ? diag::warn_arith_conv_enum_float_cxx20
1421                     : diag::warn_arith_conv_enum_float)
1422         << LHS->getSourceRange() << RHS->getSourceRange()
1423         << (int)ACK << LEnum << L << R;
1424   } else if (!IsCompAssign && LEnum && REnum &&
1425              !S.Context.hasSameUnqualifiedType(L, R)) {
1426     unsigned DiagID;
1427     if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() ||
1428         !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) {
1429       // If either enumeration type is unnamed, it's less likely that the
1430       // user cares about this, but this situation is still deprecated in
1431       // C++2a. Use a different warning group.
1432       DiagID = S.getLangOpts().CPlusPlus20
1433                     ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20
1434                     : diag::warn_arith_conv_mixed_anon_enum_types;
1435     } else if (ACK == Sema::ACK_Conditional) {
1436       // Conditional expressions are separated out because they have
1437       // historically had a different warning flag.
1438       DiagID = S.getLangOpts().CPlusPlus20
1439                    ? diag::warn_conditional_mixed_enum_types_cxx20
1440                    : diag::warn_conditional_mixed_enum_types;
1441     } else if (ACK == Sema::ACK_Comparison) {
1442       // Comparison expressions are separated out because they have
1443       // historically had a different warning flag.
1444       DiagID = S.getLangOpts().CPlusPlus20
1445                    ? diag::warn_comparison_mixed_enum_types_cxx20
1446                    : diag::warn_comparison_mixed_enum_types;
1447     } else {
1448       DiagID = S.getLangOpts().CPlusPlus20
1449                    ? diag::warn_arith_conv_mixed_enum_types_cxx20
1450                    : diag::warn_arith_conv_mixed_enum_types;
1451     }
1452     S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
1453                         << (int)ACK << L << R;
1454   }
1455 }
1456 
1457 /// UsualArithmeticConversions - Performs various conversions that are common to
1458 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1459 /// routine returns the first non-arithmetic type found. The client is
1460 /// responsible for emitting appropriate error diagnostics.
1461 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1462                                           SourceLocation Loc,
1463                                           ArithConvKind ACK) {
1464   checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK);
1465 
1466   if (ACK != ACK_CompAssign) {
1467     LHS = UsualUnaryConversions(LHS.get());
1468     if (LHS.isInvalid())
1469       return QualType();
1470   }
1471 
1472   RHS = UsualUnaryConversions(RHS.get());
1473   if (RHS.isInvalid())
1474     return QualType();
1475 
1476   // For conversion purposes, we ignore any qualifiers.
1477   // For example, "const float" and "float" are equivalent.
1478   QualType LHSType =
1479     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1480   QualType RHSType =
1481     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1482 
1483   // For conversion purposes, we ignore any atomic qualifier on the LHS.
1484   if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1485     LHSType = AtomicLHS->getValueType();
1486 
1487   // If both types are identical, no conversion is needed.
1488   if (LHSType == RHSType)
1489     return LHSType;
1490 
1491   // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1492   // The caller can deal with this (e.g. pointer + int).
1493   if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1494     return QualType();
1495 
1496   // Apply unary and bitfield promotions to the LHS's type.
1497   QualType LHSUnpromotedType = LHSType;
1498   if (LHSType->isPromotableIntegerType())
1499     LHSType = Context.getPromotedIntegerType(LHSType);
1500   QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1501   if (!LHSBitfieldPromoteTy.isNull())
1502     LHSType = LHSBitfieldPromoteTy;
1503   if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign)
1504     LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1505 
1506   // If both types are identical, no conversion is needed.
1507   if (LHSType == RHSType)
1508     return LHSType;
1509 
1510   // ExtInt types aren't subject to conversions between them or normal integers,
1511   // so this fails.
1512   if(LHSType->isExtIntType() || RHSType->isExtIntType())
1513     return QualType();
1514 
1515   // At this point, we have two different arithmetic types.
1516 
1517   // Diagnose attempts to convert between __float128 and long double where
1518   // such conversions currently can't be handled.
1519   if (unsupportedTypeConversion(*this, LHSType, RHSType))
1520     return QualType();
1521 
1522   // Handle complex types first (C99 6.3.1.8p1).
1523   if (LHSType->isComplexType() || RHSType->isComplexType())
1524     return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1525                                         ACK == ACK_CompAssign);
1526 
1527   // Now handle "real" floating types (i.e. float, double, long double).
1528   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1529     return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1530                                  ACK == ACK_CompAssign);
1531 
1532   // Handle GCC complex int extension.
1533   if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1534     return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1535                                       ACK == ACK_CompAssign);
1536 
1537   if (LHSType->isFixedPointType() || RHSType->isFixedPointType())
1538     return handleFixedPointConversion(*this, LHSType, RHSType);
1539 
1540   // Finally, we have two differing integer types.
1541   return handleIntegerConversion<doIntegralCast, doIntegralCast>
1542            (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign);
1543 }
1544 
1545 //===----------------------------------------------------------------------===//
1546 //  Semantic Analysis for various Expression Types
1547 //===----------------------------------------------------------------------===//
1548 
1549 
1550 ExprResult
1551 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1552                                 SourceLocation DefaultLoc,
1553                                 SourceLocation RParenLoc,
1554                                 Expr *ControllingExpr,
1555                                 ArrayRef<ParsedType> ArgTypes,
1556                                 ArrayRef<Expr *> ArgExprs) {
1557   unsigned NumAssocs = ArgTypes.size();
1558   assert(NumAssocs == ArgExprs.size());
1559 
1560   TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1561   for (unsigned i = 0; i < NumAssocs; ++i) {
1562     if (ArgTypes[i])
1563       (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1564     else
1565       Types[i] = nullptr;
1566   }
1567 
1568   ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1569                                              ControllingExpr,
1570                                              llvm::makeArrayRef(Types, NumAssocs),
1571                                              ArgExprs);
1572   delete [] Types;
1573   return ER;
1574 }
1575 
1576 ExprResult
1577 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1578                                  SourceLocation DefaultLoc,
1579                                  SourceLocation RParenLoc,
1580                                  Expr *ControllingExpr,
1581                                  ArrayRef<TypeSourceInfo *> Types,
1582                                  ArrayRef<Expr *> Exprs) {
1583   unsigned NumAssocs = Types.size();
1584   assert(NumAssocs == Exprs.size());
1585 
1586   // Decay and strip qualifiers for the controlling expression type, and handle
1587   // placeholder type replacement. See committee discussion from WG14 DR423.
1588   {
1589     EnterExpressionEvaluationContext Unevaluated(
1590         *this, Sema::ExpressionEvaluationContext::Unevaluated);
1591     ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
1592     if (R.isInvalid())
1593       return ExprError();
1594     ControllingExpr = R.get();
1595   }
1596 
1597   // The controlling expression is an unevaluated operand, so side effects are
1598   // likely unintended.
1599   if (!inTemplateInstantiation() &&
1600       ControllingExpr->HasSideEffects(Context, false))
1601     Diag(ControllingExpr->getExprLoc(),
1602          diag::warn_side_effects_unevaluated_context);
1603 
1604   bool TypeErrorFound = false,
1605        IsResultDependent = ControllingExpr->isTypeDependent(),
1606        ContainsUnexpandedParameterPack
1607          = ControllingExpr->containsUnexpandedParameterPack();
1608 
1609   for (unsigned i = 0; i < NumAssocs; ++i) {
1610     if (Exprs[i]->containsUnexpandedParameterPack())
1611       ContainsUnexpandedParameterPack = true;
1612 
1613     if (Types[i]) {
1614       if (Types[i]->getType()->containsUnexpandedParameterPack())
1615         ContainsUnexpandedParameterPack = true;
1616 
1617       if (Types[i]->getType()->isDependentType()) {
1618         IsResultDependent = true;
1619       } else {
1620         // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1621         // complete object type other than a variably modified type."
1622         unsigned D = 0;
1623         if (Types[i]->getType()->isIncompleteType())
1624           D = diag::err_assoc_type_incomplete;
1625         else if (!Types[i]->getType()->isObjectType())
1626           D = diag::err_assoc_type_nonobject;
1627         else if (Types[i]->getType()->isVariablyModifiedType())
1628           D = diag::err_assoc_type_variably_modified;
1629 
1630         if (D != 0) {
1631           Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1632             << Types[i]->getTypeLoc().getSourceRange()
1633             << Types[i]->getType();
1634           TypeErrorFound = true;
1635         }
1636 
1637         // C11 6.5.1.1p2 "No two generic associations in the same generic
1638         // selection shall specify compatible types."
1639         for (unsigned j = i+1; j < NumAssocs; ++j)
1640           if (Types[j] && !Types[j]->getType()->isDependentType() &&
1641               Context.typesAreCompatible(Types[i]->getType(),
1642                                          Types[j]->getType())) {
1643             Diag(Types[j]->getTypeLoc().getBeginLoc(),
1644                  diag::err_assoc_compatible_types)
1645               << Types[j]->getTypeLoc().getSourceRange()
1646               << Types[j]->getType()
1647               << Types[i]->getType();
1648             Diag(Types[i]->getTypeLoc().getBeginLoc(),
1649                  diag::note_compat_assoc)
1650               << Types[i]->getTypeLoc().getSourceRange()
1651               << Types[i]->getType();
1652             TypeErrorFound = true;
1653           }
1654       }
1655     }
1656   }
1657   if (TypeErrorFound)
1658     return ExprError();
1659 
1660   // If we determined that the generic selection is result-dependent, don't
1661   // try to compute the result expression.
1662   if (IsResultDependent)
1663     return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types,
1664                                         Exprs, DefaultLoc, RParenLoc,
1665                                         ContainsUnexpandedParameterPack);
1666 
1667   SmallVector<unsigned, 1> CompatIndices;
1668   unsigned DefaultIndex = -1U;
1669   for (unsigned i = 0; i < NumAssocs; ++i) {
1670     if (!Types[i])
1671       DefaultIndex = i;
1672     else if (Context.typesAreCompatible(ControllingExpr->getType(),
1673                                         Types[i]->getType()))
1674       CompatIndices.push_back(i);
1675   }
1676 
1677   // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1678   // type compatible with at most one of the types named in its generic
1679   // association list."
1680   if (CompatIndices.size() > 1) {
1681     // We strip parens here because the controlling expression is typically
1682     // parenthesized in macro definitions.
1683     ControllingExpr = ControllingExpr->IgnoreParens();
1684     Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match)
1685         << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1686         << (unsigned)CompatIndices.size();
1687     for (unsigned I : CompatIndices) {
1688       Diag(Types[I]->getTypeLoc().getBeginLoc(),
1689            diag::note_compat_assoc)
1690         << Types[I]->getTypeLoc().getSourceRange()
1691         << Types[I]->getType();
1692     }
1693     return ExprError();
1694   }
1695 
1696   // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1697   // its controlling expression shall have type compatible with exactly one of
1698   // the types named in its generic association list."
1699   if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1700     // We strip parens here because the controlling expression is typically
1701     // parenthesized in macro definitions.
1702     ControllingExpr = ControllingExpr->IgnoreParens();
1703     Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match)
1704         << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1705     return ExprError();
1706   }
1707 
1708   // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1709   // type name that is compatible with the type of the controlling expression,
1710   // then the result expression of the generic selection is the expression
1711   // in that generic association. Otherwise, the result expression of the
1712   // generic selection is the expression in the default generic association."
1713   unsigned ResultIndex =
1714     CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1715 
1716   return GenericSelectionExpr::Create(
1717       Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1718       ContainsUnexpandedParameterPack, ResultIndex);
1719 }
1720 
1721 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1722 /// location of the token and the offset of the ud-suffix within it.
1723 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1724                                      unsigned Offset) {
1725   return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1726                                         S.getLangOpts());
1727 }
1728 
1729 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1730 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
1731 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1732                                                  IdentifierInfo *UDSuffix,
1733                                                  SourceLocation UDSuffixLoc,
1734                                                  ArrayRef<Expr*> Args,
1735                                                  SourceLocation LitEndLoc) {
1736   assert(Args.size() <= 2 && "too many arguments for literal operator");
1737 
1738   QualType ArgTy[2];
1739   for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1740     ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1741     if (ArgTy[ArgIdx]->isArrayType())
1742       ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1743   }
1744 
1745   DeclarationName OpName =
1746     S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1747   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1748   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1749 
1750   LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1751   if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1752                               /*AllowRaw*/ false, /*AllowTemplate*/ false,
1753                               /*AllowStringTemplate*/ false,
1754                               /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
1755     return ExprError();
1756 
1757   return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1758 }
1759 
1760 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1761 /// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
1762 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1763 /// multiple tokens.  However, the common case is that StringToks points to one
1764 /// string.
1765 ///
1766 ExprResult
1767 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
1768   assert(!StringToks.empty() && "Must have at least one string!");
1769 
1770   StringLiteralParser Literal(StringToks, PP);
1771   if (Literal.hadError)
1772     return ExprError();
1773 
1774   SmallVector<SourceLocation, 4> StringTokLocs;
1775   for (const Token &Tok : StringToks)
1776     StringTokLocs.push_back(Tok.getLocation());
1777 
1778   QualType CharTy = Context.CharTy;
1779   StringLiteral::StringKind Kind = StringLiteral::Ascii;
1780   if (Literal.isWide()) {
1781     CharTy = Context.getWideCharType();
1782     Kind = StringLiteral::Wide;
1783   } else if (Literal.isUTF8()) {
1784     if (getLangOpts().Char8)
1785       CharTy = Context.Char8Ty;
1786     Kind = StringLiteral::UTF8;
1787   } else if (Literal.isUTF16()) {
1788     CharTy = Context.Char16Ty;
1789     Kind = StringLiteral::UTF16;
1790   } else if (Literal.isUTF32()) {
1791     CharTy = Context.Char32Ty;
1792     Kind = StringLiteral::UTF32;
1793   } else if (Literal.isPascal()) {
1794     CharTy = Context.UnsignedCharTy;
1795   }
1796 
1797   // Warn on initializing an array of char from a u8 string literal; this
1798   // becomes ill-formed in C++2a.
1799   if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus20 &&
1800       !getLangOpts().Char8 && Kind == StringLiteral::UTF8) {
1801     Diag(StringTokLocs.front(), diag::warn_cxx20_compat_utf8_string);
1802 
1803     // Create removals for all 'u8' prefixes in the string literal(s). This
1804     // ensures C++2a compatibility (but may change the program behavior when
1805     // built by non-Clang compilers for which the execution character set is
1806     // not always UTF-8).
1807     auto RemovalDiag = PDiag(diag::note_cxx20_compat_utf8_string_remove_u8);
1808     SourceLocation RemovalDiagLoc;
1809     for (const Token &Tok : StringToks) {
1810       if (Tok.getKind() == tok::utf8_string_literal) {
1811         if (RemovalDiagLoc.isInvalid())
1812           RemovalDiagLoc = Tok.getLocation();
1813         RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange(
1814             Tok.getLocation(),
1815             Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2,
1816                                            getSourceManager(), getLangOpts())));
1817       }
1818     }
1819     Diag(RemovalDiagLoc, RemovalDiag);
1820   }
1821 
1822   QualType StrTy =
1823       Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars());
1824 
1825   // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1826   StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1827                                              Kind, Literal.Pascal, StrTy,
1828                                              &StringTokLocs[0],
1829                                              StringTokLocs.size());
1830   if (Literal.getUDSuffix().empty())
1831     return Lit;
1832 
1833   // We're building a user-defined literal.
1834   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1835   SourceLocation UDSuffixLoc =
1836     getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1837                    Literal.getUDSuffixOffset());
1838 
1839   // Make sure we're allowed user-defined literals here.
1840   if (!UDLScope)
1841     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1842 
1843   // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1844   //   operator "" X (str, len)
1845   QualType SizeType = Context.getSizeType();
1846 
1847   DeclarationName OpName =
1848     Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1849   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1850   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1851 
1852   QualType ArgTy[] = {
1853     Context.getArrayDecayedType(StrTy), SizeType
1854   };
1855 
1856   LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1857   switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1858                                 /*AllowRaw*/ false, /*AllowTemplate*/ false,
1859                                 /*AllowStringTemplate*/ true,
1860                                 /*DiagnoseMissing*/ true)) {
1861 
1862   case LOLR_Cooked: {
1863     llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1864     IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1865                                                     StringTokLocs[0]);
1866     Expr *Args[] = { Lit, LenArg };
1867 
1868     return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1869   }
1870 
1871   case LOLR_StringTemplate: {
1872     TemplateArgumentListInfo ExplicitArgs;
1873 
1874     unsigned CharBits = Context.getIntWidth(CharTy);
1875     bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1876     llvm::APSInt Value(CharBits, CharIsUnsigned);
1877 
1878     TemplateArgument TypeArg(CharTy);
1879     TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1880     ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1881 
1882     for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1883       Value = Lit->getCodeUnit(I);
1884       TemplateArgument Arg(Context, Value, CharTy);
1885       TemplateArgumentLocInfo ArgInfo;
1886       ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1887     }
1888     return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1889                                     &ExplicitArgs);
1890   }
1891   case LOLR_Raw:
1892   case LOLR_Template:
1893   case LOLR_ErrorNoDiagnostic:
1894     llvm_unreachable("unexpected literal operator lookup result");
1895   case LOLR_Error:
1896     return ExprError();
1897   }
1898   llvm_unreachable("unexpected literal operator lookup result");
1899 }
1900 
1901 DeclRefExpr *
1902 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1903                        SourceLocation Loc,
1904                        const CXXScopeSpec *SS) {
1905   DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1906   return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1907 }
1908 
1909 DeclRefExpr *
1910 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1911                        const DeclarationNameInfo &NameInfo,
1912                        const CXXScopeSpec *SS, NamedDecl *FoundD,
1913                        SourceLocation TemplateKWLoc,
1914                        const TemplateArgumentListInfo *TemplateArgs) {
1915   NestedNameSpecifierLoc NNS =
1916       SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc();
1917   return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc,
1918                           TemplateArgs);
1919 }
1920 
1921 NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) {
1922   // A declaration named in an unevaluated operand never constitutes an odr-use.
1923   if (isUnevaluatedContext())
1924     return NOUR_Unevaluated;
1925 
1926   // C++2a [basic.def.odr]p4:
1927   //   A variable x whose name appears as a potentially-evaluated expression e
1928   //   is odr-used by e unless [...] x is a reference that is usable in
1929   //   constant expressions.
1930   if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
1931     if (VD->getType()->isReferenceType() &&
1932         !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) &&
1933         VD->isUsableInConstantExpressions(Context))
1934       return NOUR_Constant;
1935   }
1936 
1937   // All remaining non-variable cases constitute an odr-use. For variables, we
1938   // need to wait and see how the expression is used.
1939   return NOUR_None;
1940 }
1941 
1942 /// BuildDeclRefExpr - Build an expression that references a
1943 /// declaration that does not require a closure capture.
1944 DeclRefExpr *
1945 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1946                        const DeclarationNameInfo &NameInfo,
1947                        NestedNameSpecifierLoc NNS, NamedDecl *FoundD,
1948                        SourceLocation TemplateKWLoc,
1949                        const TemplateArgumentListInfo *TemplateArgs) {
1950   bool RefersToCapturedVariable =
1951       isa<VarDecl>(D) &&
1952       NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
1953 
1954   DeclRefExpr *E = DeclRefExpr::Create(
1955       Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty,
1956       VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D));
1957   MarkDeclRefReferenced(E);
1958 
1959   // C++ [except.spec]p17:
1960   //   An exception-specification is considered to be needed when:
1961   //   - in an expression, the function is the unique lookup result or
1962   //     the selected member of a set of overloaded functions.
1963   //
1964   // We delay doing this until after we've built the function reference and
1965   // marked it as used so that:
1966   //  a) if the function is defaulted, we get errors from defining it before /
1967   //     instead of errors from computing its exception specification, and
1968   //  b) if the function is a defaulted comparison, we can use the body we
1969   //     build when defining it as input to the exception specification
1970   //     computation rather than computing a new body.
1971   if (auto *FPT = Ty->getAs<FunctionProtoType>()) {
1972     if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
1973       if (auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT))
1974         E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers()));
1975     }
1976   }
1977 
1978   if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
1979       Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() &&
1980       !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc()))
1981     getCurFunction()->recordUseOfWeak(E);
1982 
1983   FieldDecl *FD = dyn_cast<FieldDecl>(D);
1984   if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
1985     FD = IFD->getAnonField();
1986   if (FD) {
1987     UnusedPrivateFields.remove(FD);
1988     // Just in case we're building an illegal pointer-to-member.
1989     if (FD->isBitField())
1990       E->setObjectKind(OK_BitField);
1991   }
1992 
1993   // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
1994   // designates a bit-field.
1995   if (auto *BD = dyn_cast<BindingDecl>(D))
1996     if (auto *BE = BD->getBinding())
1997       E->setObjectKind(BE->getObjectKind());
1998 
1999   return E;
2000 }
2001 
2002 /// Decomposes the given name into a DeclarationNameInfo, its location, and
2003 /// possibly a list of template arguments.
2004 ///
2005 /// If this produces template arguments, it is permitted to call
2006 /// DecomposeTemplateName.
2007 ///
2008 /// This actually loses a lot of source location information for
2009 /// non-standard name kinds; we should consider preserving that in
2010 /// some way.
2011 void
2012 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
2013                              TemplateArgumentListInfo &Buffer,
2014                              DeclarationNameInfo &NameInfo,
2015                              const TemplateArgumentListInfo *&TemplateArgs) {
2016   if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) {
2017     Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
2018     Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
2019 
2020     ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
2021                                        Id.TemplateId->NumArgs);
2022     translateTemplateArguments(TemplateArgsPtr, Buffer);
2023 
2024     TemplateName TName = Id.TemplateId->Template.get();
2025     SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
2026     NameInfo = Context.getNameForTemplate(TName, TNameLoc);
2027     TemplateArgs = &Buffer;
2028   } else {
2029     NameInfo = GetNameFromUnqualifiedId(Id);
2030     TemplateArgs = nullptr;
2031   }
2032 }
2033 
2034 static void emitEmptyLookupTypoDiagnostic(
2035     const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
2036     DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
2037     unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
2038   DeclContext *Ctx =
2039       SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
2040   if (!TC) {
2041     // Emit a special diagnostic for failed member lookups.
2042     // FIXME: computing the declaration context might fail here (?)
2043     if (Ctx)
2044       SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
2045                                                  << SS.getRange();
2046     else
2047       SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
2048     return;
2049   }
2050 
2051   std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
2052   bool DroppedSpecifier =
2053       TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
2054   unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
2055                         ? diag::note_implicit_param_decl
2056                         : diag::note_previous_decl;
2057   if (!Ctx)
2058     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
2059                          SemaRef.PDiag(NoteID));
2060   else
2061     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
2062                                  << Typo << Ctx << DroppedSpecifier
2063                                  << SS.getRange(),
2064                          SemaRef.PDiag(NoteID));
2065 }
2066 
2067 /// Diagnose an empty lookup.
2068 ///
2069 /// \return false if new lookup candidates were found
2070 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
2071                                CorrectionCandidateCallback &CCC,
2072                                TemplateArgumentListInfo *ExplicitTemplateArgs,
2073                                ArrayRef<Expr *> Args, TypoExpr **Out) {
2074   DeclarationName Name = R.getLookupName();
2075 
2076   unsigned diagnostic = diag::err_undeclared_var_use;
2077   unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
2078   if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
2079       Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
2080       Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
2081     diagnostic = diag::err_undeclared_use;
2082     diagnostic_suggest = diag::err_undeclared_use_suggest;
2083   }
2084 
2085   // If the original lookup was an unqualified lookup, fake an
2086   // unqualified lookup.  This is useful when (for example) the
2087   // original lookup would not have found something because it was a
2088   // dependent name.
2089   DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
2090   while (DC) {
2091     if (isa<CXXRecordDecl>(DC)) {
2092       LookupQualifiedName(R, DC);
2093 
2094       if (!R.empty()) {
2095         // Don't give errors about ambiguities in this lookup.
2096         R.suppressDiagnostics();
2097 
2098         // During a default argument instantiation the CurContext points
2099         // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
2100         // function parameter list, hence add an explicit check.
2101         bool isDefaultArgument =
2102             !CodeSynthesisContexts.empty() &&
2103             CodeSynthesisContexts.back().Kind ==
2104                 CodeSynthesisContext::DefaultFunctionArgumentInstantiation;
2105         CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
2106         bool isInstance = CurMethod &&
2107                           CurMethod->isInstance() &&
2108                           DC == CurMethod->getParent() && !isDefaultArgument;
2109 
2110         // Give a code modification hint to insert 'this->'.
2111         // TODO: fixit for inserting 'Base<T>::' in the other cases.
2112         // Actually quite difficult!
2113         if (getLangOpts().MSVCCompat)
2114           diagnostic = diag::ext_found_via_dependent_bases_lookup;
2115         if (isInstance) {
2116           Diag(R.getNameLoc(), diagnostic) << Name
2117             << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
2118           CheckCXXThisCapture(R.getNameLoc());
2119         } else {
2120           Diag(R.getNameLoc(), diagnostic) << Name;
2121         }
2122 
2123         // Do we really want to note all of these?
2124         for (NamedDecl *D : R)
2125           Diag(D->getLocation(), diag::note_dependent_var_use);
2126 
2127         // Return true if we are inside a default argument instantiation
2128         // and the found name refers to an instance member function, otherwise
2129         // the function calling DiagnoseEmptyLookup will try to create an
2130         // implicit member call and this is wrong for default argument.
2131         if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
2132           Diag(R.getNameLoc(), diag::err_member_call_without_object);
2133           return true;
2134         }
2135 
2136         // Tell the callee to try to recover.
2137         return false;
2138       }
2139 
2140       R.clear();
2141     }
2142 
2143     DC = DC->getLookupParent();
2144   }
2145 
2146   // We didn't find anything, so try to correct for a typo.
2147   TypoCorrection Corrected;
2148   if (S && Out) {
2149     SourceLocation TypoLoc = R.getNameLoc();
2150     assert(!ExplicitTemplateArgs &&
2151            "Diagnosing an empty lookup with explicit template args!");
2152     *Out = CorrectTypoDelayed(
2153         R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
2154         [=](const TypoCorrection &TC) {
2155           emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
2156                                         diagnostic, diagnostic_suggest);
2157         },
2158         nullptr, CTK_ErrorRecovery);
2159     if (*Out)
2160       return true;
2161   } else if (S &&
2162              (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
2163                                       S, &SS, CCC, CTK_ErrorRecovery))) {
2164     std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
2165     bool DroppedSpecifier =
2166         Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
2167     R.setLookupName(Corrected.getCorrection());
2168 
2169     bool AcceptableWithRecovery = false;
2170     bool AcceptableWithoutRecovery = false;
2171     NamedDecl *ND = Corrected.getFoundDecl();
2172     if (ND) {
2173       if (Corrected.isOverloaded()) {
2174         OverloadCandidateSet OCS(R.getNameLoc(),
2175                                  OverloadCandidateSet::CSK_Normal);
2176         OverloadCandidateSet::iterator Best;
2177         for (NamedDecl *CD : Corrected) {
2178           if (FunctionTemplateDecl *FTD =
2179                    dyn_cast<FunctionTemplateDecl>(CD))
2180             AddTemplateOverloadCandidate(
2181                 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
2182                 Args, OCS);
2183           else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
2184             if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
2185               AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
2186                                    Args, OCS);
2187         }
2188         switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
2189         case OR_Success:
2190           ND = Best->FoundDecl;
2191           Corrected.setCorrectionDecl(ND);
2192           break;
2193         default:
2194           // FIXME: Arbitrarily pick the first declaration for the note.
2195           Corrected.setCorrectionDecl(ND);
2196           break;
2197         }
2198       }
2199       R.addDecl(ND);
2200       if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2201         CXXRecordDecl *Record = nullptr;
2202         if (Corrected.getCorrectionSpecifier()) {
2203           const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
2204           Record = Ty->getAsCXXRecordDecl();
2205         }
2206         if (!Record)
2207           Record = cast<CXXRecordDecl>(
2208               ND->getDeclContext()->getRedeclContext());
2209         R.setNamingClass(Record);
2210       }
2211 
2212       auto *UnderlyingND = ND->getUnderlyingDecl();
2213       AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2214                                isa<FunctionTemplateDecl>(UnderlyingND);
2215       // FIXME: If we ended up with a typo for a type name or
2216       // Objective-C class name, we're in trouble because the parser
2217       // is in the wrong place to recover. Suggest the typo
2218       // correction, but don't make it a fix-it since we're not going
2219       // to recover well anyway.
2220       AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) ||
2221                                   getAsTypeTemplateDecl(UnderlyingND) ||
2222                                   isa<ObjCInterfaceDecl>(UnderlyingND);
2223     } else {
2224       // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2225       // because we aren't able to recover.
2226       AcceptableWithoutRecovery = true;
2227     }
2228 
2229     if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2230       unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2231                             ? diag::note_implicit_param_decl
2232                             : diag::note_previous_decl;
2233       if (SS.isEmpty())
2234         diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
2235                      PDiag(NoteID), AcceptableWithRecovery);
2236       else
2237         diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
2238                                   << Name << computeDeclContext(SS, false)
2239                                   << DroppedSpecifier << SS.getRange(),
2240                      PDiag(NoteID), AcceptableWithRecovery);
2241 
2242       // Tell the callee whether to try to recover.
2243       return !AcceptableWithRecovery;
2244     }
2245   }
2246   R.clear();
2247 
2248   // Emit a special diagnostic for failed member lookups.
2249   // FIXME: computing the declaration context might fail here (?)
2250   if (!SS.isEmpty()) {
2251     Diag(R.getNameLoc(), diag::err_no_member)
2252       << Name << computeDeclContext(SS, false)
2253       << SS.getRange();
2254     return true;
2255   }
2256 
2257   // Give up, we can't recover.
2258   Diag(R.getNameLoc(), diagnostic) << Name;
2259   return true;
2260 }
2261 
2262 /// In Microsoft mode, if we are inside a template class whose parent class has
2263 /// dependent base classes, and we can't resolve an unqualified identifier, then
2264 /// assume the identifier is a member of a dependent base class.  We can only
2265 /// recover successfully in static methods, instance methods, and other contexts
2266 /// where 'this' is available.  This doesn't precisely match MSVC's
2267 /// instantiation model, but it's close enough.
2268 static Expr *
2269 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
2270                                DeclarationNameInfo &NameInfo,
2271                                SourceLocation TemplateKWLoc,
2272                                const TemplateArgumentListInfo *TemplateArgs) {
2273   // Only try to recover from lookup into dependent bases in static methods or
2274   // contexts where 'this' is available.
2275   QualType ThisType = S.getCurrentThisType();
2276   const CXXRecordDecl *RD = nullptr;
2277   if (!ThisType.isNull())
2278     RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2279   else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2280     RD = MD->getParent();
2281   if (!RD || !RD->hasAnyDependentBases())
2282     return nullptr;
2283 
2284   // Diagnose this as unqualified lookup into a dependent base class.  If 'this'
2285   // is available, suggest inserting 'this->' as a fixit.
2286   SourceLocation Loc = NameInfo.getLoc();
2287   auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2288   DB << NameInfo.getName() << RD;
2289 
2290   if (!ThisType.isNull()) {
2291     DB << FixItHint::CreateInsertion(Loc, "this->");
2292     return CXXDependentScopeMemberExpr::Create(
2293         Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2294         /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2295         /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
2296   }
2297 
2298   // Synthesize a fake NNS that points to the derived class.  This will
2299   // perform name lookup during template instantiation.
2300   CXXScopeSpec SS;
2301   auto *NNS =
2302       NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2303   SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2304   return DependentScopeDeclRefExpr::Create(
2305       Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2306       TemplateArgs);
2307 }
2308 
2309 ExprResult
2310 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2311                         SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2312                         bool HasTrailingLParen, bool IsAddressOfOperand,
2313                         CorrectionCandidateCallback *CCC,
2314                         bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2315   assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2316          "cannot be direct & operand and have a trailing lparen");
2317   if (SS.isInvalid())
2318     return ExprError();
2319 
2320   TemplateArgumentListInfo TemplateArgsBuffer;
2321 
2322   // Decompose the UnqualifiedId into the following data.
2323   DeclarationNameInfo NameInfo;
2324   const TemplateArgumentListInfo *TemplateArgs;
2325   DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2326 
2327   DeclarationName Name = NameInfo.getName();
2328   IdentifierInfo *II = Name.getAsIdentifierInfo();
2329   SourceLocation NameLoc = NameInfo.getLoc();
2330 
2331   if (II && II->isEditorPlaceholder()) {
2332     // FIXME: When typed placeholders are supported we can create a typed
2333     // placeholder expression node.
2334     return ExprError();
2335   }
2336 
2337   // C++ [temp.dep.expr]p3:
2338   //   An id-expression is type-dependent if it contains:
2339   //     -- an identifier that was declared with a dependent type,
2340   //        (note: handled after lookup)
2341   //     -- a template-id that is dependent,
2342   //        (note: handled in BuildTemplateIdExpr)
2343   //     -- a conversion-function-id that specifies a dependent type,
2344   //     -- a nested-name-specifier that contains a class-name that
2345   //        names a dependent type.
2346   // Determine whether this is a member of an unknown specialization;
2347   // we need to handle these differently.
2348   bool DependentID = false;
2349   if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2350       Name.getCXXNameType()->isDependentType()) {
2351     DependentID = true;
2352   } else if (SS.isSet()) {
2353     if (DeclContext *DC = computeDeclContext(SS, false)) {
2354       if (RequireCompleteDeclContext(SS, DC))
2355         return ExprError();
2356     } else {
2357       DependentID = true;
2358     }
2359   }
2360 
2361   if (DependentID)
2362     return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2363                                       IsAddressOfOperand, TemplateArgs);
2364 
2365   // Perform the required lookup.
2366   LookupResult R(*this, NameInfo,
2367                  (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam)
2368                      ? LookupObjCImplicitSelfParam
2369                      : LookupOrdinaryName);
2370   if (TemplateKWLoc.isValid() || TemplateArgs) {
2371     // Lookup the template name again to correctly establish the context in
2372     // which it was found. This is really unfortunate as we already did the
2373     // lookup to determine that it was a template name in the first place. If
2374     // this becomes a performance hit, we can work harder to preserve those
2375     // results until we get here but it's likely not worth it.
2376     bool MemberOfUnknownSpecialization;
2377     AssumedTemplateKind AssumedTemplate;
2378     if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2379                            MemberOfUnknownSpecialization, TemplateKWLoc,
2380                            &AssumedTemplate))
2381       return ExprError();
2382 
2383     if (MemberOfUnknownSpecialization ||
2384         (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2385       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2386                                         IsAddressOfOperand, TemplateArgs);
2387   } else {
2388     bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2389     LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2390 
2391     // If the result might be in a dependent base class, this is a dependent
2392     // id-expression.
2393     if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2394       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2395                                         IsAddressOfOperand, TemplateArgs);
2396 
2397     // If this reference is in an Objective-C method, then we need to do
2398     // some special Objective-C lookup, too.
2399     if (IvarLookupFollowUp) {
2400       ExprResult E(LookupInObjCMethod(R, S, II, true));
2401       if (E.isInvalid())
2402         return ExprError();
2403 
2404       if (Expr *Ex = E.getAs<Expr>())
2405         return Ex;
2406     }
2407   }
2408 
2409   if (R.isAmbiguous())
2410     return ExprError();
2411 
2412   // This could be an implicitly declared function reference (legal in C90,
2413   // extension in C99, forbidden in C++).
2414   if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2415     NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2416     if (D) R.addDecl(D);
2417   }
2418 
2419   // Determine whether this name might be a candidate for
2420   // argument-dependent lookup.
2421   bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2422 
2423   if (R.empty() && !ADL) {
2424     if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2425       if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2426                                                    TemplateKWLoc, TemplateArgs))
2427         return E;
2428     }
2429 
2430     // Don't diagnose an empty lookup for inline assembly.
2431     if (IsInlineAsmIdentifier)
2432       return ExprError();
2433 
2434     // If this name wasn't predeclared and if this is not a function
2435     // call, diagnose the problem.
2436     TypoExpr *TE = nullptr;
2437     DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep()
2438                                                        : nullptr);
2439     DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;
2440     assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2441            "Typo correction callback misconfigured");
2442     if (CCC) {
2443       // Make sure the callback knows what the typo being diagnosed is.
2444       CCC->setTypoName(II);
2445       if (SS.isValid())
2446         CCC->setTypoNNS(SS.getScopeRep());
2447     }
2448     // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2449     // a template name, but we happen to have always already looked up the name
2450     // before we get here if it must be a template name.
2451     if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr,
2452                             None, &TE)) {
2453       if (TE && KeywordReplacement) {
2454         auto &State = getTypoExprState(TE);
2455         auto BestTC = State.Consumer->getNextCorrection();
2456         if (BestTC.isKeyword()) {
2457           auto *II = BestTC.getCorrectionAsIdentifierInfo();
2458           if (State.DiagHandler)
2459             State.DiagHandler(BestTC);
2460           KeywordReplacement->startToken();
2461           KeywordReplacement->setKind(II->getTokenID());
2462           KeywordReplacement->setIdentifierInfo(II);
2463           KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2464           // Clean up the state associated with the TypoExpr, since it has
2465           // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2466           clearDelayedTypo(TE);
2467           // Signal that a correction to a keyword was performed by returning a
2468           // valid-but-null ExprResult.
2469           return (Expr*)nullptr;
2470         }
2471         State.Consumer->resetCorrectionStream();
2472       }
2473       return TE ? TE : ExprError();
2474     }
2475 
2476     assert(!R.empty() &&
2477            "DiagnoseEmptyLookup returned false but added no results");
2478 
2479     // If we found an Objective-C instance variable, let
2480     // LookupInObjCMethod build the appropriate expression to
2481     // reference the ivar.
2482     if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2483       R.clear();
2484       ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2485       // In a hopelessly buggy code, Objective-C instance variable
2486       // lookup fails and no expression will be built to reference it.
2487       if (!E.isInvalid() && !E.get())
2488         return ExprError();
2489       return E;
2490     }
2491   }
2492 
2493   // This is guaranteed from this point on.
2494   assert(!R.empty() || ADL);
2495 
2496   // Check whether this might be a C++ implicit instance member access.
2497   // C++ [class.mfct.non-static]p3:
2498   //   When an id-expression that is not part of a class member access
2499   //   syntax and not used to form a pointer to member is used in the
2500   //   body of a non-static member function of class X, if name lookup
2501   //   resolves the name in the id-expression to a non-static non-type
2502   //   member of some class C, the id-expression is transformed into a
2503   //   class member access expression using (*this) as the
2504   //   postfix-expression to the left of the . operator.
2505   //
2506   // But we don't actually need to do this for '&' operands if R
2507   // resolved to a function or overloaded function set, because the
2508   // expression is ill-formed if it actually works out to be a
2509   // non-static member function:
2510   //
2511   // C++ [expr.ref]p4:
2512   //   Otherwise, if E1.E2 refers to a non-static member function. . .
2513   //   [t]he expression can be used only as the left-hand operand of a
2514   //   member function call.
2515   //
2516   // There are other safeguards against such uses, but it's important
2517   // to get this right here so that we don't end up making a
2518   // spuriously dependent expression if we're inside a dependent
2519   // instance method.
2520   if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2521     bool MightBeImplicitMember;
2522     if (!IsAddressOfOperand)
2523       MightBeImplicitMember = true;
2524     else if (!SS.isEmpty())
2525       MightBeImplicitMember = false;
2526     else if (R.isOverloadedResult())
2527       MightBeImplicitMember = false;
2528     else if (R.isUnresolvableResult())
2529       MightBeImplicitMember = true;
2530     else
2531       MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2532                               isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2533                               isa<MSPropertyDecl>(R.getFoundDecl());
2534 
2535     if (MightBeImplicitMember)
2536       return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2537                                              R, TemplateArgs, S);
2538   }
2539 
2540   if (TemplateArgs || TemplateKWLoc.isValid()) {
2541 
2542     // In C++1y, if this is a variable template id, then check it
2543     // in BuildTemplateIdExpr().
2544     // The single lookup result must be a variable template declaration.
2545     if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId &&
2546         Id.TemplateId->Kind == TNK_Var_template) {
2547       assert(R.getAsSingle<VarTemplateDecl>() &&
2548              "There should only be one declaration found.");
2549     }
2550 
2551     return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2552   }
2553 
2554   return BuildDeclarationNameExpr(SS, R, ADL);
2555 }
2556 
2557 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2558 /// declaration name, generally during template instantiation.
2559 /// There's a large number of things which don't need to be done along
2560 /// this path.
2561 ExprResult Sema::BuildQualifiedDeclarationNameExpr(
2562     CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2563     bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2564   DeclContext *DC = computeDeclContext(SS, false);
2565   if (!DC)
2566     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2567                                      NameInfo, /*TemplateArgs=*/nullptr);
2568 
2569   if (RequireCompleteDeclContext(SS, DC))
2570     return ExprError();
2571 
2572   LookupResult R(*this, NameInfo, LookupOrdinaryName);
2573   LookupQualifiedName(R, DC);
2574 
2575   if (R.isAmbiguous())
2576     return ExprError();
2577 
2578   if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2579     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2580                                      NameInfo, /*TemplateArgs=*/nullptr);
2581 
2582   if (R.empty()) {
2583     Diag(NameInfo.getLoc(), diag::err_no_member)
2584       << NameInfo.getName() << DC << SS.getRange();
2585     return ExprError();
2586   }
2587 
2588   if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2589     // Diagnose a missing typename if this resolved unambiguously to a type in
2590     // a dependent context.  If we can recover with a type, downgrade this to
2591     // a warning in Microsoft compatibility mode.
2592     unsigned DiagID = diag::err_typename_missing;
2593     if (RecoveryTSI && getLangOpts().MSVCCompat)
2594       DiagID = diag::ext_typename_missing;
2595     SourceLocation Loc = SS.getBeginLoc();
2596     auto D = Diag(Loc, DiagID);
2597     D << SS.getScopeRep() << NameInfo.getName().getAsString()
2598       << SourceRange(Loc, NameInfo.getEndLoc());
2599 
2600     // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2601     // context.
2602     if (!RecoveryTSI)
2603       return ExprError();
2604 
2605     // Only issue the fixit if we're prepared to recover.
2606     D << FixItHint::CreateInsertion(Loc, "typename ");
2607 
2608     // Recover by pretending this was an elaborated type.
2609     QualType Ty = Context.getTypeDeclType(TD);
2610     TypeLocBuilder TLB;
2611     TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2612 
2613     QualType ET = getElaboratedType(ETK_None, SS, Ty);
2614     ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2615     QTL.setElaboratedKeywordLoc(SourceLocation());
2616     QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2617 
2618     *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2619 
2620     return ExprEmpty();
2621   }
2622 
2623   // Defend against this resolving to an implicit member access. We usually
2624   // won't get here if this might be a legitimate a class member (we end up in
2625   // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2626   // a pointer-to-member or in an unevaluated context in C++11.
2627   if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2628     return BuildPossibleImplicitMemberExpr(SS,
2629                                            /*TemplateKWLoc=*/SourceLocation(),
2630                                            R, /*TemplateArgs=*/nullptr, S);
2631 
2632   return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2633 }
2634 
2635 /// The parser has read a name in, and Sema has detected that we're currently
2636 /// inside an ObjC method. Perform some additional checks and determine if we
2637 /// should form a reference to an ivar.
2638 ///
2639 /// Ideally, most of this would be done by lookup, but there's
2640 /// actually quite a lot of extra work involved.
2641 DeclResult Sema::LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S,
2642                                         IdentifierInfo *II) {
2643   SourceLocation Loc = Lookup.getNameLoc();
2644   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2645 
2646   // Check for error condition which is already reported.
2647   if (!CurMethod)
2648     return DeclResult(true);
2649 
2650   // There are two cases to handle here.  1) scoped lookup could have failed,
2651   // in which case we should look for an ivar.  2) scoped lookup could have
2652   // found a decl, but that decl is outside the current instance method (i.e.
2653   // a global variable).  In these two cases, we do a lookup for an ivar with
2654   // this name, if the lookup sucedes, we replace it our current decl.
2655 
2656   // If we're in a class method, we don't normally want to look for
2657   // ivars.  But if we don't find anything else, and there's an
2658   // ivar, that's an error.
2659   bool IsClassMethod = CurMethod->isClassMethod();
2660 
2661   bool LookForIvars;
2662   if (Lookup.empty())
2663     LookForIvars = true;
2664   else if (IsClassMethod)
2665     LookForIvars = false;
2666   else
2667     LookForIvars = (Lookup.isSingleResult() &&
2668                     Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2669   ObjCInterfaceDecl *IFace = nullptr;
2670   if (LookForIvars) {
2671     IFace = CurMethod->getClassInterface();
2672     ObjCInterfaceDecl *ClassDeclared;
2673     ObjCIvarDecl *IV = nullptr;
2674     if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2675       // Diagnose using an ivar in a class method.
2676       if (IsClassMethod) {
2677         Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
2678         return DeclResult(true);
2679       }
2680 
2681       // Diagnose the use of an ivar outside of the declaring class.
2682       if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2683           !declaresSameEntity(ClassDeclared, IFace) &&
2684           !getLangOpts().DebuggerSupport)
2685         Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
2686 
2687       // Success.
2688       return IV;
2689     }
2690   } else if (CurMethod->isInstanceMethod()) {
2691     // We should warn if a local variable hides an ivar.
2692     if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2693       ObjCInterfaceDecl *ClassDeclared;
2694       if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2695         if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2696             declaresSameEntity(IFace, ClassDeclared))
2697           Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2698       }
2699     }
2700   } else if (Lookup.isSingleResult() &&
2701              Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2702     // If accessing a stand-alone ivar in a class method, this is an error.
2703     if (const ObjCIvarDecl *IV =
2704             dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) {
2705       Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
2706       return DeclResult(true);
2707     }
2708   }
2709 
2710   // Didn't encounter an error, didn't find an ivar.
2711   return DeclResult(false);
2712 }
2713 
2714 ExprResult Sema::BuildIvarRefExpr(Scope *S, SourceLocation Loc,
2715                                   ObjCIvarDecl *IV) {
2716   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2717   assert(CurMethod && CurMethod->isInstanceMethod() &&
2718          "should not reference ivar from this context");
2719 
2720   ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
2721   assert(IFace && "should not reference ivar from this context");
2722 
2723   // If we're referencing an invalid decl, just return this as a silent
2724   // error node.  The error diagnostic was already emitted on the decl.
2725   if (IV->isInvalidDecl())
2726     return ExprError();
2727 
2728   // Check if referencing a field with __attribute__((deprecated)).
2729   if (DiagnoseUseOfDecl(IV, Loc))
2730     return ExprError();
2731 
2732   // FIXME: This should use a new expr for a direct reference, don't
2733   // turn this into Self->ivar, just return a BareIVarExpr or something.
2734   IdentifierInfo &II = Context.Idents.get("self");
2735   UnqualifiedId SelfName;
2736   SelfName.setIdentifier(&II, SourceLocation());
2737   SelfName.setKind(UnqualifiedIdKind::IK_ImplicitSelfParam);
2738   CXXScopeSpec SelfScopeSpec;
2739   SourceLocation TemplateKWLoc;
2740   ExprResult SelfExpr =
2741       ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName,
2742                         /*HasTrailingLParen=*/false,
2743                         /*IsAddressOfOperand=*/false);
2744   if (SelfExpr.isInvalid())
2745     return ExprError();
2746 
2747   SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2748   if (SelfExpr.isInvalid())
2749     return ExprError();
2750 
2751   MarkAnyDeclReferenced(Loc, IV, true);
2752 
2753   ObjCMethodFamily MF = CurMethod->getMethodFamily();
2754   if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2755       !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2756     Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2757 
2758   ObjCIvarRefExpr *Result = new (Context)
2759       ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2760                       IV->getLocation(), SelfExpr.get(), true, true);
2761 
2762   if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2763     if (!isUnevaluatedContext() &&
2764         !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2765       getCurFunction()->recordUseOfWeak(Result);
2766   }
2767   if (getLangOpts().ObjCAutoRefCount)
2768     if (const BlockDecl *BD = CurContext->getInnermostBlockDecl())
2769       ImplicitlyRetainedSelfLocs.push_back({Loc, BD});
2770 
2771   return Result;
2772 }
2773 
2774 /// The parser has read a name in, and Sema has detected that we're currently
2775 /// inside an ObjC method. Perform some additional checks and determine if we
2776 /// should form a reference to an ivar. If so, build an expression referencing
2777 /// that ivar.
2778 ExprResult
2779 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2780                          IdentifierInfo *II, bool AllowBuiltinCreation) {
2781   // FIXME: Integrate this lookup step into LookupParsedName.
2782   DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II);
2783   if (Ivar.isInvalid())
2784     return ExprError();
2785   if (Ivar.isUsable())
2786     return BuildIvarRefExpr(S, Lookup.getNameLoc(),
2787                             cast<ObjCIvarDecl>(Ivar.get()));
2788 
2789   if (Lookup.empty() && II && AllowBuiltinCreation)
2790     LookupBuiltin(Lookup);
2791 
2792   // Sentinel value saying that we didn't do anything special.
2793   return ExprResult(false);
2794 }
2795 
2796 /// Cast a base object to a member's actual type.
2797 ///
2798 /// Logically this happens in three phases:
2799 ///
2800 /// * First we cast from the base type to the naming class.
2801 ///   The naming class is the class into which we were looking
2802 ///   when we found the member;  it's the qualifier type if a
2803 ///   qualifier was provided, and otherwise it's the base type.
2804 ///
2805 /// * Next we cast from the naming class to the declaring class.
2806 ///   If the member we found was brought into a class's scope by
2807 ///   a using declaration, this is that class;  otherwise it's
2808 ///   the class declaring the member.
2809 ///
2810 /// * Finally we cast from the declaring class to the "true"
2811 ///   declaring class of the member.  This conversion does not
2812 ///   obey access control.
2813 ExprResult
2814 Sema::PerformObjectMemberConversion(Expr *From,
2815                                     NestedNameSpecifier *Qualifier,
2816                                     NamedDecl *FoundDecl,
2817                                     NamedDecl *Member) {
2818   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2819   if (!RD)
2820     return From;
2821 
2822   QualType DestRecordType;
2823   QualType DestType;
2824   QualType FromRecordType;
2825   QualType FromType = From->getType();
2826   bool PointerConversions = false;
2827   if (isa<FieldDecl>(Member)) {
2828     DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2829     auto FromPtrType = FromType->getAs<PointerType>();
2830     DestRecordType = Context.getAddrSpaceQualType(
2831         DestRecordType, FromPtrType
2832                             ? FromType->getPointeeType().getAddressSpace()
2833                             : FromType.getAddressSpace());
2834 
2835     if (FromPtrType) {
2836       DestType = Context.getPointerType(DestRecordType);
2837       FromRecordType = FromPtrType->getPointeeType();
2838       PointerConversions = true;
2839     } else {
2840       DestType = DestRecordType;
2841       FromRecordType = FromType;
2842     }
2843   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2844     if (Method->isStatic())
2845       return From;
2846 
2847     DestType = Method->getThisType();
2848     DestRecordType = DestType->getPointeeType();
2849 
2850     if (FromType->getAs<PointerType>()) {
2851       FromRecordType = FromType->getPointeeType();
2852       PointerConversions = true;
2853     } else {
2854       FromRecordType = FromType;
2855       DestType = DestRecordType;
2856     }
2857 
2858     LangAS FromAS = FromRecordType.getAddressSpace();
2859     LangAS DestAS = DestRecordType.getAddressSpace();
2860     if (FromAS != DestAS) {
2861       QualType FromRecordTypeWithoutAS =
2862           Context.removeAddrSpaceQualType(FromRecordType);
2863       QualType FromTypeWithDestAS =
2864           Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS);
2865       if (PointerConversions)
2866         FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS);
2867       From = ImpCastExprToType(From, FromTypeWithDestAS,
2868                                CK_AddressSpaceConversion, From->getValueKind())
2869                  .get();
2870     }
2871   } else {
2872     // No conversion necessary.
2873     return From;
2874   }
2875 
2876   if (DestType->isDependentType() || FromType->isDependentType())
2877     return From;
2878 
2879   // If the unqualified types are the same, no conversion is necessary.
2880   if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2881     return From;
2882 
2883   SourceRange FromRange = From->getSourceRange();
2884   SourceLocation FromLoc = FromRange.getBegin();
2885 
2886   ExprValueKind VK = From->getValueKind();
2887 
2888   // C++ [class.member.lookup]p8:
2889   //   [...] Ambiguities can often be resolved by qualifying a name with its
2890   //   class name.
2891   //
2892   // If the member was a qualified name and the qualified referred to a
2893   // specific base subobject type, we'll cast to that intermediate type
2894   // first and then to the object in which the member is declared. That allows
2895   // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2896   //
2897   //   class Base { public: int x; };
2898   //   class Derived1 : public Base { };
2899   //   class Derived2 : public Base { };
2900   //   class VeryDerived : public Derived1, public Derived2 { void f(); };
2901   //
2902   //   void VeryDerived::f() {
2903   //     x = 17; // error: ambiguous base subobjects
2904   //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
2905   //   }
2906   if (Qualifier && Qualifier->getAsType()) {
2907     QualType QType = QualType(Qualifier->getAsType(), 0);
2908     assert(QType->isRecordType() && "lookup done with non-record type");
2909 
2910     QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2911 
2912     // In C++98, the qualifier type doesn't actually have to be a base
2913     // type of the object type, in which case we just ignore it.
2914     // Otherwise build the appropriate casts.
2915     if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
2916       CXXCastPath BasePath;
2917       if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2918                                        FromLoc, FromRange, &BasePath))
2919         return ExprError();
2920 
2921       if (PointerConversions)
2922         QType = Context.getPointerType(QType);
2923       From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2924                                VK, &BasePath).get();
2925 
2926       FromType = QType;
2927       FromRecordType = QRecordType;
2928 
2929       // If the qualifier type was the same as the destination type,
2930       // we're done.
2931       if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2932         return From;
2933     }
2934   }
2935 
2936   bool IgnoreAccess = false;
2937 
2938   // If we actually found the member through a using declaration, cast
2939   // down to the using declaration's type.
2940   //
2941   // Pointer equality is fine here because only one declaration of a
2942   // class ever has member declarations.
2943   if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2944     assert(isa<UsingShadowDecl>(FoundDecl));
2945     QualType URecordType = Context.getTypeDeclType(
2946                            cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2947 
2948     // We only need to do this if the naming-class to declaring-class
2949     // conversion is non-trivial.
2950     if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2951       assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType));
2952       CXXCastPath BasePath;
2953       if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2954                                        FromLoc, FromRange, &BasePath))
2955         return ExprError();
2956 
2957       QualType UType = URecordType;
2958       if (PointerConversions)
2959         UType = Context.getPointerType(UType);
2960       From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2961                                VK, &BasePath).get();
2962       FromType = UType;
2963       FromRecordType = URecordType;
2964     }
2965 
2966     // We don't do access control for the conversion from the
2967     // declaring class to the true declaring class.
2968     IgnoreAccess = true;
2969   }
2970 
2971   CXXCastPath BasePath;
2972   if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2973                                    FromLoc, FromRange, &BasePath,
2974                                    IgnoreAccess))
2975     return ExprError();
2976 
2977   return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2978                            VK, &BasePath);
2979 }
2980 
2981 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2982                                       const LookupResult &R,
2983                                       bool HasTrailingLParen) {
2984   // Only when used directly as the postfix-expression of a call.
2985   if (!HasTrailingLParen)
2986     return false;
2987 
2988   // Never if a scope specifier was provided.
2989   if (SS.isSet())
2990     return false;
2991 
2992   // Only in C++ or ObjC++.
2993   if (!getLangOpts().CPlusPlus)
2994     return false;
2995 
2996   // Turn off ADL when we find certain kinds of declarations during
2997   // normal lookup:
2998   for (NamedDecl *D : R) {
2999     // C++0x [basic.lookup.argdep]p3:
3000     //     -- a declaration of a class member
3001     // Since using decls preserve this property, we check this on the
3002     // original decl.
3003     if (D->isCXXClassMember())
3004       return false;
3005 
3006     // C++0x [basic.lookup.argdep]p3:
3007     //     -- a block-scope function declaration that is not a
3008     //        using-declaration
3009     // NOTE: we also trigger this for function templates (in fact, we
3010     // don't check the decl type at all, since all other decl types
3011     // turn off ADL anyway).
3012     if (isa<UsingShadowDecl>(D))
3013       D = cast<UsingShadowDecl>(D)->getTargetDecl();
3014     else if (D->getLexicalDeclContext()->isFunctionOrMethod())
3015       return false;
3016 
3017     // C++0x [basic.lookup.argdep]p3:
3018     //     -- a declaration that is neither a function or a function
3019     //        template
3020     // And also for builtin functions.
3021     if (isa<FunctionDecl>(D)) {
3022       FunctionDecl *FDecl = cast<FunctionDecl>(D);
3023 
3024       // But also builtin functions.
3025       if (FDecl->getBuiltinID() && FDecl->isImplicit())
3026         return false;
3027     } else if (!isa<FunctionTemplateDecl>(D))
3028       return false;
3029   }
3030 
3031   return true;
3032 }
3033 
3034 
3035 /// Diagnoses obvious problems with the use of the given declaration
3036 /// as an expression.  This is only actually called for lookups that
3037 /// were not overloaded, and it doesn't promise that the declaration
3038 /// will in fact be used.
3039 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
3040   if (D->isInvalidDecl())
3041     return true;
3042 
3043   if (isa<TypedefNameDecl>(D)) {
3044     S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
3045     return true;
3046   }
3047 
3048   if (isa<ObjCInterfaceDecl>(D)) {
3049     S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
3050     return true;
3051   }
3052 
3053   if (isa<NamespaceDecl>(D)) {
3054     S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
3055     return true;
3056   }
3057 
3058   return false;
3059 }
3060 
3061 // Certain multiversion types should be treated as overloaded even when there is
3062 // only one result.
3063 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) {
3064   assert(R.isSingleResult() && "Expected only a single result");
3065   const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
3066   return FD &&
3067          (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
3068 }
3069 
3070 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
3071                                           LookupResult &R, bool NeedsADL,
3072                                           bool AcceptInvalidDecl) {
3073   // If this is a single, fully-resolved result and we don't need ADL,
3074   // just build an ordinary singleton decl ref.
3075   if (!NeedsADL && R.isSingleResult() &&
3076       !R.getAsSingle<FunctionTemplateDecl>() &&
3077       !ShouldLookupResultBeMultiVersionOverload(R))
3078     return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
3079                                     R.getRepresentativeDecl(), nullptr,
3080                                     AcceptInvalidDecl);
3081 
3082   // We only need to check the declaration if there's exactly one
3083   // result, because in the overloaded case the results can only be
3084   // functions and function templates.
3085   if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) &&
3086       CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
3087     return ExprError();
3088 
3089   // Otherwise, just build an unresolved lookup expression.  Suppress
3090   // any lookup-related diagnostics; we'll hash these out later, when
3091   // we've picked a target.
3092   R.suppressDiagnostics();
3093 
3094   UnresolvedLookupExpr *ULE
3095     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
3096                                    SS.getWithLocInContext(Context),
3097                                    R.getLookupNameInfo(),
3098                                    NeedsADL, R.isOverloadedResult(),
3099                                    R.begin(), R.end());
3100 
3101   return ULE;
3102 }
3103 
3104 static void
3105 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
3106                                    ValueDecl *var, DeclContext *DC);
3107 
3108 /// Complete semantic analysis for a reference to the given declaration.
3109 ExprResult Sema::BuildDeclarationNameExpr(
3110     const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
3111     NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
3112     bool AcceptInvalidDecl) {
3113   assert(D && "Cannot refer to a NULL declaration");
3114   assert(!isa<FunctionTemplateDecl>(D) &&
3115          "Cannot refer unambiguously to a function template");
3116 
3117   SourceLocation Loc = NameInfo.getLoc();
3118   if (CheckDeclInExpr(*this, Loc, D))
3119     return ExprError();
3120 
3121   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
3122     // Specifically diagnose references to class templates that are missing
3123     // a template argument list.
3124     diagnoseMissingTemplateArguments(TemplateName(Template), Loc);
3125     return ExprError();
3126   }
3127 
3128   // Make sure that we're referring to a value.
3129   ValueDecl *VD = dyn_cast<ValueDecl>(D);
3130   if (!VD) {
3131     Diag(Loc, diag::err_ref_non_value)
3132       << D << SS.getRange();
3133     Diag(D->getLocation(), diag::note_declared_at);
3134     return ExprError();
3135   }
3136 
3137   // Check whether this declaration can be used. Note that we suppress
3138   // this check when we're going to perform argument-dependent lookup
3139   // on this function name, because this might not be the function
3140   // that overload resolution actually selects.
3141   if (DiagnoseUseOfDecl(VD, Loc))
3142     return ExprError();
3143 
3144   // Only create DeclRefExpr's for valid Decl's.
3145   if (VD->isInvalidDecl() && !AcceptInvalidDecl)
3146     return ExprError();
3147 
3148   // Handle members of anonymous structs and unions.  If we got here,
3149   // and the reference is to a class member indirect field, then this
3150   // must be the subject of a pointer-to-member expression.
3151   if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
3152     if (!indirectField->isCXXClassMember())
3153       return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
3154                                                       indirectField);
3155 
3156   {
3157     QualType type = VD->getType();
3158     if (type.isNull())
3159       return ExprError();
3160     ExprValueKind valueKind = VK_RValue;
3161 
3162     // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of
3163     // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value,
3164     // is expanded by some outer '...' in the context of the use.
3165     type = type.getNonPackExpansionType();
3166 
3167     switch (D->getKind()) {
3168     // Ignore all the non-ValueDecl kinds.
3169 #define ABSTRACT_DECL(kind)
3170 #define VALUE(type, base)
3171 #define DECL(type, base) \
3172     case Decl::type:
3173 #include "clang/AST/DeclNodes.inc"
3174       llvm_unreachable("invalid value decl kind");
3175 
3176     // These shouldn't make it here.
3177     case Decl::ObjCAtDefsField:
3178       llvm_unreachable("forming non-member reference to ivar?");
3179 
3180     // Enum constants are always r-values and never references.
3181     // Unresolved using declarations are dependent.
3182     case Decl::EnumConstant:
3183     case Decl::UnresolvedUsingValue:
3184     case Decl::OMPDeclareReduction:
3185     case Decl::OMPDeclareMapper:
3186       valueKind = VK_RValue;
3187       break;
3188 
3189     // Fields and indirect fields that got here must be for
3190     // pointer-to-member expressions; we just call them l-values for
3191     // internal consistency, because this subexpression doesn't really
3192     // exist in the high-level semantics.
3193     case Decl::Field:
3194     case Decl::IndirectField:
3195     case Decl::ObjCIvar:
3196       assert(getLangOpts().CPlusPlus &&
3197              "building reference to field in C?");
3198 
3199       // These can't have reference type in well-formed programs, but
3200       // for internal consistency we do this anyway.
3201       type = type.getNonReferenceType();
3202       valueKind = VK_LValue;
3203       break;
3204 
3205     // Non-type template parameters are either l-values or r-values
3206     // depending on the type.
3207     case Decl::NonTypeTemplateParm: {
3208       if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
3209         type = reftype->getPointeeType();
3210         valueKind = VK_LValue; // even if the parameter is an r-value reference
3211         break;
3212       }
3213 
3214       // For non-references, we need to strip qualifiers just in case
3215       // the template parameter was declared as 'const int' or whatever.
3216       valueKind = VK_RValue;
3217       type = type.getUnqualifiedType();
3218       break;
3219     }
3220 
3221     case Decl::Var:
3222     case Decl::VarTemplateSpecialization:
3223     case Decl::VarTemplatePartialSpecialization:
3224     case Decl::Decomposition:
3225     case Decl::OMPCapturedExpr:
3226       // In C, "extern void blah;" is valid and is an r-value.
3227       if (!getLangOpts().CPlusPlus &&
3228           !type.hasQualifiers() &&
3229           type->isVoidType()) {
3230         valueKind = VK_RValue;
3231         break;
3232       }
3233       LLVM_FALLTHROUGH;
3234 
3235     case Decl::ImplicitParam:
3236     case Decl::ParmVar: {
3237       // These are always l-values.
3238       valueKind = VK_LValue;
3239       type = type.getNonReferenceType();
3240 
3241       // FIXME: Does the addition of const really only apply in
3242       // potentially-evaluated contexts? Since the variable isn't actually
3243       // captured in an unevaluated context, it seems that the answer is no.
3244       if (!isUnevaluatedContext()) {
3245         QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
3246         if (!CapturedType.isNull())
3247           type = CapturedType;
3248       }
3249 
3250       break;
3251     }
3252 
3253     case Decl::Binding: {
3254       // These are always lvalues.
3255       valueKind = VK_LValue;
3256       type = type.getNonReferenceType();
3257       // FIXME: Support lambda-capture of BindingDecls, once CWG actually
3258       // decides how that's supposed to work.
3259       auto *BD = cast<BindingDecl>(VD);
3260       if (BD->getDeclContext() != CurContext) {
3261         auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl());
3262         if (DD && DD->hasLocalStorage())
3263           diagnoseUncapturableValueReference(*this, Loc, BD, CurContext);
3264       }
3265       break;
3266     }
3267 
3268     case Decl::Function: {
3269       if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
3270         if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
3271           type = Context.BuiltinFnTy;
3272           valueKind = VK_RValue;
3273           break;
3274         }
3275       }
3276 
3277       const FunctionType *fty = type->castAs<FunctionType>();
3278 
3279       // If we're referring to a function with an __unknown_anytype
3280       // result type, make the entire expression __unknown_anytype.
3281       if (fty->getReturnType() == Context.UnknownAnyTy) {
3282         type = Context.UnknownAnyTy;
3283         valueKind = VK_RValue;
3284         break;
3285       }
3286 
3287       // Functions are l-values in C++.
3288       if (getLangOpts().CPlusPlus) {
3289         valueKind = VK_LValue;
3290         break;
3291       }
3292 
3293       // C99 DR 316 says that, if a function type comes from a
3294       // function definition (without a prototype), that type is only
3295       // used for checking compatibility. Therefore, when referencing
3296       // the function, we pretend that we don't have the full function
3297       // type.
3298       if (!cast<FunctionDecl>(VD)->hasPrototype() &&
3299           isa<FunctionProtoType>(fty))
3300         type = Context.getFunctionNoProtoType(fty->getReturnType(),
3301                                               fty->getExtInfo());
3302 
3303       // Functions are r-values in C.
3304       valueKind = VK_RValue;
3305       break;
3306     }
3307 
3308     case Decl::CXXDeductionGuide:
3309       llvm_unreachable("building reference to deduction guide");
3310 
3311     case Decl::MSProperty:
3312     case Decl::MSGuid:
3313       // FIXME: Should MSGuidDecl be subject to capture in OpenMP,
3314       // or duplicated between host and device?
3315       valueKind = VK_LValue;
3316       break;
3317 
3318     case Decl::CXXMethod:
3319       // If we're referring to a method with an __unknown_anytype
3320       // result type, make the entire expression __unknown_anytype.
3321       // This should only be possible with a type written directly.
3322       if (const FunctionProtoType *proto
3323             = dyn_cast<FunctionProtoType>(VD->getType()))
3324         if (proto->getReturnType() == Context.UnknownAnyTy) {
3325           type = Context.UnknownAnyTy;
3326           valueKind = VK_RValue;
3327           break;
3328         }
3329 
3330       // C++ methods are l-values if static, r-values if non-static.
3331       if (cast<CXXMethodDecl>(VD)->isStatic()) {
3332         valueKind = VK_LValue;
3333         break;
3334       }
3335       LLVM_FALLTHROUGH;
3336 
3337     case Decl::CXXConversion:
3338     case Decl::CXXDestructor:
3339     case Decl::CXXConstructor:
3340       valueKind = VK_RValue;
3341       break;
3342     }
3343 
3344     return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3345                             /*FIXME: TemplateKWLoc*/ SourceLocation(),
3346                             TemplateArgs);
3347   }
3348 }
3349 
3350 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3351                                     SmallString<32> &Target) {
3352   Target.resize(CharByteWidth * (Source.size() + 1));
3353   char *ResultPtr = &Target[0];
3354   const llvm::UTF8 *ErrorPtr;
3355   bool success =
3356       llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3357   (void)success;
3358   assert(success);
3359   Target.resize(ResultPtr - &Target[0]);
3360 }
3361 
3362 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3363                                      PredefinedExpr::IdentKind IK) {
3364   // Pick the current block, lambda, captured statement or function.
3365   Decl *currentDecl = nullptr;
3366   if (const BlockScopeInfo *BSI = getCurBlock())
3367     currentDecl = BSI->TheDecl;
3368   else if (const LambdaScopeInfo *LSI = getCurLambda())
3369     currentDecl = LSI->CallOperator;
3370   else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3371     currentDecl = CSI->TheCapturedDecl;
3372   else
3373     currentDecl = getCurFunctionOrMethodDecl();
3374 
3375   if (!currentDecl) {
3376     Diag(Loc, diag::ext_predef_outside_function);
3377     currentDecl = Context.getTranslationUnitDecl();
3378   }
3379 
3380   QualType ResTy;
3381   StringLiteral *SL = nullptr;
3382   if (cast<DeclContext>(currentDecl)->isDependentContext())
3383     ResTy = Context.DependentTy;
3384   else {
3385     // Pre-defined identifiers are of type char[x], where x is the length of
3386     // the string.
3387     auto Str = PredefinedExpr::ComputeName(IK, currentDecl);
3388     unsigned Length = Str.length();
3389 
3390     llvm::APInt LengthI(32, Length + 1);
3391     if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) {
3392       ResTy =
3393           Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst());
3394       SmallString<32> RawChars;
3395       ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3396                               Str, RawChars);
3397       ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3398                                            ArrayType::Normal,
3399                                            /*IndexTypeQuals*/ 0);
3400       SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3401                                  /*Pascal*/ false, ResTy, Loc);
3402     } else {
3403       ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
3404       ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3405                                            ArrayType::Normal,
3406                                            /*IndexTypeQuals*/ 0);
3407       SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3408                                  /*Pascal*/ false, ResTy, Loc);
3409     }
3410   }
3411 
3412   return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL);
3413 }
3414 
3415 static std::pair<QualType, StringLiteral *>
3416 GetUniqueStableNameInfo(ASTContext &Context, QualType OpType,
3417                         SourceLocation OpLoc, PredefinedExpr::IdentKind K) {
3418   std::pair<QualType, StringLiteral*> Result{{}, nullptr};
3419 
3420   if (OpType->isDependentType()) {
3421       Result.first = Context.DependentTy;
3422       return Result;
3423   }
3424 
3425   std::string Str = PredefinedExpr::ComputeName(Context, K, OpType);
3426   llvm::APInt Length(32, Str.length() + 1);
3427   Result.first =
3428       Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
3429   Result.first = Context.getConstantArrayType(
3430       Result.first, Length, nullptr, ArrayType::Normal, /*IndexTypeQuals*/ 0);
3431   Result.second = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3432                                         /*Pascal*/ false, Result.first, OpLoc);
3433   return Result;
3434 }
3435 
3436 ExprResult Sema::BuildUniqueStableName(SourceLocation OpLoc,
3437                                        TypeSourceInfo *Operand) {
3438   QualType ResultTy;
3439   StringLiteral *SL;
3440   std::tie(ResultTy, SL) = GetUniqueStableNameInfo(
3441       Context, Operand->getType(), OpLoc, PredefinedExpr::UniqueStableNameType);
3442 
3443   return PredefinedExpr::Create(Context, OpLoc, ResultTy,
3444                                 PredefinedExpr::UniqueStableNameType, SL,
3445                                 Operand);
3446 }
3447 
3448 ExprResult Sema::BuildUniqueStableName(SourceLocation OpLoc,
3449                                        Expr *E) {
3450   QualType ResultTy;
3451   StringLiteral *SL;
3452   std::tie(ResultTy, SL) = GetUniqueStableNameInfo(
3453       Context, E->getType(), OpLoc, PredefinedExpr::UniqueStableNameExpr);
3454 
3455   return PredefinedExpr::Create(Context, OpLoc, ResultTy,
3456                                 PredefinedExpr::UniqueStableNameExpr, SL, E);
3457 }
3458 
3459 ExprResult Sema::ActOnUniqueStableNameExpr(SourceLocation OpLoc,
3460                                            SourceLocation L, SourceLocation R,
3461                                            ParsedType Ty) {
3462   TypeSourceInfo *TInfo = nullptr;
3463   QualType T = GetTypeFromParser(Ty, &TInfo);
3464 
3465   if (T.isNull())
3466     return ExprError();
3467   if (!TInfo)
3468     TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
3469 
3470   return BuildUniqueStableName(OpLoc, TInfo);
3471 }
3472 
3473 ExprResult Sema::ActOnUniqueStableNameExpr(SourceLocation OpLoc,
3474                                            SourceLocation L, SourceLocation R,
3475                                            Expr *E) {
3476   return BuildUniqueStableName(OpLoc, E);
3477 }
3478 
3479 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3480   PredefinedExpr::IdentKind IK;
3481 
3482   switch (Kind) {
3483   default: llvm_unreachable("Unknown simple primary expr!");
3484   case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3485   case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break;
3486   case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS]
3487   case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS]
3488   case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS]
3489   case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS]
3490   case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break;
3491   }
3492 
3493   return BuildPredefinedExpr(Loc, IK);
3494 }
3495 
3496 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3497   SmallString<16> CharBuffer;
3498   bool Invalid = false;
3499   StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3500   if (Invalid)
3501     return ExprError();
3502 
3503   CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3504                             PP, Tok.getKind());
3505   if (Literal.hadError())
3506     return ExprError();
3507 
3508   QualType Ty;
3509   if (Literal.isWide())
3510     Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3511   else if (Literal.isUTF8() && getLangOpts().Char8)
3512     Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3513   else if (Literal.isUTF16())
3514     Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3515   else if (Literal.isUTF32())
3516     Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3517   else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3518     Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
3519   else
3520     Ty = Context.CharTy;  // 'x' -> char in C++
3521 
3522   CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3523   if (Literal.isWide())
3524     Kind = CharacterLiteral::Wide;
3525   else if (Literal.isUTF16())
3526     Kind = CharacterLiteral::UTF16;
3527   else if (Literal.isUTF32())
3528     Kind = CharacterLiteral::UTF32;
3529   else if (Literal.isUTF8())
3530     Kind = CharacterLiteral::UTF8;
3531 
3532   Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3533                                              Tok.getLocation());
3534 
3535   if (Literal.getUDSuffix().empty())
3536     return Lit;
3537 
3538   // We're building a user-defined literal.
3539   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3540   SourceLocation UDSuffixLoc =
3541     getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3542 
3543   // Make sure we're allowed user-defined literals here.
3544   if (!UDLScope)
3545     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3546 
3547   // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3548   //   operator "" X (ch)
3549   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3550                                         Lit, Tok.getLocation());
3551 }
3552 
3553 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3554   unsigned IntSize = Context.getTargetInfo().getIntWidth();
3555   return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3556                                 Context.IntTy, Loc);
3557 }
3558 
3559 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3560                                   QualType Ty, SourceLocation Loc) {
3561   const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3562 
3563   using llvm::APFloat;
3564   APFloat Val(Format);
3565 
3566   APFloat::opStatus result = Literal.GetFloatValue(Val);
3567 
3568   // Overflow is always an error, but underflow is only an error if
3569   // we underflowed to zero (APFloat reports denormals as underflow).
3570   if ((result & APFloat::opOverflow) ||
3571       ((result & APFloat::opUnderflow) && Val.isZero())) {
3572     unsigned diagnostic;
3573     SmallString<20> buffer;
3574     if (result & APFloat::opOverflow) {
3575       diagnostic = diag::warn_float_overflow;
3576       APFloat::getLargest(Format).toString(buffer);
3577     } else {
3578       diagnostic = diag::warn_float_underflow;
3579       APFloat::getSmallest(Format).toString(buffer);
3580     }
3581 
3582     S.Diag(Loc, diagnostic)
3583       << Ty
3584       << StringRef(buffer.data(), buffer.size());
3585   }
3586 
3587   bool isExact = (result == APFloat::opOK);
3588   return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3589 }
3590 
3591 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3592   assert(E && "Invalid expression");
3593 
3594   if (E->isValueDependent())
3595     return false;
3596 
3597   QualType QT = E->getType();
3598   if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3599     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3600     return true;
3601   }
3602 
3603   llvm::APSInt ValueAPS;
3604   ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3605 
3606   if (R.isInvalid())
3607     return true;
3608 
3609   bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3610   if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3611     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3612         << ValueAPS.toString(10) << ValueIsPositive;
3613     return true;
3614   }
3615 
3616   return false;
3617 }
3618 
3619 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3620   // Fast path for a single digit (which is quite common).  A single digit
3621   // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3622   if (Tok.getLength() == 1) {
3623     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3624     return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3625   }
3626 
3627   SmallString<128> SpellingBuffer;
3628   // NumericLiteralParser wants to overread by one character.  Add padding to
3629   // the buffer in case the token is copied to the buffer.  If getSpelling()
3630   // returns a StringRef to the memory buffer, it should have a null char at
3631   // the EOF, so it is also safe.
3632   SpellingBuffer.resize(Tok.getLength() + 1);
3633 
3634   // Get the spelling of the token, which eliminates trigraphs, etc.
3635   bool Invalid = false;
3636   StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3637   if (Invalid)
3638     return ExprError();
3639 
3640   NumericLiteralParser Literal(TokSpelling, Tok.getLocation(),
3641                                PP.getSourceManager(), PP.getLangOpts(),
3642                                PP.getTargetInfo(), PP.getDiagnostics());
3643   if (Literal.hadError)
3644     return ExprError();
3645 
3646   if (Literal.hasUDSuffix()) {
3647     // We're building a user-defined literal.
3648     IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3649     SourceLocation UDSuffixLoc =
3650       getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3651 
3652     // Make sure we're allowed user-defined literals here.
3653     if (!UDLScope)
3654       return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3655 
3656     QualType CookedTy;
3657     if (Literal.isFloatingLiteral()) {
3658       // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3659       // long double, the literal is treated as a call of the form
3660       //   operator "" X (f L)
3661       CookedTy = Context.LongDoubleTy;
3662     } else {
3663       // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3664       // unsigned long long, the literal is treated as a call of the form
3665       //   operator "" X (n ULL)
3666       CookedTy = Context.UnsignedLongLongTy;
3667     }
3668 
3669     DeclarationName OpName =
3670       Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3671     DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3672     OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3673 
3674     SourceLocation TokLoc = Tok.getLocation();
3675 
3676     // Perform literal operator lookup to determine if we're building a raw
3677     // literal or a cooked one.
3678     LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3679     switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3680                                   /*AllowRaw*/ true, /*AllowTemplate*/ true,
3681                                   /*AllowStringTemplate*/ false,
3682                                   /*DiagnoseMissing*/ !Literal.isImaginary)) {
3683     case LOLR_ErrorNoDiagnostic:
3684       // Lookup failure for imaginary constants isn't fatal, there's still the
3685       // GNU extension producing _Complex types.
3686       break;
3687     case LOLR_Error:
3688       return ExprError();
3689     case LOLR_Cooked: {
3690       Expr *Lit;
3691       if (Literal.isFloatingLiteral()) {
3692         Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3693       } else {
3694         llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3695         if (Literal.GetIntegerValue(ResultVal))
3696           Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3697               << /* Unsigned */ 1;
3698         Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3699                                      Tok.getLocation());
3700       }
3701       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3702     }
3703 
3704     case LOLR_Raw: {
3705       // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3706       // literal is treated as a call of the form
3707       //   operator "" X ("n")
3708       unsigned Length = Literal.getUDSuffixOffset();
3709       QualType StrTy = Context.getConstantArrayType(
3710           Context.adjustStringLiteralBaseType(Context.CharTy.withConst()),
3711           llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0);
3712       Expr *Lit = StringLiteral::Create(
3713           Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3714           /*Pascal*/false, StrTy, &TokLoc, 1);
3715       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3716     }
3717 
3718     case LOLR_Template: {
3719       // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3720       // template), L is treated as a call fo the form
3721       //   operator "" X <'c1', 'c2', ... 'ck'>()
3722       // where n is the source character sequence c1 c2 ... ck.
3723       TemplateArgumentListInfo ExplicitArgs;
3724       unsigned CharBits = Context.getIntWidth(Context.CharTy);
3725       bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3726       llvm::APSInt Value(CharBits, CharIsUnsigned);
3727       for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3728         Value = TokSpelling[I];
3729         TemplateArgument Arg(Context, Value, Context.CharTy);
3730         TemplateArgumentLocInfo ArgInfo;
3731         ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3732       }
3733       return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3734                                       &ExplicitArgs);
3735     }
3736     case LOLR_StringTemplate:
3737       llvm_unreachable("unexpected literal operator lookup result");
3738     }
3739   }
3740 
3741   Expr *Res;
3742 
3743   if (Literal.isFixedPointLiteral()) {
3744     QualType Ty;
3745 
3746     if (Literal.isAccum) {
3747       if (Literal.isHalf) {
3748         Ty = Context.ShortAccumTy;
3749       } else if (Literal.isLong) {
3750         Ty = Context.LongAccumTy;
3751       } else {
3752         Ty = Context.AccumTy;
3753       }
3754     } else if (Literal.isFract) {
3755       if (Literal.isHalf) {
3756         Ty = Context.ShortFractTy;
3757       } else if (Literal.isLong) {
3758         Ty = Context.LongFractTy;
3759       } else {
3760         Ty = Context.FractTy;
3761       }
3762     }
3763 
3764     if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
3765 
3766     bool isSigned = !Literal.isUnsigned;
3767     unsigned scale = Context.getFixedPointScale(Ty);
3768     unsigned bit_width = Context.getTypeInfo(Ty).Width;
3769 
3770     llvm::APInt Val(bit_width, 0, isSigned);
3771     bool Overflowed = Literal.GetFixedPointValue(Val, scale);
3772     bool ValIsZero = Val.isNullValue() && !Overflowed;
3773 
3774     auto MaxVal = Context.getFixedPointMax(Ty).getValue();
3775     if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
3776       // Clause 6.4.4 - The value of a constant shall be in the range of
3777       // representable values for its type, with exception for constants of a
3778       // fract type with a value of exactly 1; such a constant shall denote
3779       // the maximal value for the type.
3780       --Val;
3781     else if (Val.ugt(MaxVal) || Overflowed)
3782       Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
3783 
3784     Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty,
3785                                               Tok.getLocation(), scale);
3786   } else if (Literal.isFloatingLiteral()) {
3787     QualType Ty;
3788     if (Literal.isHalf){
3789       if (getOpenCLOptions().isEnabled("cl_khr_fp16"))
3790         Ty = Context.HalfTy;
3791       else {
3792         Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3793         return ExprError();
3794       }
3795     } else if (Literal.isFloat)
3796       Ty = Context.FloatTy;
3797     else if (Literal.isLong)
3798       Ty = Context.LongDoubleTy;
3799     else if (Literal.isFloat16)
3800       Ty = Context.Float16Ty;
3801     else if (Literal.isFloat128)
3802       Ty = Context.Float128Ty;
3803     else
3804       Ty = Context.DoubleTy;
3805 
3806     Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3807 
3808     if (Ty == Context.DoubleTy) {
3809       if (getLangOpts().SinglePrecisionConstants) {
3810         const BuiltinType *BTy = Ty->getAs<BuiltinType>();
3811         if (BTy->getKind() != BuiltinType::Float) {
3812           Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3813         }
3814       } else if (getLangOpts().OpenCL &&
3815                  !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
3816         // Impose single-precision float type when cl_khr_fp64 is not enabled.
3817         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
3818         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3819       }
3820     }
3821   } else if (!Literal.isIntegerLiteral()) {
3822     return ExprError();
3823   } else {
3824     QualType Ty;
3825 
3826     // 'long long' is a C99 or C++11 feature.
3827     if (!getLangOpts().C99 && Literal.isLongLong) {
3828       if (getLangOpts().CPlusPlus)
3829         Diag(Tok.getLocation(),
3830              getLangOpts().CPlusPlus11 ?
3831              diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3832       else
3833         Diag(Tok.getLocation(), diag::ext_c99_longlong);
3834     }
3835 
3836     // Get the value in the widest-possible width.
3837     unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3838     llvm::APInt ResultVal(MaxWidth, 0);
3839 
3840     if (Literal.GetIntegerValue(ResultVal)) {
3841       // If this value didn't fit into uintmax_t, error and force to ull.
3842       Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3843           << /* Unsigned */ 1;
3844       Ty = Context.UnsignedLongLongTy;
3845       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3846              "long long is not intmax_t?");
3847     } else {
3848       // If this value fits into a ULL, try to figure out what else it fits into
3849       // according to the rules of C99 6.4.4.1p5.
3850 
3851       // Octal, Hexadecimal, and integers with a U suffix are allowed to
3852       // be an unsigned int.
3853       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3854 
3855       // Check from smallest to largest, picking the smallest type we can.
3856       unsigned Width = 0;
3857 
3858       // Microsoft specific integer suffixes are explicitly sized.
3859       if (Literal.MicrosoftInteger) {
3860         if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3861           Width = 8;
3862           Ty = Context.CharTy;
3863         } else {
3864           Width = Literal.MicrosoftInteger;
3865           Ty = Context.getIntTypeForBitwidth(Width,
3866                                              /*Signed=*/!Literal.isUnsigned);
3867         }
3868       }
3869 
3870       if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
3871         // Are int/unsigned possibilities?
3872         unsigned IntSize = Context.getTargetInfo().getIntWidth();
3873 
3874         // Does it fit in a unsigned int?
3875         if (ResultVal.isIntN(IntSize)) {
3876           // Does it fit in a signed int?
3877           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3878             Ty = Context.IntTy;
3879           else if (AllowUnsigned)
3880             Ty = Context.UnsignedIntTy;
3881           Width = IntSize;
3882         }
3883       }
3884 
3885       // Are long/unsigned long possibilities?
3886       if (Ty.isNull() && !Literal.isLongLong) {
3887         unsigned LongSize = Context.getTargetInfo().getLongWidth();
3888 
3889         // Does it fit in a unsigned long?
3890         if (ResultVal.isIntN(LongSize)) {
3891           // Does it fit in a signed long?
3892           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3893             Ty = Context.LongTy;
3894           else if (AllowUnsigned)
3895             Ty = Context.UnsignedLongTy;
3896           // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
3897           // is compatible.
3898           else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
3899             const unsigned LongLongSize =
3900                 Context.getTargetInfo().getLongLongWidth();
3901             Diag(Tok.getLocation(),
3902                  getLangOpts().CPlusPlus
3903                      ? Literal.isLong
3904                            ? diag::warn_old_implicitly_unsigned_long_cxx
3905                            : /*C++98 UB*/ diag::
3906                                  ext_old_implicitly_unsigned_long_cxx
3907                      : diag::warn_old_implicitly_unsigned_long)
3908                 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
3909                                             : /*will be ill-formed*/ 1);
3910             Ty = Context.UnsignedLongTy;
3911           }
3912           Width = LongSize;
3913         }
3914       }
3915 
3916       // Check long long if needed.
3917       if (Ty.isNull()) {
3918         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3919 
3920         // Does it fit in a unsigned long long?
3921         if (ResultVal.isIntN(LongLongSize)) {
3922           // Does it fit in a signed long long?
3923           // To be compatible with MSVC, hex integer literals ending with the
3924           // LL or i64 suffix are always signed in Microsoft mode.
3925           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3926               (getLangOpts().MSVCCompat && Literal.isLongLong)))
3927             Ty = Context.LongLongTy;
3928           else if (AllowUnsigned)
3929             Ty = Context.UnsignedLongLongTy;
3930           Width = LongLongSize;
3931         }
3932       }
3933 
3934       // If we still couldn't decide a type, we probably have something that
3935       // does not fit in a signed long long, but has no U suffix.
3936       if (Ty.isNull()) {
3937         Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
3938         Ty = Context.UnsignedLongLongTy;
3939         Width = Context.getTargetInfo().getLongLongWidth();
3940       }
3941 
3942       if (ResultVal.getBitWidth() != Width)
3943         ResultVal = ResultVal.trunc(Width);
3944     }
3945     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3946   }
3947 
3948   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3949   if (Literal.isImaginary) {
3950     Res = new (Context) ImaginaryLiteral(Res,
3951                                         Context.getComplexType(Res->getType()));
3952 
3953     Diag(Tok.getLocation(), diag::ext_imaginary_constant);
3954   }
3955   return Res;
3956 }
3957 
3958 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
3959   assert(E && "ActOnParenExpr() missing expr");
3960   return new (Context) ParenExpr(L, R, E);
3961 }
3962 
3963 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3964                                          SourceLocation Loc,
3965                                          SourceRange ArgRange) {
3966   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3967   // scalar or vector data type argument..."
3968   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3969   // type (C99 6.2.5p18) or void.
3970   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3971     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3972       << T << ArgRange;
3973     return true;
3974   }
3975 
3976   assert((T->isVoidType() || !T->isIncompleteType()) &&
3977          "Scalar types should always be complete");
3978   return false;
3979 }
3980 
3981 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3982                                            SourceLocation Loc,
3983                                            SourceRange ArgRange,
3984                                            UnaryExprOrTypeTrait TraitKind) {
3985   // Invalid types must be hard errors for SFINAE in C++.
3986   if (S.LangOpts.CPlusPlus)
3987     return true;
3988 
3989   // C99 6.5.3.4p1:
3990   if (T->isFunctionType() &&
3991       (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
3992        TraitKind == UETT_PreferredAlignOf)) {
3993     // sizeof(function)/alignof(function) is allowed as an extension.
3994     S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3995         << getTraitSpelling(TraitKind) << ArgRange;
3996     return false;
3997   }
3998 
3999   // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
4000   // this is an error (OpenCL v1.1 s6.3.k)
4001   if (T->isVoidType()) {
4002     unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
4003                                         : diag::ext_sizeof_alignof_void_type;
4004     S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange;
4005     return false;
4006   }
4007 
4008   return true;
4009 }
4010 
4011 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
4012                                              SourceLocation Loc,
4013                                              SourceRange ArgRange,
4014                                              UnaryExprOrTypeTrait TraitKind) {
4015   // Reject sizeof(interface) and sizeof(interface<proto>) if the
4016   // runtime doesn't allow it.
4017   if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
4018     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
4019       << T << (TraitKind == UETT_SizeOf)
4020       << ArgRange;
4021     return true;
4022   }
4023 
4024   return false;
4025 }
4026 
4027 /// Check whether E is a pointer from a decayed array type (the decayed
4028 /// pointer type is equal to T) and emit a warning if it is.
4029 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
4030                                      Expr *E) {
4031   // Don't warn if the operation changed the type.
4032   if (T != E->getType())
4033     return;
4034 
4035   // Now look for array decays.
4036   ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
4037   if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
4038     return;
4039 
4040   S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
4041                                              << ICE->getType()
4042                                              << ICE->getSubExpr()->getType();
4043 }
4044 
4045 /// Check the constraints on expression operands to unary type expression
4046 /// and type traits.
4047 ///
4048 /// Completes any types necessary and validates the constraints on the operand
4049 /// expression. The logic mostly mirrors the type-based overload, but may modify
4050 /// the expression as it completes the type for that expression through template
4051 /// instantiation, etc.
4052 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
4053                                             UnaryExprOrTypeTrait ExprKind) {
4054   QualType ExprTy = E->getType();
4055   assert(!ExprTy->isReferenceType());
4056 
4057   bool IsUnevaluatedOperand =
4058       (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf ||
4059        ExprKind == UETT_PreferredAlignOf);
4060   if (IsUnevaluatedOperand) {
4061     ExprResult Result = CheckUnevaluatedOperand(E);
4062     if (Result.isInvalid())
4063       return true;
4064     E = Result.get();
4065   }
4066 
4067   if (ExprKind == UETT_VecStep)
4068     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
4069                                         E->getSourceRange());
4070 
4071   // Explicitly list some types as extensions.
4072   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
4073                                       E->getSourceRange(), ExprKind))
4074     return false;
4075 
4076   // 'alignof' applied to an expression only requires the base element type of
4077   // the expression to be complete. 'sizeof' requires the expression's type to
4078   // be complete (and will attempt to complete it if it's an array of unknown
4079   // bound).
4080   if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4081     if (RequireCompleteSizedType(
4082             E->getExprLoc(), Context.getBaseElementType(E->getType()),
4083             diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4084             getTraitSpelling(ExprKind), E->getSourceRange()))
4085       return true;
4086   } else {
4087     if (RequireCompleteSizedExprType(
4088             E, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4089             getTraitSpelling(ExprKind), E->getSourceRange()))
4090       return true;
4091   }
4092 
4093   // Completing the expression's type may have changed it.
4094   ExprTy = E->getType();
4095   assert(!ExprTy->isReferenceType());
4096 
4097   if (ExprTy->isFunctionType()) {
4098     Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
4099         << getTraitSpelling(ExprKind) << E->getSourceRange();
4100     return true;
4101   }
4102 
4103   // The operand for sizeof and alignof is in an unevaluated expression context,
4104   // so side effects could result in unintended consequences.
4105   if (IsUnevaluatedOperand && !inTemplateInstantiation() &&
4106       E->HasSideEffects(Context, false))
4107     Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
4108 
4109   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
4110                                        E->getSourceRange(), ExprKind))
4111     return true;
4112 
4113   if (ExprKind == UETT_SizeOf) {
4114     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
4115       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
4116         QualType OType = PVD->getOriginalType();
4117         QualType Type = PVD->getType();
4118         if (Type->isPointerType() && OType->isArrayType()) {
4119           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
4120             << Type << OType;
4121           Diag(PVD->getLocation(), diag::note_declared_at);
4122         }
4123       }
4124     }
4125 
4126     // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
4127     // decays into a pointer and returns an unintended result. This is most
4128     // likely a typo for "sizeof(array) op x".
4129     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
4130       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4131                                BO->getLHS());
4132       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4133                                BO->getRHS());
4134     }
4135   }
4136 
4137   return false;
4138 }
4139 
4140 /// Check the constraints on operands to unary expression and type
4141 /// traits.
4142 ///
4143 /// This will complete any types necessary, and validate the various constraints
4144 /// on those operands.
4145 ///
4146 /// The UsualUnaryConversions() function is *not* called by this routine.
4147 /// C99 6.3.2.1p[2-4] all state:
4148 ///   Except when it is the operand of the sizeof operator ...
4149 ///
4150 /// C++ [expr.sizeof]p4
4151 ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
4152 ///   standard conversions are not applied to the operand of sizeof.
4153 ///
4154 /// This policy is followed for all of the unary trait expressions.
4155 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
4156                                             SourceLocation OpLoc,
4157                                             SourceRange ExprRange,
4158                                             UnaryExprOrTypeTrait ExprKind) {
4159   if (ExprType->isDependentType())
4160     return false;
4161 
4162   // C++ [expr.sizeof]p2:
4163   //     When applied to a reference or a reference type, the result
4164   //     is the size of the referenced type.
4165   // C++11 [expr.alignof]p3:
4166   //     When alignof is applied to a reference type, the result
4167   //     shall be the alignment of the referenced type.
4168   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
4169     ExprType = Ref->getPointeeType();
4170 
4171   // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
4172   //   When alignof or _Alignof is applied to an array type, the result
4173   //   is the alignment of the element type.
4174   if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4175       ExprKind == UETT_OpenMPRequiredSimdAlign)
4176     ExprType = Context.getBaseElementType(ExprType);
4177 
4178   if (ExprKind == UETT_VecStep)
4179     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
4180 
4181   // Explicitly list some types as extensions.
4182   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
4183                                       ExprKind))
4184     return false;
4185 
4186   if (RequireCompleteSizedType(
4187           OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4188           getTraitSpelling(ExprKind), ExprRange))
4189     return true;
4190 
4191   if (ExprType->isFunctionType()) {
4192     Diag(OpLoc, diag::err_sizeof_alignof_function_type)
4193         << getTraitSpelling(ExprKind) << ExprRange;
4194     return true;
4195   }
4196 
4197   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
4198                                        ExprKind))
4199     return true;
4200 
4201   return false;
4202 }
4203 
4204 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
4205   // Cannot know anything else if the expression is dependent.
4206   if (E->isTypeDependent())
4207     return false;
4208 
4209   if (E->getObjectKind() == OK_BitField) {
4210     S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
4211        << 1 << E->getSourceRange();
4212     return true;
4213   }
4214 
4215   ValueDecl *D = nullptr;
4216   Expr *Inner = E->IgnoreParens();
4217   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) {
4218     D = DRE->getDecl();
4219   } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) {
4220     D = ME->getMemberDecl();
4221   }
4222 
4223   // If it's a field, require the containing struct to have a
4224   // complete definition so that we can compute the layout.
4225   //
4226   // This can happen in C++11 onwards, either by naming the member
4227   // in a way that is not transformed into a member access expression
4228   // (in an unevaluated operand, for instance), or by naming the member
4229   // in a trailing-return-type.
4230   //
4231   // For the record, since __alignof__ on expressions is a GCC
4232   // extension, GCC seems to permit this but always gives the
4233   // nonsensical answer 0.
4234   //
4235   // We don't really need the layout here --- we could instead just
4236   // directly check for all the appropriate alignment-lowing
4237   // attributes --- but that would require duplicating a lot of
4238   // logic that just isn't worth duplicating for such a marginal
4239   // use-case.
4240   if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
4241     // Fast path this check, since we at least know the record has a
4242     // definition if we can find a member of it.
4243     if (!FD->getParent()->isCompleteDefinition()) {
4244       S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
4245         << E->getSourceRange();
4246       return true;
4247     }
4248 
4249     // Otherwise, if it's a field, and the field doesn't have
4250     // reference type, then it must have a complete type (or be a
4251     // flexible array member, which we explicitly want to
4252     // white-list anyway), which makes the following checks trivial.
4253     if (!FD->getType()->isReferenceType())
4254       return false;
4255   }
4256 
4257   return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4258 }
4259 
4260 bool Sema::CheckVecStepExpr(Expr *E) {
4261   E = E->IgnoreParens();
4262 
4263   // Cannot know anything else if the expression is dependent.
4264   if (E->isTypeDependent())
4265     return false;
4266 
4267   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
4268 }
4269 
4270 static void captureVariablyModifiedType(ASTContext &Context, QualType T,
4271                                         CapturingScopeInfo *CSI) {
4272   assert(T->isVariablyModifiedType());
4273   assert(CSI != nullptr);
4274 
4275   // We're going to walk down into the type and look for VLA expressions.
4276   do {
4277     const Type *Ty = T.getTypePtr();
4278     switch (Ty->getTypeClass()) {
4279 #define TYPE(Class, Base)
4280 #define ABSTRACT_TYPE(Class, Base)
4281 #define NON_CANONICAL_TYPE(Class, Base)
4282 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
4283 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4284 #include "clang/AST/TypeNodes.inc"
4285       T = QualType();
4286       break;
4287     // These types are never variably-modified.
4288     case Type::Builtin:
4289     case Type::Complex:
4290     case Type::Vector:
4291     case Type::ExtVector:
4292     case Type::ConstantMatrix:
4293     case Type::Record:
4294     case Type::Enum:
4295     case Type::Elaborated:
4296     case Type::TemplateSpecialization:
4297     case Type::ObjCObject:
4298     case Type::ObjCInterface:
4299     case Type::ObjCObjectPointer:
4300     case Type::ObjCTypeParam:
4301     case Type::Pipe:
4302     case Type::ExtInt:
4303       llvm_unreachable("type class is never variably-modified!");
4304     case Type::Adjusted:
4305       T = cast<AdjustedType>(Ty)->getOriginalType();
4306       break;
4307     case Type::Decayed:
4308       T = cast<DecayedType>(Ty)->getPointeeType();
4309       break;
4310     case Type::Pointer:
4311       T = cast<PointerType>(Ty)->getPointeeType();
4312       break;
4313     case Type::BlockPointer:
4314       T = cast<BlockPointerType>(Ty)->getPointeeType();
4315       break;
4316     case Type::LValueReference:
4317     case Type::RValueReference:
4318       T = cast<ReferenceType>(Ty)->getPointeeType();
4319       break;
4320     case Type::MemberPointer:
4321       T = cast<MemberPointerType>(Ty)->getPointeeType();
4322       break;
4323     case Type::ConstantArray:
4324     case Type::IncompleteArray:
4325       // Losing element qualification here is fine.
4326       T = cast<ArrayType>(Ty)->getElementType();
4327       break;
4328     case Type::VariableArray: {
4329       // Losing element qualification here is fine.
4330       const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
4331 
4332       // Unknown size indication requires no size computation.
4333       // Otherwise, evaluate and record it.
4334       auto Size = VAT->getSizeExpr();
4335       if (Size && !CSI->isVLATypeCaptured(VAT) &&
4336           (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI)))
4337         CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType());
4338 
4339       T = VAT->getElementType();
4340       break;
4341     }
4342     case Type::FunctionProto:
4343     case Type::FunctionNoProto:
4344       T = cast<FunctionType>(Ty)->getReturnType();
4345       break;
4346     case Type::Paren:
4347     case Type::TypeOf:
4348     case Type::UnaryTransform:
4349     case Type::Attributed:
4350     case Type::SubstTemplateTypeParm:
4351     case Type::MacroQualified:
4352       // Keep walking after single level desugaring.
4353       T = T.getSingleStepDesugaredType(Context);
4354       break;
4355     case Type::Typedef:
4356       T = cast<TypedefType>(Ty)->desugar();
4357       break;
4358     case Type::Decltype:
4359       T = cast<DecltypeType>(Ty)->desugar();
4360       break;
4361     case Type::Auto:
4362     case Type::DeducedTemplateSpecialization:
4363       T = cast<DeducedType>(Ty)->getDeducedType();
4364       break;
4365     case Type::TypeOfExpr:
4366       T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
4367       break;
4368     case Type::Atomic:
4369       T = cast<AtomicType>(Ty)->getValueType();
4370       break;
4371     }
4372   } while (!T.isNull() && T->isVariablyModifiedType());
4373 }
4374 
4375 /// Build a sizeof or alignof expression given a type operand.
4376 ExprResult
4377 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4378                                      SourceLocation OpLoc,
4379                                      UnaryExprOrTypeTrait ExprKind,
4380                                      SourceRange R) {
4381   if (!TInfo)
4382     return ExprError();
4383 
4384   QualType T = TInfo->getType();
4385 
4386   if (!T->isDependentType() &&
4387       CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
4388     return ExprError();
4389 
4390   if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4391     if (auto *TT = T->getAs<TypedefType>()) {
4392       for (auto I = FunctionScopes.rbegin(),
4393                 E = std::prev(FunctionScopes.rend());
4394            I != E; ++I) {
4395         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4396         if (CSI == nullptr)
4397           break;
4398         DeclContext *DC = nullptr;
4399         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4400           DC = LSI->CallOperator;
4401         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4402           DC = CRSI->TheCapturedDecl;
4403         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4404           DC = BSI->TheDecl;
4405         if (DC) {
4406           if (DC->containsDecl(TT->getDecl()))
4407             break;
4408           captureVariablyModifiedType(Context, T, CSI);
4409         }
4410       }
4411     }
4412   }
4413 
4414   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4415   return new (Context) UnaryExprOrTypeTraitExpr(
4416       ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4417 }
4418 
4419 /// Build a sizeof or alignof expression given an expression
4420 /// operand.
4421 ExprResult
4422 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4423                                      UnaryExprOrTypeTrait ExprKind) {
4424   ExprResult PE = CheckPlaceholderExpr(E);
4425   if (PE.isInvalid())
4426     return ExprError();
4427 
4428   E = PE.get();
4429 
4430   // Verify that the operand is valid.
4431   bool isInvalid = false;
4432   if (E->isTypeDependent()) {
4433     // Delay type-checking for type-dependent expressions.
4434   } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4435     isInvalid = CheckAlignOfExpr(*this, E, ExprKind);
4436   } else if (ExprKind == UETT_VecStep) {
4437     isInvalid = CheckVecStepExpr(E);
4438   } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4439       Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4440       isInvalid = true;
4441   } else if (E->refersToBitField()) {  // C99 6.5.3.4p1.
4442     Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4443     isInvalid = true;
4444   } else {
4445     isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
4446   }
4447 
4448   if (isInvalid)
4449     return ExprError();
4450 
4451   if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4452     PE = TransformToPotentiallyEvaluated(E);
4453     if (PE.isInvalid()) return ExprError();
4454     E = PE.get();
4455   }
4456 
4457   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4458   return new (Context) UnaryExprOrTypeTraitExpr(
4459       ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4460 }
4461 
4462 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4463 /// expr and the same for @c alignof and @c __alignof
4464 /// Note that the ArgRange is invalid if isType is false.
4465 ExprResult
4466 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4467                                     UnaryExprOrTypeTrait ExprKind, bool IsType,
4468                                     void *TyOrEx, SourceRange ArgRange) {
4469   // If error parsing type, ignore.
4470   if (!TyOrEx) return ExprError();
4471 
4472   if (IsType) {
4473     TypeSourceInfo *TInfo;
4474     (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4475     return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4476   }
4477 
4478   Expr *ArgEx = (Expr *)TyOrEx;
4479   ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4480   return Result;
4481 }
4482 
4483 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4484                                      bool IsReal) {
4485   if (V.get()->isTypeDependent())
4486     return S.Context.DependentTy;
4487 
4488   // _Real and _Imag are only l-values for normal l-values.
4489   if (V.get()->getObjectKind() != OK_Ordinary) {
4490     V = S.DefaultLvalueConversion(V.get());
4491     if (V.isInvalid())
4492       return QualType();
4493   }
4494 
4495   // These operators return the element type of a complex type.
4496   if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4497     return CT->getElementType();
4498 
4499   // Otherwise they pass through real integer and floating point types here.
4500   if (V.get()->getType()->isArithmeticType())
4501     return V.get()->getType();
4502 
4503   // Test for placeholders.
4504   ExprResult PR = S.CheckPlaceholderExpr(V.get());
4505   if (PR.isInvalid()) return QualType();
4506   if (PR.get() != V.get()) {
4507     V = PR;
4508     return CheckRealImagOperand(S, V, Loc, IsReal);
4509   }
4510 
4511   // Reject anything else.
4512   S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4513     << (IsReal ? "__real" : "__imag");
4514   return QualType();
4515 }
4516 
4517 
4518 
4519 ExprResult
4520 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4521                           tok::TokenKind Kind, Expr *Input) {
4522   UnaryOperatorKind Opc;
4523   switch (Kind) {
4524   default: llvm_unreachable("Unknown unary op!");
4525   case tok::plusplus:   Opc = UO_PostInc; break;
4526   case tok::minusminus: Opc = UO_PostDec; break;
4527   }
4528 
4529   // Since this might is a postfix expression, get rid of ParenListExprs.
4530   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4531   if (Result.isInvalid()) return ExprError();
4532   Input = Result.get();
4533 
4534   return BuildUnaryOp(S, OpLoc, Opc, Input);
4535 }
4536 
4537 /// Diagnose if arithmetic on the given ObjC pointer is illegal.
4538 ///
4539 /// \return true on error
4540 static bool checkArithmeticOnObjCPointer(Sema &S,
4541                                          SourceLocation opLoc,
4542                                          Expr *op) {
4543   assert(op->getType()->isObjCObjectPointerType());
4544   if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4545       !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4546     return false;
4547 
4548   S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4549     << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4550     << op->getSourceRange();
4551   return true;
4552 }
4553 
4554 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4555   auto *BaseNoParens = Base->IgnoreParens();
4556   if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4557     return MSProp->getPropertyDecl()->getType()->isArrayType();
4558   return isa<MSPropertySubscriptExpr>(BaseNoParens);
4559 }
4560 
4561 ExprResult
4562 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
4563                               Expr *idx, SourceLocation rbLoc) {
4564   if (base && !base->getType().isNull() &&
4565       base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection))
4566     return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
4567                                     SourceLocation(), /*Length*/ nullptr,
4568                                     /*Stride=*/nullptr, rbLoc);
4569 
4570   // Since this might be a postfix expression, get rid of ParenListExprs.
4571   if (isa<ParenListExpr>(base)) {
4572     ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4573     if (result.isInvalid()) return ExprError();
4574     base = result.get();
4575   }
4576 
4577   // Check if base and idx form a MatrixSubscriptExpr.
4578   //
4579   // Helper to check for comma expressions, which are not allowed as indices for
4580   // matrix subscript expressions.
4581   auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) {
4582     if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) {
4583       Diag(E->getExprLoc(), diag::err_matrix_subscript_comma)
4584           << SourceRange(base->getBeginLoc(), rbLoc);
4585       return true;
4586     }
4587     return false;
4588   };
4589   // The matrix subscript operator ([][])is considered a single operator.
4590   // Separating the index expressions by parenthesis is not allowed.
4591   if (base->getType()->isSpecificPlaceholderType(
4592           BuiltinType::IncompleteMatrixIdx) &&
4593       !isa<MatrixSubscriptExpr>(base)) {
4594     Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index)
4595         << SourceRange(base->getBeginLoc(), rbLoc);
4596     return ExprError();
4597   }
4598   // If the base is a MatrixSubscriptExpr, try to create a new
4599   // MatrixSubscriptExpr.
4600   auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base);
4601   if (matSubscriptE) {
4602     if (CheckAndReportCommaError(idx))
4603       return ExprError();
4604 
4605     assert(matSubscriptE->isIncomplete() &&
4606            "base has to be an incomplete matrix subscript");
4607     return CreateBuiltinMatrixSubscriptExpr(
4608         matSubscriptE->getBase(), matSubscriptE->getRowIdx(), idx, rbLoc);
4609   }
4610 
4611   // Handle any non-overload placeholder types in the base and index
4612   // expressions.  We can't handle overloads here because the other
4613   // operand might be an overloadable type, in which case the overload
4614   // resolution for the operator overload should get the first crack
4615   // at the overload.
4616   bool IsMSPropertySubscript = false;
4617   if (base->getType()->isNonOverloadPlaceholderType()) {
4618     IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4619     if (!IsMSPropertySubscript) {
4620       ExprResult result = CheckPlaceholderExpr(base);
4621       if (result.isInvalid())
4622         return ExprError();
4623       base = result.get();
4624     }
4625   }
4626 
4627   // If the base is a matrix type, try to create a new MatrixSubscriptExpr.
4628   if (base->getType()->isMatrixType()) {
4629     if (CheckAndReportCommaError(idx))
4630       return ExprError();
4631 
4632     return CreateBuiltinMatrixSubscriptExpr(base, idx, nullptr, rbLoc);
4633   }
4634 
4635   // A comma-expression as the index is deprecated in C++2a onwards.
4636   if (getLangOpts().CPlusPlus20 &&
4637       ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) ||
4638        (isa<CXXOperatorCallExpr>(idx) &&
4639         cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma))) {
4640     Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript)
4641         << SourceRange(base->getBeginLoc(), rbLoc);
4642   }
4643 
4644   if (idx->getType()->isNonOverloadPlaceholderType()) {
4645     ExprResult result = CheckPlaceholderExpr(idx);
4646     if (result.isInvalid()) return ExprError();
4647     idx = result.get();
4648   }
4649 
4650   // Build an unanalyzed expression if either operand is type-dependent.
4651   if (getLangOpts().CPlusPlus &&
4652       (base->isTypeDependent() || idx->isTypeDependent())) {
4653     return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
4654                                             VK_LValue, OK_Ordinary, rbLoc);
4655   }
4656 
4657   // MSDN, property (C++)
4658   // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4659   // This attribute can also be used in the declaration of an empty array in a
4660   // class or structure definition. For example:
4661   // __declspec(property(get=GetX, put=PutX)) int x[];
4662   // The above statement indicates that x[] can be used with one or more array
4663   // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4664   // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4665   if (IsMSPropertySubscript) {
4666     // Build MS property subscript expression if base is MS property reference
4667     // or MS property subscript.
4668     return new (Context) MSPropertySubscriptExpr(
4669         base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
4670   }
4671 
4672   // Use C++ overloaded-operator rules if either operand has record
4673   // type.  The spec says to do this if either type is *overloadable*,
4674   // but enum types can't declare subscript operators or conversion
4675   // operators, so there's nothing interesting for overload resolution
4676   // to do if there aren't any record types involved.
4677   //
4678   // ObjC pointers have their own subscripting logic that is not tied
4679   // to overload resolution and so should not take this path.
4680   if (getLangOpts().CPlusPlus &&
4681       (base->getType()->isRecordType() ||
4682        (!base->getType()->isObjCObjectPointerType() &&
4683         idx->getType()->isRecordType()))) {
4684     return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
4685   }
4686 
4687   ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
4688 
4689   if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get()))
4690     CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get()));
4691 
4692   return Res;
4693 }
4694 
4695 ExprResult Sema::tryConvertExprToType(Expr *E, QualType Ty) {
4696   InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty);
4697   InitializationKind Kind =
4698       InitializationKind::CreateCopy(E->getBeginLoc(), SourceLocation());
4699   InitializationSequence InitSeq(*this, Entity, Kind, E);
4700   return InitSeq.Perform(*this, Entity, Kind, E);
4701 }
4702 
4703 ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx,
4704                                                   Expr *ColumnIdx,
4705                                                   SourceLocation RBLoc) {
4706   ExprResult BaseR = CheckPlaceholderExpr(Base);
4707   if (BaseR.isInvalid())
4708     return BaseR;
4709   Base = BaseR.get();
4710 
4711   ExprResult RowR = CheckPlaceholderExpr(RowIdx);
4712   if (RowR.isInvalid())
4713     return RowR;
4714   RowIdx = RowR.get();
4715 
4716   if (!ColumnIdx)
4717     return new (Context) MatrixSubscriptExpr(
4718         Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc);
4719 
4720   // Build an unanalyzed expression if any of the operands is type-dependent.
4721   if (Base->isTypeDependent() || RowIdx->isTypeDependent() ||
4722       ColumnIdx->isTypeDependent())
4723     return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
4724                                              Context.DependentTy, RBLoc);
4725 
4726   ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx);
4727   if (ColumnR.isInvalid())
4728     return ColumnR;
4729   ColumnIdx = ColumnR.get();
4730 
4731   // Check that IndexExpr is an integer expression. If it is a constant
4732   // expression, check that it is less than Dim (= the number of elements in the
4733   // corresponding dimension).
4734   auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim,
4735                           bool IsColumnIdx) -> Expr * {
4736     if (!IndexExpr->getType()->isIntegerType() &&
4737         !IndexExpr->isTypeDependent()) {
4738       Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer)
4739           << IsColumnIdx;
4740       return nullptr;
4741     }
4742 
4743     if (Optional<llvm::APSInt> Idx =
4744             IndexExpr->getIntegerConstantExpr(Context)) {
4745       if ((*Idx < 0 || *Idx >= Dim)) {
4746         Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range)
4747             << IsColumnIdx << Dim;
4748         return nullptr;
4749       }
4750     }
4751 
4752     ExprResult ConvExpr =
4753         tryConvertExprToType(IndexExpr, Context.getSizeType());
4754     assert(!ConvExpr.isInvalid() &&
4755            "should be able to convert any integer type to size type");
4756     return ConvExpr.get();
4757   };
4758 
4759   auto *MTy = Base->getType()->getAs<ConstantMatrixType>();
4760   RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false);
4761   ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true);
4762   if (!RowIdx || !ColumnIdx)
4763     return ExprError();
4764 
4765   return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
4766                                            MTy->getElementType(), RBLoc);
4767 }
4768 
4769 void Sema::CheckAddressOfNoDeref(const Expr *E) {
4770   ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4771   const Expr *StrippedExpr = E->IgnoreParenImpCasts();
4772 
4773   // For expressions like `&(*s).b`, the base is recorded and what should be
4774   // checked.
4775   const MemberExpr *Member = nullptr;
4776   while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow())
4777     StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
4778 
4779   LastRecord.PossibleDerefs.erase(StrippedExpr);
4780 }
4781 
4782 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
4783   QualType ResultTy = E->getType();
4784   ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4785 
4786   // Bail if the element is an array since it is not memory access.
4787   if (isa<ArrayType>(ResultTy))
4788     return;
4789 
4790   if (ResultTy->hasAttr(attr::NoDeref)) {
4791     LastRecord.PossibleDerefs.insert(E);
4792     return;
4793   }
4794 
4795   // Check if the base type is a pointer to a member access of a struct
4796   // marked with noderef.
4797   const Expr *Base = E->getBase();
4798   QualType BaseTy = Base->getType();
4799   if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy)))
4800     // Not a pointer access
4801     return;
4802 
4803   const MemberExpr *Member = nullptr;
4804   while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) &&
4805          Member->isArrow())
4806     Base = Member->getBase();
4807 
4808   if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) {
4809     if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))
4810       LastRecord.PossibleDerefs.insert(E);
4811   }
4812 }
4813 
4814 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4815                                           Expr *LowerBound,
4816                                           SourceLocation ColonLocFirst,
4817                                           SourceLocation ColonLocSecond,
4818                                           Expr *Length, Expr *Stride,
4819                                           SourceLocation RBLoc) {
4820   if (Base->getType()->isPlaceholderType() &&
4821       !Base->getType()->isSpecificPlaceholderType(
4822           BuiltinType::OMPArraySection)) {
4823     ExprResult Result = CheckPlaceholderExpr(Base);
4824     if (Result.isInvalid())
4825       return ExprError();
4826     Base = Result.get();
4827   }
4828   if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
4829     ExprResult Result = CheckPlaceholderExpr(LowerBound);
4830     if (Result.isInvalid())
4831       return ExprError();
4832     Result = DefaultLvalueConversion(Result.get());
4833     if (Result.isInvalid())
4834       return ExprError();
4835     LowerBound = Result.get();
4836   }
4837   if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
4838     ExprResult Result = CheckPlaceholderExpr(Length);
4839     if (Result.isInvalid())
4840       return ExprError();
4841     Result = DefaultLvalueConversion(Result.get());
4842     if (Result.isInvalid())
4843       return ExprError();
4844     Length = Result.get();
4845   }
4846   if (Stride && Stride->getType()->isNonOverloadPlaceholderType()) {
4847     ExprResult Result = CheckPlaceholderExpr(Stride);
4848     if (Result.isInvalid())
4849       return ExprError();
4850     Result = DefaultLvalueConversion(Result.get());
4851     if (Result.isInvalid())
4852       return ExprError();
4853     Stride = Result.get();
4854   }
4855 
4856   // Build an unanalyzed expression if either operand is type-dependent.
4857   if (Base->isTypeDependent() ||
4858       (LowerBound &&
4859        (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
4860       (Length && (Length->isTypeDependent() || Length->isValueDependent())) ||
4861       (Stride && (Stride->isTypeDependent() || Stride->isValueDependent()))) {
4862     return new (Context) OMPArraySectionExpr(
4863         Base, LowerBound, Length, Stride, Context.DependentTy, VK_LValue,
4864         OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc);
4865   }
4866 
4867   // Perform default conversions.
4868   QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
4869   QualType ResultTy;
4870   if (OriginalTy->isAnyPointerType()) {
4871     ResultTy = OriginalTy->getPointeeType();
4872   } else if (OriginalTy->isArrayType()) {
4873     ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
4874   } else {
4875     return ExprError(
4876         Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
4877         << Base->getSourceRange());
4878   }
4879   // C99 6.5.2.1p1
4880   if (LowerBound) {
4881     auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
4882                                                       LowerBound);
4883     if (Res.isInvalid())
4884       return ExprError(Diag(LowerBound->getExprLoc(),
4885                             diag::err_omp_typecheck_section_not_integer)
4886                        << 0 << LowerBound->getSourceRange());
4887     LowerBound = Res.get();
4888 
4889     if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4890         LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4891       Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
4892           << 0 << LowerBound->getSourceRange();
4893   }
4894   if (Length) {
4895     auto Res =
4896         PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
4897     if (Res.isInvalid())
4898       return ExprError(Diag(Length->getExprLoc(),
4899                             diag::err_omp_typecheck_section_not_integer)
4900                        << 1 << Length->getSourceRange());
4901     Length = Res.get();
4902 
4903     if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4904         Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4905       Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
4906           << 1 << Length->getSourceRange();
4907   }
4908   if (Stride) {
4909     ExprResult Res =
4910         PerformOpenMPImplicitIntegerConversion(Stride->getExprLoc(), Stride);
4911     if (Res.isInvalid())
4912       return ExprError(Diag(Stride->getExprLoc(),
4913                             diag::err_omp_typecheck_section_not_integer)
4914                        << 1 << Stride->getSourceRange());
4915     Stride = Res.get();
4916 
4917     if (Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4918         Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4919       Diag(Stride->getExprLoc(), diag::warn_omp_section_is_char)
4920           << 1 << Stride->getSourceRange();
4921   }
4922 
4923   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4924   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4925   // type. Note that functions are not objects, and that (in C99 parlance)
4926   // incomplete types are not object types.
4927   if (ResultTy->isFunctionType()) {
4928     Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
4929         << ResultTy << Base->getSourceRange();
4930     return ExprError();
4931   }
4932 
4933   if (RequireCompleteType(Base->getExprLoc(), ResultTy,
4934                           diag::err_omp_section_incomplete_type, Base))
4935     return ExprError();
4936 
4937   if (LowerBound && !OriginalTy->isAnyPointerType()) {
4938     Expr::EvalResult Result;
4939     if (LowerBound->EvaluateAsInt(Result, Context)) {
4940       // OpenMP 5.0, [2.1.5 Array Sections]
4941       // The array section must be a subset of the original array.
4942       llvm::APSInt LowerBoundValue = Result.Val.getInt();
4943       if (LowerBoundValue.isNegative()) {
4944         Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
4945             << LowerBound->getSourceRange();
4946         return ExprError();
4947       }
4948     }
4949   }
4950 
4951   if (Length) {
4952     Expr::EvalResult Result;
4953     if (Length->EvaluateAsInt(Result, Context)) {
4954       // OpenMP 5.0, [2.1.5 Array Sections]
4955       // The length must evaluate to non-negative integers.
4956       llvm::APSInt LengthValue = Result.Val.getInt();
4957       if (LengthValue.isNegative()) {
4958         Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
4959             << LengthValue.toString(/*Radix=*/10, /*Signed=*/true)
4960             << Length->getSourceRange();
4961         return ExprError();
4962       }
4963     }
4964   } else if (ColonLocFirst.isValid() &&
4965              (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
4966                                       !OriginalTy->isVariableArrayType()))) {
4967     // OpenMP 5.0, [2.1.5 Array Sections]
4968     // When the size of the array dimension is not known, the length must be
4969     // specified explicitly.
4970     Diag(ColonLocFirst, diag::err_omp_section_length_undefined)
4971         << (!OriginalTy.isNull() && OriginalTy->isArrayType());
4972     return ExprError();
4973   }
4974 
4975   if (Stride) {
4976     Expr::EvalResult Result;
4977     if (Stride->EvaluateAsInt(Result, Context)) {
4978       // OpenMP 5.0, [2.1.5 Array Sections]
4979       // The stride must evaluate to a positive integer.
4980       llvm::APSInt StrideValue = Result.Val.getInt();
4981       if (!StrideValue.isStrictlyPositive()) {
4982         Diag(Stride->getExprLoc(), diag::err_omp_section_stride_non_positive)
4983             << StrideValue.toString(/*Radix=*/10, /*Signed=*/true)
4984             << Stride->getSourceRange();
4985         return ExprError();
4986       }
4987     }
4988   }
4989 
4990   if (!Base->getType()->isSpecificPlaceholderType(
4991           BuiltinType::OMPArraySection)) {
4992     ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
4993     if (Result.isInvalid())
4994       return ExprError();
4995     Base = Result.get();
4996   }
4997   return new (Context) OMPArraySectionExpr(
4998       Base, LowerBound, Length, Stride, Context.OMPArraySectionTy, VK_LValue,
4999       OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc);
5000 }
5001 
5002 ExprResult Sema::ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc,
5003                                           SourceLocation RParenLoc,
5004                                           ArrayRef<Expr *> Dims,
5005                                           ArrayRef<SourceRange> Brackets) {
5006   if (Base->getType()->isPlaceholderType()) {
5007     ExprResult Result = CheckPlaceholderExpr(Base);
5008     if (Result.isInvalid())
5009       return ExprError();
5010     Result = DefaultLvalueConversion(Result.get());
5011     if (Result.isInvalid())
5012       return ExprError();
5013     Base = Result.get();
5014   }
5015   QualType BaseTy = Base->getType();
5016   // Delay analysis of the types/expressions if instantiation/specialization is
5017   // required.
5018   if (!BaseTy->isPointerType() && Base->isTypeDependent())
5019     return OMPArrayShapingExpr::Create(Context, Context.DependentTy, Base,
5020                                        LParenLoc, RParenLoc, Dims, Brackets);
5021   if (!BaseTy->isPointerType() ||
5022       (!Base->isTypeDependent() &&
5023        BaseTy->getPointeeType()->isIncompleteType()))
5024     return ExprError(Diag(Base->getExprLoc(),
5025                           diag::err_omp_non_pointer_type_array_shaping_base)
5026                      << Base->getSourceRange());
5027 
5028   SmallVector<Expr *, 4> NewDims;
5029   bool ErrorFound = false;
5030   for (Expr *Dim : Dims) {
5031     if (Dim->getType()->isPlaceholderType()) {
5032       ExprResult Result = CheckPlaceholderExpr(Dim);
5033       if (Result.isInvalid()) {
5034         ErrorFound = true;
5035         continue;
5036       }
5037       Result = DefaultLvalueConversion(Result.get());
5038       if (Result.isInvalid()) {
5039         ErrorFound = true;
5040         continue;
5041       }
5042       Dim = Result.get();
5043     }
5044     if (!Dim->isTypeDependent()) {
5045       ExprResult Result =
5046           PerformOpenMPImplicitIntegerConversion(Dim->getExprLoc(), Dim);
5047       if (Result.isInvalid()) {
5048         ErrorFound = true;
5049         Diag(Dim->getExprLoc(), diag::err_omp_typecheck_shaping_not_integer)
5050             << Dim->getSourceRange();
5051         continue;
5052       }
5053       Dim = Result.get();
5054       Expr::EvalResult EvResult;
5055       if (!Dim->isValueDependent() && Dim->EvaluateAsInt(EvResult, Context)) {
5056         // OpenMP 5.0, [2.1.4 Array Shaping]
5057         // Each si is an integral type expression that must evaluate to a
5058         // positive integer.
5059         llvm::APSInt Value = EvResult.Val.getInt();
5060         if (!Value.isStrictlyPositive()) {
5061           Diag(Dim->getExprLoc(), diag::err_omp_shaping_dimension_not_positive)
5062               << Value.toString(/*Radix=*/10, /*Signed=*/true)
5063               << Dim->getSourceRange();
5064           ErrorFound = true;
5065           continue;
5066         }
5067       }
5068     }
5069     NewDims.push_back(Dim);
5070   }
5071   if (ErrorFound)
5072     return ExprError();
5073   return OMPArrayShapingExpr::Create(Context, Context.OMPArrayShapingTy, Base,
5074                                      LParenLoc, RParenLoc, NewDims, Brackets);
5075 }
5076 
5077 ExprResult Sema::ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc,
5078                                       SourceLocation LLoc, SourceLocation RLoc,
5079                                       ArrayRef<OMPIteratorData> Data) {
5080   SmallVector<OMPIteratorExpr::IteratorDefinition, 4> ID;
5081   bool IsCorrect = true;
5082   for (const OMPIteratorData &D : Data) {
5083     TypeSourceInfo *TInfo = nullptr;
5084     SourceLocation StartLoc;
5085     QualType DeclTy;
5086     if (!D.Type.getAsOpaquePtr()) {
5087       // OpenMP 5.0, 2.1.6 Iterators
5088       // In an iterator-specifier, if the iterator-type is not specified then
5089       // the type of that iterator is of int type.
5090       DeclTy = Context.IntTy;
5091       StartLoc = D.DeclIdentLoc;
5092     } else {
5093       DeclTy = GetTypeFromParser(D.Type, &TInfo);
5094       StartLoc = TInfo->getTypeLoc().getBeginLoc();
5095     }
5096 
5097     bool IsDeclTyDependent = DeclTy->isDependentType() ||
5098                              DeclTy->containsUnexpandedParameterPack() ||
5099                              DeclTy->isInstantiationDependentType();
5100     if (!IsDeclTyDependent) {
5101       if (!DeclTy->isIntegralType(Context) && !DeclTy->isAnyPointerType()) {
5102         // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++
5103         // The iterator-type must be an integral or pointer type.
5104         Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer)
5105             << DeclTy;
5106         IsCorrect = false;
5107         continue;
5108       }
5109       if (DeclTy.isConstant(Context)) {
5110         // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++
5111         // The iterator-type must not be const qualified.
5112         Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer)
5113             << DeclTy;
5114         IsCorrect = false;
5115         continue;
5116       }
5117     }
5118 
5119     // Iterator declaration.
5120     assert(D.DeclIdent && "Identifier expected.");
5121     // Always try to create iterator declarator to avoid extra error messages
5122     // about unknown declarations use.
5123     auto *VD = VarDecl::Create(Context, CurContext, StartLoc, D.DeclIdentLoc,
5124                                D.DeclIdent, DeclTy, TInfo, SC_None);
5125     VD->setImplicit();
5126     if (S) {
5127       // Check for conflicting previous declaration.
5128       DeclarationNameInfo NameInfo(VD->getDeclName(), D.DeclIdentLoc);
5129       LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5130                             ForVisibleRedeclaration);
5131       Previous.suppressDiagnostics();
5132       LookupName(Previous, S);
5133 
5134       FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false,
5135                            /*AllowInlineNamespace=*/false);
5136       if (!Previous.empty()) {
5137         NamedDecl *Old = Previous.getRepresentativeDecl();
5138         Diag(D.DeclIdentLoc, diag::err_redefinition) << VD->getDeclName();
5139         Diag(Old->getLocation(), diag::note_previous_definition);
5140       } else {
5141         PushOnScopeChains(VD, S);
5142       }
5143     } else {
5144       CurContext->addDecl(VD);
5145     }
5146     Expr *Begin = D.Range.Begin;
5147     if (!IsDeclTyDependent && Begin && !Begin->isTypeDependent()) {
5148       ExprResult BeginRes =
5149           PerformImplicitConversion(Begin, DeclTy, AA_Converting);
5150       Begin = BeginRes.get();
5151     }
5152     Expr *End = D.Range.End;
5153     if (!IsDeclTyDependent && End && !End->isTypeDependent()) {
5154       ExprResult EndRes = PerformImplicitConversion(End, DeclTy, AA_Converting);
5155       End = EndRes.get();
5156     }
5157     Expr *Step = D.Range.Step;
5158     if (!IsDeclTyDependent && Step && !Step->isTypeDependent()) {
5159       if (!Step->getType()->isIntegralType(Context)) {
5160         Diag(Step->getExprLoc(), diag::err_omp_iterator_step_not_integral)
5161             << Step << Step->getSourceRange();
5162         IsCorrect = false;
5163         continue;
5164       }
5165       Optional<llvm::APSInt> Result = Step->getIntegerConstantExpr(Context);
5166       // OpenMP 5.0, 2.1.6 Iterators, Restrictions
5167       // If the step expression of a range-specification equals zero, the
5168       // behavior is unspecified.
5169       if (Result && Result->isNullValue()) {
5170         Diag(Step->getExprLoc(), diag::err_omp_iterator_step_constant_zero)
5171             << Step << Step->getSourceRange();
5172         IsCorrect = false;
5173         continue;
5174       }
5175     }
5176     if (!Begin || !End || !IsCorrect) {
5177       IsCorrect = false;
5178       continue;
5179     }
5180     OMPIteratorExpr::IteratorDefinition &IDElem = ID.emplace_back();
5181     IDElem.IteratorDecl = VD;
5182     IDElem.AssignmentLoc = D.AssignLoc;
5183     IDElem.Range.Begin = Begin;
5184     IDElem.Range.End = End;
5185     IDElem.Range.Step = Step;
5186     IDElem.ColonLoc = D.ColonLoc;
5187     IDElem.SecondColonLoc = D.SecColonLoc;
5188   }
5189   if (!IsCorrect) {
5190     // Invalidate all created iterator declarations if error is found.
5191     for (const OMPIteratorExpr::IteratorDefinition &D : ID) {
5192       if (Decl *ID = D.IteratorDecl)
5193         ID->setInvalidDecl();
5194     }
5195     return ExprError();
5196   }
5197   SmallVector<OMPIteratorHelperData, 4> Helpers;
5198   if (!CurContext->isDependentContext()) {
5199     // Build number of ityeration for each iteration range.
5200     // Ni = ((Stepi > 0) ? ((Endi + Stepi -1 - Begini)/Stepi) :
5201     // ((Begini-Stepi-1-Endi) / -Stepi);
5202     for (OMPIteratorExpr::IteratorDefinition &D : ID) {
5203       // (Endi - Begini)
5204       ExprResult Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, D.Range.End,
5205                                           D.Range.Begin);
5206       if(!Res.isUsable()) {
5207         IsCorrect = false;
5208         continue;
5209       }
5210       ExprResult St, St1;
5211       if (D.Range.Step) {
5212         St = D.Range.Step;
5213         // (Endi - Begini) + Stepi
5214         Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res.get(), St.get());
5215         if (!Res.isUsable()) {
5216           IsCorrect = false;
5217           continue;
5218         }
5219         // (Endi - Begini) + Stepi - 1
5220         Res =
5221             CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res.get(),
5222                                ActOnIntegerConstant(D.AssignmentLoc, 1).get());
5223         if (!Res.isUsable()) {
5224           IsCorrect = false;
5225           continue;
5226         }
5227         // ((Endi - Begini) + Stepi - 1) / Stepi
5228         Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res.get(), St.get());
5229         if (!Res.isUsable()) {
5230           IsCorrect = false;
5231           continue;
5232         }
5233         St1 = CreateBuiltinUnaryOp(D.AssignmentLoc, UO_Minus, D.Range.Step);
5234         // (Begini - Endi)
5235         ExprResult Res1 = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub,
5236                                              D.Range.Begin, D.Range.End);
5237         if (!Res1.isUsable()) {
5238           IsCorrect = false;
5239           continue;
5240         }
5241         // (Begini - Endi) - Stepi
5242         Res1 =
5243             CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res1.get(), St1.get());
5244         if (!Res1.isUsable()) {
5245           IsCorrect = false;
5246           continue;
5247         }
5248         // (Begini - Endi) - Stepi - 1
5249         Res1 =
5250             CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res1.get(),
5251                                ActOnIntegerConstant(D.AssignmentLoc, 1).get());
5252         if (!Res1.isUsable()) {
5253           IsCorrect = false;
5254           continue;
5255         }
5256         // ((Begini - Endi) - Stepi - 1) / (-Stepi)
5257         Res1 =
5258             CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res1.get(), St1.get());
5259         if (!Res1.isUsable()) {
5260           IsCorrect = false;
5261           continue;
5262         }
5263         // Stepi > 0.
5264         ExprResult CmpRes =
5265             CreateBuiltinBinOp(D.AssignmentLoc, BO_GT, D.Range.Step,
5266                                ActOnIntegerConstant(D.AssignmentLoc, 0).get());
5267         if (!CmpRes.isUsable()) {
5268           IsCorrect = false;
5269           continue;
5270         }
5271         Res = ActOnConditionalOp(D.AssignmentLoc, D.AssignmentLoc, CmpRes.get(),
5272                                  Res.get(), Res1.get());
5273         if (!Res.isUsable()) {
5274           IsCorrect = false;
5275           continue;
5276         }
5277       }
5278       Res = ActOnFinishFullExpr(Res.get(), /*DiscardedValue=*/false);
5279       if (!Res.isUsable()) {
5280         IsCorrect = false;
5281         continue;
5282       }
5283 
5284       // Build counter update.
5285       // Build counter.
5286       auto *CounterVD =
5287           VarDecl::Create(Context, CurContext, D.IteratorDecl->getBeginLoc(),
5288                           D.IteratorDecl->getBeginLoc(), nullptr,
5289                           Res.get()->getType(), nullptr, SC_None);
5290       CounterVD->setImplicit();
5291       ExprResult RefRes =
5292           BuildDeclRefExpr(CounterVD, CounterVD->getType(), VK_LValue,
5293                            D.IteratorDecl->getBeginLoc());
5294       // Build counter update.
5295       // I = Begini + counter * Stepi;
5296       ExprResult UpdateRes;
5297       if (D.Range.Step) {
5298         UpdateRes = CreateBuiltinBinOp(
5299             D.AssignmentLoc, BO_Mul,
5300             DefaultLvalueConversion(RefRes.get()).get(), St.get());
5301       } else {
5302         UpdateRes = DefaultLvalueConversion(RefRes.get());
5303       }
5304       if (!UpdateRes.isUsable()) {
5305         IsCorrect = false;
5306         continue;
5307       }
5308       UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, D.Range.Begin,
5309                                      UpdateRes.get());
5310       if (!UpdateRes.isUsable()) {
5311         IsCorrect = false;
5312         continue;
5313       }
5314       ExprResult VDRes =
5315           BuildDeclRefExpr(cast<VarDecl>(D.IteratorDecl),
5316                            cast<VarDecl>(D.IteratorDecl)->getType(), VK_LValue,
5317                            D.IteratorDecl->getBeginLoc());
5318       UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Assign, VDRes.get(),
5319                                      UpdateRes.get());
5320       if (!UpdateRes.isUsable()) {
5321         IsCorrect = false;
5322         continue;
5323       }
5324       UpdateRes =
5325           ActOnFinishFullExpr(UpdateRes.get(), /*DiscardedValue=*/true);
5326       if (!UpdateRes.isUsable()) {
5327         IsCorrect = false;
5328         continue;
5329       }
5330       ExprResult CounterUpdateRes =
5331           CreateBuiltinUnaryOp(D.AssignmentLoc, UO_PreInc, RefRes.get());
5332       if (!CounterUpdateRes.isUsable()) {
5333         IsCorrect = false;
5334         continue;
5335       }
5336       CounterUpdateRes =
5337           ActOnFinishFullExpr(CounterUpdateRes.get(), /*DiscardedValue=*/true);
5338       if (!CounterUpdateRes.isUsable()) {
5339         IsCorrect = false;
5340         continue;
5341       }
5342       OMPIteratorHelperData &HD = Helpers.emplace_back();
5343       HD.CounterVD = CounterVD;
5344       HD.Upper = Res.get();
5345       HD.Update = UpdateRes.get();
5346       HD.CounterUpdate = CounterUpdateRes.get();
5347     }
5348   } else {
5349     Helpers.assign(ID.size(), {});
5350   }
5351   if (!IsCorrect) {
5352     // Invalidate all created iterator declarations if error is found.
5353     for (const OMPIteratorExpr::IteratorDefinition &D : ID) {
5354       if (Decl *ID = D.IteratorDecl)
5355         ID->setInvalidDecl();
5356     }
5357     return ExprError();
5358   }
5359   return OMPIteratorExpr::Create(Context, Context.OMPIteratorTy, IteratorKwLoc,
5360                                  LLoc, RLoc, ID, Helpers);
5361 }
5362 
5363 ExprResult
5364 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
5365                                       Expr *Idx, SourceLocation RLoc) {
5366   Expr *LHSExp = Base;
5367   Expr *RHSExp = Idx;
5368 
5369   ExprValueKind VK = VK_LValue;
5370   ExprObjectKind OK = OK_Ordinary;
5371 
5372   // Per C++ core issue 1213, the result is an xvalue if either operand is
5373   // a non-lvalue array, and an lvalue otherwise.
5374   if (getLangOpts().CPlusPlus11) {
5375     for (auto *Op : {LHSExp, RHSExp}) {
5376       Op = Op->IgnoreImplicit();
5377       if (Op->getType()->isArrayType() && !Op->isLValue())
5378         VK = VK_XValue;
5379     }
5380   }
5381 
5382   // Perform default conversions.
5383   if (!LHSExp->getType()->getAs<VectorType>()) {
5384     ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
5385     if (Result.isInvalid())
5386       return ExprError();
5387     LHSExp = Result.get();
5388   }
5389   ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
5390   if (Result.isInvalid())
5391     return ExprError();
5392   RHSExp = Result.get();
5393 
5394   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
5395 
5396   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
5397   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
5398   // in the subscript position. As a result, we need to derive the array base
5399   // and index from the expression types.
5400   Expr *BaseExpr, *IndexExpr;
5401   QualType ResultType;
5402   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
5403     BaseExpr = LHSExp;
5404     IndexExpr = RHSExp;
5405     ResultType = Context.DependentTy;
5406   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
5407     BaseExpr = LHSExp;
5408     IndexExpr = RHSExp;
5409     ResultType = PTy->getPointeeType();
5410   } else if (const ObjCObjectPointerType *PTy =
5411                LHSTy->getAs<ObjCObjectPointerType>()) {
5412     BaseExpr = LHSExp;
5413     IndexExpr = RHSExp;
5414 
5415     // Use custom logic if this should be the pseudo-object subscript
5416     // expression.
5417     if (!LangOpts.isSubscriptPointerArithmetic())
5418       return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
5419                                           nullptr);
5420 
5421     ResultType = PTy->getPointeeType();
5422   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
5423      // Handle the uncommon case of "123[Ptr]".
5424     BaseExpr = RHSExp;
5425     IndexExpr = LHSExp;
5426     ResultType = PTy->getPointeeType();
5427   } else if (const ObjCObjectPointerType *PTy =
5428                RHSTy->getAs<ObjCObjectPointerType>()) {
5429      // Handle the uncommon case of "123[Ptr]".
5430     BaseExpr = RHSExp;
5431     IndexExpr = LHSExp;
5432     ResultType = PTy->getPointeeType();
5433     if (!LangOpts.isSubscriptPointerArithmetic()) {
5434       Diag(LLoc, diag::err_subscript_nonfragile_interface)
5435         << ResultType << BaseExpr->getSourceRange();
5436       return ExprError();
5437     }
5438   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
5439     BaseExpr = LHSExp;    // vectors: V[123]
5440     IndexExpr = RHSExp;
5441     // We apply C++ DR1213 to vector subscripting too.
5442     if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_RValue) {
5443       ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
5444       if (Materialized.isInvalid())
5445         return ExprError();
5446       LHSExp = Materialized.get();
5447     }
5448     VK = LHSExp->getValueKind();
5449     if (VK != VK_RValue)
5450       OK = OK_VectorComponent;
5451 
5452     ResultType = VTy->getElementType();
5453     QualType BaseType = BaseExpr->getType();
5454     Qualifiers BaseQuals = BaseType.getQualifiers();
5455     Qualifiers MemberQuals = ResultType.getQualifiers();
5456     Qualifiers Combined = BaseQuals + MemberQuals;
5457     if (Combined != MemberQuals)
5458       ResultType = Context.getQualifiedType(ResultType, Combined);
5459   } else if (LHSTy->isArrayType()) {
5460     // If we see an array that wasn't promoted by
5461     // DefaultFunctionArrayLvalueConversion, it must be an array that
5462     // wasn't promoted because of the C90 rule that doesn't
5463     // allow promoting non-lvalue arrays.  Warn, then
5464     // force the promotion here.
5465     Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5466         << LHSExp->getSourceRange();
5467     LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
5468                                CK_ArrayToPointerDecay).get();
5469     LHSTy = LHSExp->getType();
5470 
5471     BaseExpr = LHSExp;
5472     IndexExpr = RHSExp;
5473     ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
5474   } else if (RHSTy->isArrayType()) {
5475     // Same as previous, except for 123[f().a] case
5476     Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5477         << RHSExp->getSourceRange();
5478     RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
5479                                CK_ArrayToPointerDecay).get();
5480     RHSTy = RHSExp->getType();
5481 
5482     BaseExpr = RHSExp;
5483     IndexExpr = LHSExp;
5484     ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
5485   } else {
5486     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
5487        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
5488   }
5489   // C99 6.5.2.1p1
5490   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
5491     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
5492                      << IndexExpr->getSourceRange());
5493 
5494   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5495        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5496          && !IndexExpr->isTypeDependent())
5497     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
5498 
5499   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5500   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5501   // type. Note that Functions are not objects, and that (in C99 parlance)
5502   // incomplete types are not object types.
5503   if (ResultType->isFunctionType()) {
5504     Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type)
5505         << ResultType << BaseExpr->getSourceRange();
5506     return ExprError();
5507   }
5508 
5509   if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
5510     // GNU extension: subscripting on pointer to void
5511     Diag(LLoc, diag::ext_gnu_subscript_void_type)
5512       << BaseExpr->getSourceRange();
5513 
5514     // C forbids expressions of unqualified void type from being l-values.
5515     // See IsCForbiddenLValueType.
5516     if (!ResultType.hasQualifiers()) VK = VK_RValue;
5517   } else if (!ResultType->isDependentType() &&
5518              RequireCompleteSizedType(
5519                  LLoc, ResultType,
5520                  diag::err_subscript_incomplete_or_sizeless_type, BaseExpr))
5521     return ExprError();
5522 
5523   assert(VK == VK_RValue || LangOpts.CPlusPlus ||
5524          !ResultType.isCForbiddenLValueType());
5525 
5526   if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() &&
5527       FunctionScopes.size() > 1) {
5528     if (auto *TT =
5529             LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) {
5530       for (auto I = FunctionScopes.rbegin(),
5531                 E = std::prev(FunctionScopes.rend());
5532            I != E; ++I) {
5533         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
5534         if (CSI == nullptr)
5535           break;
5536         DeclContext *DC = nullptr;
5537         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
5538           DC = LSI->CallOperator;
5539         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
5540           DC = CRSI->TheCapturedDecl;
5541         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
5542           DC = BSI->TheDecl;
5543         if (DC) {
5544           if (DC->containsDecl(TT->getDecl()))
5545             break;
5546           captureVariablyModifiedType(
5547               Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI);
5548         }
5549       }
5550     }
5551   }
5552 
5553   return new (Context)
5554       ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
5555 }
5556 
5557 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
5558                                   ParmVarDecl *Param) {
5559   if (Param->hasUnparsedDefaultArg()) {
5560     // If we've already cleared out the location for the default argument,
5561     // that means we're parsing it right now.
5562     if (!UnparsedDefaultArgLocs.count(Param)) {
5563       Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
5564       Diag(CallLoc, diag::note_recursive_default_argument_used_here);
5565       Param->setInvalidDecl();
5566       return true;
5567     }
5568 
5569     Diag(CallLoc, diag::err_use_of_default_argument_to_function_declared_later)
5570         << FD << cast<CXXRecordDecl>(FD->getDeclContext());
5571     Diag(UnparsedDefaultArgLocs[Param],
5572          diag::note_default_argument_declared_here);
5573     return true;
5574   }
5575 
5576   if (Param->hasUninstantiatedDefaultArg() &&
5577       InstantiateDefaultArgument(CallLoc, FD, Param))
5578     return true;
5579 
5580   assert(Param->hasInit() && "default argument but no initializer?");
5581 
5582   // If the default expression creates temporaries, we need to
5583   // push them to the current stack of expression temporaries so they'll
5584   // be properly destroyed.
5585   // FIXME: We should really be rebuilding the default argument with new
5586   // bound temporaries; see the comment in PR5810.
5587   // We don't need to do that with block decls, though, because
5588   // blocks in default argument expression can never capture anything.
5589   if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
5590     // Set the "needs cleanups" bit regardless of whether there are
5591     // any explicit objects.
5592     Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
5593 
5594     // Append all the objects to the cleanup list.  Right now, this
5595     // should always be a no-op, because blocks in default argument
5596     // expressions should never be able to capture anything.
5597     assert(!Init->getNumObjects() &&
5598            "default argument expression has capturing blocks?");
5599   }
5600 
5601   // We already type-checked the argument, so we know it works.
5602   // Just mark all of the declarations in this potentially-evaluated expression
5603   // as being "referenced".
5604   EnterExpressionEvaluationContext EvalContext(
5605       *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
5606   MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
5607                                    /*SkipLocalVariables=*/true);
5608   return false;
5609 }
5610 
5611 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
5612                                         FunctionDecl *FD, ParmVarDecl *Param) {
5613   assert(Param->hasDefaultArg() && "can't build nonexistent default arg");
5614   if (CheckCXXDefaultArgExpr(CallLoc, FD, Param))
5615     return ExprError();
5616   return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext);
5617 }
5618 
5619 Sema::VariadicCallType
5620 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
5621                           Expr *Fn) {
5622   if (Proto && Proto->isVariadic()) {
5623     if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
5624       return VariadicConstructor;
5625     else if (Fn && Fn->getType()->isBlockPointerType())
5626       return VariadicBlock;
5627     else if (FDecl) {
5628       if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5629         if (Method->isInstance())
5630           return VariadicMethod;
5631     } else if (Fn && Fn->getType() == Context.BoundMemberTy)
5632       return VariadicMethod;
5633     return VariadicFunction;
5634   }
5635   return VariadicDoesNotApply;
5636 }
5637 
5638 namespace {
5639 class FunctionCallCCC final : public FunctionCallFilterCCC {
5640 public:
5641   FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
5642                   unsigned NumArgs, MemberExpr *ME)
5643       : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
5644         FunctionName(FuncName) {}
5645 
5646   bool ValidateCandidate(const TypoCorrection &candidate) override {
5647     if (!candidate.getCorrectionSpecifier() ||
5648         candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
5649       return false;
5650     }
5651 
5652     return FunctionCallFilterCCC::ValidateCandidate(candidate);
5653   }
5654 
5655   std::unique_ptr<CorrectionCandidateCallback> clone() override {
5656     return std::make_unique<FunctionCallCCC>(*this);
5657   }
5658 
5659 private:
5660   const IdentifierInfo *const FunctionName;
5661 };
5662 }
5663 
5664 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
5665                                                FunctionDecl *FDecl,
5666                                                ArrayRef<Expr *> Args) {
5667   MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
5668   DeclarationName FuncName = FDecl->getDeclName();
5669   SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
5670 
5671   FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
5672   if (TypoCorrection Corrected = S.CorrectTypo(
5673           DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
5674           S.getScopeForContext(S.CurContext), nullptr, CCC,
5675           Sema::CTK_ErrorRecovery)) {
5676     if (NamedDecl *ND = Corrected.getFoundDecl()) {
5677       if (Corrected.isOverloaded()) {
5678         OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
5679         OverloadCandidateSet::iterator Best;
5680         for (NamedDecl *CD : Corrected) {
5681           if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
5682             S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
5683                                    OCS);
5684         }
5685         switch (OCS.BestViableFunction(S, NameLoc, Best)) {
5686         case OR_Success:
5687           ND = Best->FoundDecl;
5688           Corrected.setCorrectionDecl(ND);
5689           break;
5690         default:
5691           break;
5692         }
5693       }
5694       ND = ND->getUnderlyingDecl();
5695       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
5696         return Corrected;
5697     }
5698   }
5699   return TypoCorrection();
5700 }
5701 
5702 /// ConvertArgumentsForCall - Converts the arguments specified in
5703 /// Args/NumArgs to the parameter types of the function FDecl with
5704 /// function prototype Proto. Call is the call expression itself, and
5705 /// Fn is the function expression. For a C++ member function, this
5706 /// routine does not attempt to convert the object argument. Returns
5707 /// true if the call is ill-formed.
5708 bool
5709 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
5710                               FunctionDecl *FDecl,
5711                               const FunctionProtoType *Proto,
5712                               ArrayRef<Expr *> Args,
5713                               SourceLocation RParenLoc,
5714                               bool IsExecConfig) {
5715   // Bail out early if calling a builtin with custom typechecking.
5716   if (FDecl)
5717     if (unsigned ID = FDecl->getBuiltinID())
5718       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
5719         return false;
5720 
5721   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
5722   // assignment, to the types of the corresponding parameter, ...
5723   unsigned NumParams = Proto->getNumParams();
5724   bool Invalid = false;
5725   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
5726   unsigned FnKind = Fn->getType()->isBlockPointerType()
5727                        ? 1 /* block */
5728                        : (IsExecConfig ? 3 /* kernel function (exec config) */
5729                                        : 0 /* function */);
5730 
5731   // If too few arguments are available (and we don't have default
5732   // arguments for the remaining parameters), don't make the call.
5733   if (Args.size() < NumParams) {
5734     if (Args.size() < MinArgs) {
5735       TypoCorrection TC;
5736       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5737         unsigned diag_id =
5738             MinArgs == NumParams && !Proto->isVariadic()
5739                 ? diag::err_typecheck_call_too_few_args_suggest
5740                 : diag::err_typecheck_call_too_few_args_at_least_suggest;
5741         diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
5742                                         << static_cast<unsigned>(Args.size())
5743                                         << TC.getCorrectionRange());
5744       } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
5745         Diag(RParenLoc,
5746              MinArgs == NumParams && !Proto->isVariadic()
5747                  ? diag::err_typecheck_call_too_few_args_one
5748                  : diag::err_typecheck_call_too_few_args_at_least_one)
5749             << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
5750       else
5751         Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
5752                             ? diag::err_typecheck_call_too_few_args
5753                             : diag::err_typecheck_call_too_few_args_at_least)
5754             << FnKind << MinArgs << static_cast<unsigned>(Args.size())
5755             << Fn->getSourceRange();
5756 
5757       // Emit the location of the prototype.
5758       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5759         Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
5760 
5761       return true;
5762     }
5763     // We reserve space for the default arguments when we create
5764     // the call expression, before calling ConvertArgumentsForCall.
5765     assert((Call->getNumArgs() == NumParams) &&
5766            "We should have reserved space for the default arguments before!");
5767   }
5768 
5769   // If too many are passed and not variadic, error on the extras and drop
5770   // them.
5771   if (Args.size() > NumParams) {
5772     if (!Proto->isVariadic()) {
5773       TypoCorrection TC;
5774       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5775         unsigned diag_id =
5776             MinArgs == NumParams && !Proto->isVariadic()
5777                 ? diag::err_typecheck_call_too_many_args_suggest
5778                 : diag::err_typecheck_call_too_many_args_at_most_suggest;
5779         diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
5780                                         << static_cast<unsigned>(Args.size())
5781                                         << TC.getCorrectionRange());
5782       } else if (NumParams == 1 && FDecl &&
5783                  FDecl->getParamDecl(0)->getDeclName())
5784         Diag(Args[NumParams]->getBeginLoc(),
5785              MinArgs == NumParams
5786                  ? diag::err_typecheck_call_too_many_args_one
5787                  : diag::err_typecheck_call_too_many_args_at_most_one)
5788             << FnKind << FDecl->getParamDecl(0)
5789             << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
5790             << SourceRange(Args[NumParams]->getBeginLoc(),
5791                            Args.back()->getEndLoc());
5792       else
5793         Diag(Args[NumParams]->getBeginLoc(),
5794              MinArgs == NumParams
5795                  ? diag::err_typecheck_call_too_many_args
5796                  : diag::err_typecheck_call_too_many_args_at_most)
5797             << FnKind << NumParams << static_cast<unsigned>(Args.size())
5798             << Fn->getSourceRange()
5799             << SourceRange(Args[NumParams]->getBeginLoc(),
5800                            Args.back()->getEndLoc());
5801 
5802       // Emit the location of the prototype.
5803       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5804         Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
5805 
5806       // This deletes the extra arguments.
5807       Call->shrinkNumArgs(NumParams);
5808       return true;
5809     }
5810   }
5811   SmallVector<Expr *, 8> AllArgs;
5812   VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
5813 
5814   Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args,
5815                                    AllArgs, CallType);
5816   if (Invalid)
5817     return true;
5818   unsigned TotalNumArgs = AllArgs.size();
5819   for (unsigned i = 0; i < TotalNumArgs; ++i)
5820     Call->setArg(i, AllArgs[i]);
5821 
5822   return false;
5823 }
5824 
5825 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
5826                                   const FunctionProtoType *Proto,
5827                                   unsigned FirstParam, ArrayRef<Expr *> Args,
5828                                   SmallVectorImpl<Expr *> &AllArgs,
5829                                   VariadicCallType CallType, bool AllowExplicit,
5830                                   bool IsListInitialization) {
5831   unsigned NumParams = Proto->getNumParams();
5832   bool Invalid = false;
5833   size_t ArgIx = 0;
5834   // Continue to check argument types (even if we have too few/many args).
5835   for (unsigned i = FirstParam; i < NumParams; i++) {
5836     QualType ProtoArgType = Proto->getParamType(i);
5837 
5838     Expr *Arg;
5839     ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
5840     if (ArgIx < Args.size()) {
5841       Arg = Args[ArgIx++];
5842 
5843       if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType,
5844                               diag::err_call_incomplete_argument, Arg))
5845         return true;
5846 
5847       // Strip the unbridged-cast placeholder expression off, if applicable.
5848       bool CFAudited = false;
5849       if (Arg->getType() == Context.ARCUnbridgedCastTy &&
5850           FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5851           (!Param || !Param->hasAttr<CFConsumedAttr>()))
5852         Arg = stripARCUnbridgedCast(Arg);
5853       else if (getLangOpts().ObjCAutoRefCount &&
5854                FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5855                (!Param || !Param->hasAttr<CFConsumedAttr>()))
5856         CFAudited = true;
5857 
5858       if (Proto->getExtParameterInfo(i).isNoEscape())
5859         if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
5860           BE->getBlockDecl()->setDoesNotEscape();
5861 
5862       InitializedEntity Entity =
5863           Param ? InitializedEntity::InitializeParameter(Context, Param,
5864                                                          ProtoArgType)
5865                 : InitializedEntity::InitializeParameter(
5866                       Context, ProtoArgType, Proto->isParamConsumed(i));
5867 
5868       // Remember that parameter belongs to a CF audited API.
5869       if (CFAudited)
5870         Entity.setParameterCFAudited();
5871 
5872       ExprResult ArgE = PerformCopyInitialization(
5873           Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
5874       if (ArgE.isInvalid())
5875         return true;
5876 
5877       Arg = ArgE.getAs<Expr>();
5878     } else {
5879       assert(Param && "can't use default arguments without a known callee");
5880 
5881       ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
5882       if (ArgExpr.isInvalid())
5883         return true;
5884 
5885       Arg = ArgExpr.getAs<Expr>();
5886     }
5887 
5888     // Check for array bounds violations for each argument to the call. This
5889     // check only triggers warnings when the argument isn't a more complex Expr
5890     // with its own checking, such as a BinaryOperator.
5891     CheckArrayAccess(Arg);
5892 
5893     // Check for violations of C99 static array rules (C99 6.7.5.3p7).
5894     CheckStaticArrayArgument(CallLoc, Param, Arg);
5895 
5896     AllArgs.push_back(Arg);
5897   }
5898 
5899   // If this is a variadic call, handle args passed through "...".
5900   if (CallType != VariadicDoesNotApply) {
5901     // Assume that extern "C" functions with variadic arguments that
5902     // return __unknown_anytype aren't *really* variadic.
5903     if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
5904         FDecl->isExternC()) {
5905       for (Expr *A : Args.slice(ArgIx)) {
5906         QualType paramType; // ignored
5907         ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
5908         Invalid |= arg.isInvalid();
5909         AllArgs.push_back(arg.get());
5910       }
5911 
5912     // Otherwise do argument promotion, (C99 6.5.2.2p7).
5913     } else {
5914       for (Expr *A : Args.slice(ArgIx)) {
5915         ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
5916         Invalid |= Arg.isInvalid();
5917         AllArgs.push_back(Arg.get());
5918       }
5919     }
5920 
5921     // Check for array bounds violations.
5922     for (Expr *A : Args.slice(ArgIx))
5923       CheckArrayAccess(A);
5924   }
5925   return Invalid;
5926 }
5927 
5928 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
5929   TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
5930   if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
5931     TL = DTL.getOriginalLoc();
5932   if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
5933     S.Diag(PVD->getLocation(), diag::note_callee_static_array)
5934       << ATL.getLocalSourceRange();
5935 }
5936 
5937 /// CheckStaticArrayArgument - If the given argument corresponds to a static
5938 /// array parameter, check that it is non-null, and that if it is formed by
5939 /// array-to-pointer decay, the underlying array is sufficiently large.
5940 ///
5941 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
5942 /// array type derivation, then for each call to the function, the value of the
5943 /// corresponding actual argument shall provide access to the first element of
5944 /// an array with at least as many elements as specified by the size expression.
5945 void
5946 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
5947                                ParmVarDecl *Param,
5948                                const Expr *ArgExpr) {
5949   // Static array parameters are not supported in C++.
5950   if (!Param || getLangOpts().CPlusPlus)
5951     return;
5952 
5953   QualType OrigTy = Param->getOriginalType();
5954 
5955   const ArrayType *AT = Context.getAsArrayType(OrigTy);
5956   if (!AT || AT->getSizeModifier() != ArrayType::Static)
5957     return;
5958 
5959   if (ArgExpr->isNullPointerConstant(Context,
5960                                      Expr::NPC_NeverValueDependent)) {
5961     Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
5962     DiagnoseCalleeStaticArrayParam(*this, Param);
5963     return;
5964   }
5965 
5966   const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
5967   if (!CAT)
5968     return;
5969 
5970   const ConstantArrayType *ArgCAT =
5971     Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType());
5972   if (!ArgCAT)
5973     return;
5974 
5975   if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(),
5976                                              ArgCAT->getElementType())) {
5977     if (ArgCAT->getSize().ult(CAT->getSize())) {
5978       Diag(CallLoc, diag::warn_static_array_too_small)
5979           << ArgExpr->getSourceRange()
5980           << (unsigned)ArgCAT->getSize().getZExtValue()
5981           << (unsigned)CAT->getSize().getZExtValue() << 0;
5982       DiagnoseCalleeStaticArrayParam(*this, Param);
5983     }
5984     return;
5985   }
5986 
5987   Optional<CharUnits> ArgSize =
5988       getASTContext().getTypeSizeInCharsIfKnown(ArgCAT);
5989   Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT);
5990   if (ArgSize && ParmSize && *ArgSize < *ParmSize) {
5991     Diag(CallLoc, diag::warn_static_array_too_small)
5992         << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()
5993         << (unsigned)ParmSize->getQuantity() << 1;
5994     DiagnoseCalleeStaticArrayParam(*this, Param);
5995   }
5996 }
5997 
5998 /// Given a function expression of unknown-any type, try to rebuild it
5999 /// to have a function type.
6000 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
6001 
6002 /// Is the given type a placeholder that we need to lower out
6003 /// immediately during argument processing?
6004 static bool isPlaceholderToRemoveAsArg(QualType type) {
6005   // Placeholders are never sugared.
6006   const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
6007   if (!placeholder) return false;
6008 
6009   switch (placeholder->getKind()) {
6010   // Ignore all the non-placeholder types.
6011 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6012   case BuiltinType::Id:
6013 #include "clang/Basic/OpenCLImageTypes.def"
6014 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6015   case BuiltinType::Id:
6016 #include "clang/Basic/OpenCLExtensionTypes.def"
6017   // In practice we'll never use this, since all SVE types are sugared
6018   // via TypedefTypes rather than exposed directly as BuiltinTypes.
6019 #define SVE_TYPE(Name, Id, SingletonId) \
6020   case BuiltinType::Id:
6021 #include "clang/Basic/AArch64SVEACLETypes.def"
6022 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
6023 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
6024 #include "clang/AST/BuiltinTypes.def"
6025     return false;
6026 
6027   // We cannot lower out overload sets; they might validly be resolved
6028   // by the call machinery.
6029   case BuiltinType::Overload:
6030     return false;
6031 
6032   // Unbridged casts in ARC can be handled in some call positions and
6033   // should be left in place.
6034   case BuiltinType::ARCUnbridgedCast:
6035     return false;
6036 
6037   // Pseudo-objects should be converted as soon as possible.
6038   case BuiltinType::PseudoObject:
6039     return true;
6040 
6041   // The debugger mode could theoretically but currently does not try
6042   // to resolve unknown-typed arguments based on known parameter types.
6043   case BuiltinType::UnknownAny:
6044     return true;
6045 
6046   // These are always invalid as call arguments and should be reported.
6047   case BuiltinType::BoundMember:
6048   case BuiltinType::BuiltinFn:
6049   case BuiltinType::IncompleteMatrixIdx:
6050   case BuiltinType::OMPArraySection:
6051   case BuiltinType::OMPArrayShaping:
6052   case BuiltinType::OMPIterator:
6053     return true;
6054 
6055   }
6056   llvm_unreachable("bad builtin type kind");
6057 }
6058 
6059 /// Check an argument list for placeholders that we won't try to
6060 /// handle later.
6061 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
6062   // Apply this processing to all the arguments at once instead of
6063   // dying at the first failure.
6064   bool hasInvalid = false;
6065   for (size_t i = 0, e = args.size(); i != e; i++) {
6066     if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
6067       ExprResult result = S.CheckPlaceholderExpr(args[i]);
6068       if (result.isInvalid()) hasInvalid = true;
6069       else args[i] = result.get();
6070     } else if (hasInvalid) {
6071       (void)S.CorrectDelayedTyposInExpr(args[i]);
6072     }
6073   }
6074   return hasInvalid;
6075 }
6076 
6077 /// If a builtin function has a pointer argument with no explicit address
6078 /// space, then it should be able to accept a pointer to any address
6079 /// space as input.  In order to do this, we need to replace the
6080 /// standard builtin declaration with one that uses the same address space
6081 /// as the call.
6082 ///
6083 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
6084 ///                  it does not contain any pointer arguments without
6085 ///                  an address space qualifer.  Otherwise the rewritten
6086 ///                  FunctionDecl is returned.
6087 /// TODO: Handle pointer return types.
6088 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
6089                                                 FunctionDecl *FDecl,
6090                                                 MultiExprArg ArgExprs) {
6091 
6092   QualType DeclType = FDecl->getType();
6093   const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
6094 
6095   if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT ||
6096       ArgExprs.size() < FT->getNumParams())
6097     return nullptr;
6098 
6099   bool NeedsNewDecl = false;
6100   unsigned i = 0;
6101   SmallVector<QualType, 8> OverloadParams;
6102 
6103   for (QualType ParamType : FT->param_types()) {
6104 
6105     // Convert array arguments to pointer to simplify type lookup.
6106     ExprResult ArgRes =
6107         Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
6108     if (ArgRes.isInvalid())
6109       return nullptr;
6110     Expr *Arg = ArgRes.get();
6111     QualType ArgType = Arg->getType();
6112     if (!ParamType->isPointerType() ||
6113         ParamType.hasAddressSpace() ||
6114         !ArgType->isPointerType() ||
6115         !ArgType->getPointeeType().hasAddressSpace()) {
6116       OverloadParams.push_back(ParamType);
6117       continue;
6118     }
6119 
6120     QualType PointeeType = ParamType->getPointeeType();
6121     if (PointeeType.hasAddressSpace())
6122       continue;
6123 
6124     NeedsNewDecl = true;
6125     LangAS AS = ArgType->getPointeeType().getAddressSpace();
6126 
6127     PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
6128     OverloadParams.push_back(Context.getPointerType(PointeeType));
6129   }
6130 
6131   if (!NeedsNewDecl)
6132     return nullptr;
6133 
6134   FunctionProtoType::ExtProtoInfo EPI;
6135   EPI.Variadic = FT->isVariadic();
6136   QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
6137                                                 OverloadParams, EPI);
6138   DeclContext *Parent = FDecl->getParent();
6139   FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
6140                                                     FDecl->getLocation(),
6141                                                     FDecl->getLocation(),
6142                                                     FDecl->getIdentifier(),
6143                                                     OverloadTy,
6144                                                     /*TInfo=*/nullptr,
6145                                                     SC_Extern, false,
6146                                                     /*hasPrototype=*/true);
6147   SmallVector<ParmVarDecl*, 16> Params;
6148   FT = cast<FunctionProtoType>(OverloadTy);
6149   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
6150     QualType ParamType = FT->getParamType(i);
6151     ParmVarDecl *Parm =
6152         ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
6153                                 SourceLocation(), nullptr, ParamType,
6154                                 /*TInfo=*/nullptr, SC_None, nullptr);
6155     Parm->setScopeInfo(0, i);
6156     Params.push_back(Parm);
6157   }
6158   OverloadDecl->setParams(Params);
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(Context, E.get()->getType(),
6964                                CK_ARCExtendBlockObject, E.get(),
6965                                /*base path*/ nullptr, VK_RValue);
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         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   return Func->isConstexpr() &&
16585          (Func->isImplicitlyInstantiable() || !Func->isUserProvided());
16586 }
16587 
16588 /// Mark a function referenced, and check whether it is odr-used
16589 /// (C++ [basic.def.odr]p2, C99 6.9p3)
16590 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
16591                                   bool MightBeOdrUse) {
16592   assert(Func && "No function?");
16593 
16594   Func->setReferenced();
16595 
16596   // Recursive functions aren't really used until they're used from some other
16597   // context.
16598   bool IsRecursiveCall = CurContext == Func;
16599 
16600   // C++11 [basic.def.odr]p3:
16601   //   A function whose name appears as a potentially-evaluated expression is
16602   //   odr-used if it is the unique lookup result or the selected member of a
16603   //   set of overloaded functions [...].
16604   //
16605   // We (incorrectly) mark overload resolution as an unevaluated context, so we
16606   // can just check that here.
16607   OdrUseContext OdrUse =
16608       MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None;
16609   if (IsRecursiveCall && OdrUse == OdrUseContext::Used)
16610     OdrUse = OdrUseContext::FormallyOdrUsed;
16611 
16612   // Trivial default constructors and destructors are never actually used.
16613   // FIXME: What about other special members?
16614   if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() &&
16615       OdrUse == OdrUseContext::Used) {
16616     if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func))
16617       if (Constructor->isDefaultConstructor())
16618         OdrUse = OdrUseContext::FormallyOdrUsed;
16619     if (isa<CXXDestructorDecl>(Func))
16620       OdrUse = OdrUseContext::FormallyOdrUsed;
16621   }
16622 
16623   // C++20 [expr.const]p12:
16624   //   A function [...] is needed for constant evaluation if it is [...] a
16625   //   constexpr function that is named by an expression that is potentially
16626   //   constant evaluated
16627   bool NeededForConstantEvaluation =
16628       isPotentiallyConstantEvaluatedContext(*this) &&
16629       isImplicitlyDefinableConstexprFunction(Func);
16630 
16631   // Determine whether we require a function definition to exist, per
16632   // C++11 [temp.inst]p3:
16633   //   Unless a function template specialization has been explicitly
16634   //   instantiated or explicitly specialized, the function template
16635   //   specialization is implicitly instantiated when the specialization is
16636   //   referenced in a context that requires a function definition to exist.
16637   // C++20 [temp.inst]p7:
16638   //   The existence of a definition of a [...] function is considered to
16639   //   affect the semantics of the program if the [...] function is needed for
16640   //   constant evaluation by an expression
16641   // C++20 [basic.def.odr]p10:
16642   //   Every program shall contain exactly one definition of every non-inline
16643   //   function or variable that is odr-used in that program outside of a
16644   //   discarded statement
16645   // C++20 [special]p1:
16646   //   The implementation will implicitly define [defaulted special members]
16647   //   if they are odr-used or needed for constant evaluation.
16648   //
16649   // Note that we skip the implicit instantiation of templates that are only
16650   // used in unused default arguments or by recursive calls to themselves.
16651   // This is formally non-conforming, but seems reasonable in practice.
16652   bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used ||
16653                                              NeededForConstantEvaluation);
16654 
16655   // C++14 [temp.expl.spec]p6:
16656   //   If a template [...] is explicitly specialized then that specialization
16657   //   shall be declared before the first use of that specialization that would
16658   //   cause an implicit instantiation to take place, in every translation unit
16659   //   in which such a use occurs
16660   if (NeedDefinition &&
16661       (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
16662        Func->getMemberSpecializationInfo()))
16663     checkSpecializationVisibility(Loc, Func);
16664 
16665   if (getLangOpts().CUDA)
16666     CheckCUDACall(Loc, Func);
16667 
16668   if (getLangOpts().SYCLIsDevice)
16669     checkSYCLDeviceFunction(Loc, Func);
16670 
16671   // If we need a definition, try to create one.
16672   if (NeedDefinition && !Func->getBody()) {
16673     runWithSufficientStackSpace(Loc, [&] {
16674       if (CXXConstructorDecl *Constructor =
16675               dyn_cast<CXXConstructorDecl>(Func)) {
16676         Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
16677         if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
16678           if (Constructor->isDefaultConstructor()) {
16679             if (Constructor->isTrivial() &&
16680                 !Constructor->hasAttr<DLLExportAttr>())
16681               return;
16682             DefineImplicitDefaultConstructor(Loc, Constructor);
16683           } else if (Constructor->isCopyConstructor()) {
16684             DefineImplicitCopyConstructor(Loc, Constructor);
16685           } else if (Constructor->isMoveConstructor()) {
16686             DefineImplicitMoveConstructor(Loc, Constructor);
16687           }
16688         } else if (Constructor->getInheritedConstructor()) {
16689           DefineInheritingConstructor(Loc, Constructor);
16690         }
16691       } else if (CXXDestructorDecl *Destructor =
16692                      dyn_cast<CXXDestructorDecl>(Func)) {
16693         Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
16694         if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
16695           if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
16696             return;
16697           DefineImplicitDestructor(Loc, Destructor);
16698         }
16699         if (Destructor->isVirtual() && getLangOpts().AppleKext)
16700           MarkVTableUsed(Loc, Destructor->getParent());
16701       } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
16702         if (MethodDecl->isOverloadedOperator() &&
16703             MethodDecl->getOverloadedOperator() == OO_Equal) {
16704           MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
16705           if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
16706             if (MethodDecl->isCopyAssignmentOperator())
16707               DefineImplicitCopyAssignment(Loc, MethodDecl);
16708             else if (MethodDecl->isMoveAssignmentOperator())
16709               DefineImplicitMoveAssignment(Loc, MethodDecl);
16710           }
16711         } else if (isa<CXXConversionDecl>(MethodDecl) &&
16712                    MethodDecl->getParent()->isLambda()) {
16713           CXXConversionDecl *Conversion =
16714               cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
16715           if (Conversion->isLambdaToBlockPointerConversion())
16716             DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
16717           else
16718             DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
16719         } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
16720           MarkVTableUsed(Loc, MethodDecl->getParent());
16721       }
16722 
16723       if (Func->isDefaulted() && !Func->isDeleted()) {
16724         DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func);
16725         if (DCK != DefaultedComparisonKind::None)
16726           DefineDefaultedComparison(Loc, Func, DCK);
16727       }
16728 
16729       // Implicit instantiation of function templates and member functions of
16730       // class templates.
16731       if (Func->isImplicitlyInstantiable()) {
16732         TemplateSpecializationKind TSK =
16733             Func->getTemplateSpecializationKindForInstantiation();
16734         SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
16735         bool FirstInstantiation = PointOfInstantiation.isInvalid();
16736         if (FirstInstantiation) {
16737           PointOfInstantiation = Loc;
16738           Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
16739         } else if (TSK != TSK_ImplicitInstantiation) {
16740           // Use the point of use as the point of instantiation, instead of the
16741           // point of explicit instantiation (which we track as the actual point
16742           // of instantiation). This gives better backtraces in diagnostics.
16743           PointOfInstantiation = Loc;
16744         }
16745 
16746         if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
16747             Func->isConstexpr()) {
16748           if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
16749               cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
16750               CodeSynthesisContexts.size())
16751             PendingLocalImplicitInstantiations.push_back(
16752                 std::make_pair(Func, PointOfInstantiation));
16753           else if (Func->isConstexpr())
16754             // Do not defer instantiations of constexpr functions, to avoid the
16755             // expression evaluator needing to call back into Sema if it sees a
16756             // call to such a function.
16757             InstantiateFunctionDefinition(PointOfInstantiation, Func);
16758           else {
16759             Func->setInstantiationIsPending(true);
16760             PendingInstantiations.push_back(
16761                 std::make_pair(Func, PointOfInstantiation));
16762             // Notify the consumer that a function was implicitly instantiated.
16763             Consumer.HandleCXXImplicitFunctionInstantiation(Func);
16764           }
16765         }
16766       } else {
16767         // Walk redefinitions, as some of them may be instantiable.
16768         for (auto i : Func->redecls()) {
16769           if (!i->isUsed(false) && i->isImplicitlyInstantiable())
16770             MarkFunctionReferenced(Loc, i, MightBeOdrUse);
16771         }
16772       }
16773     });
16774   }
16775 
16776   // C++14 [except.spec]p17:
16777   //   An exception-specification is considered to be needed when:
16778   //   - the function is odr-used or, if it appears in an unevaluated operand,
16779   //     would be odr-used if the expression were potentially-evaluated;
16780   //
16781   // Note, we do this even if MightBeOdrUse is false. That indicates that the
16782   // function is a pure virtual function we're calling, and in that case the
16783   // function was selected by overload resolution and we need to resolve its
16784   // exception specification for a different reason.
16785   const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
16786   if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
16787     ResolveExceptionSpec(Loc, FPT);
16788 
16789   // If this is the first "real" use, act on that.
16790   if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) {
16791     // Keep track of used but undefined functions.
16792     if (!Func->isDefined()) {
16793       if (mightHaveNonExternalLinkage(Func))
16794         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
16795       else if (Func->getMostRecentDecl()->isInlined() &&
16796                !LangOpts.GNUInline &&
16797                !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
16798         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
16799       else if (isExternalWithNoLinkageType(Func))
16800         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
16801     }
16802 
16803     // Some x86 Windows calling conventions mangle the size of the parameter
16804     // pack into the name. Computing the size of the parameters requires the
16805     // parameter types to be complete. Check that now.
16806     if (funcHasParameterSizeMangling(*this, Func))
16807       CheckCompleteParameterTypesForMangler(*this, Func, Loc);
16808 
16809     // In the MS C++ ABI, the compiler emits destructor variants where they are
16810     // used. If the destructor is used here but defined elsewhere, mark the
16811     // virtual base destructors referenced. If those virtual base destructors
16812     // are inline, this will ensure they are defined when emitting the complete
16813     // destructor variant. This checking may be redundant if the destructor is
16814     // provided later in this TU.
16815     if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
16816       if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) {
16817         CXXRecordDecl *Parent = Dtor->getParent();
16818         if (Parent->getNumVBases() > 0 && !Dtor->getBody())
16819           CheckCompleteDestructorVariant(Loc, Dtor);
16820       }
16821     }
16822 
16823     Func->markUsed(Context);
16824   }
16825 }
16826 
16827 /// Directly mark a variable odr-used. Given a choice, prefer to use
16828 /// MarkVariableReferenced since it does additional checks and then
16829 /// calls MarkVarDeclODRUsed.
16830 /// If the variable must be captured:
16831 ///  - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
16832 ///  - else capture it in the DeclContext that maps to the
16833 ///    *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
16834 static void
16835 MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef,
16836                    const unsigned *const FunctionScopeIndexToStopAt = nullptr) {
16837   // Keep track of used but undefined variables.
16838   // FIXME: We shouldn't suppress this warning for static data members.
16839   if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
16840       (!Var->isExternallyVisible() || Var->isInline() ||
16841        SemaRef.isExternalWithNoLinkageType(Var)) &&
16842       !(Var->isStaticDataMember() && Var->hasInit())) {
16843     SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()];
16844     if (old.isInvalid())
16845       old = Loc;
16846   }
16847   QualType CaptureType, DeclRefType;
16848   if (SemaRef.LangOpts.OpenMP)
16849     SemaRef.tryCaptureOpenMPLambdas(Var);
16850   SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit,
16851     /*EllipsisLoc*/ SourceLocation(),
16852     /*BuildAndDiagnose*/ true,
16853     CaptureType, DeclRefType,
16854     FunctionScopeIndexToStopAt);
16855 
16856   Var->markUsed(SemaRef.Context);
16857 }
16858 
16859 void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture,
16860                                              SourceLocation Loc,
16861                                              unsigned CapturingScopeIndex) {
16862   MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex);
16863 }
16864 
16865 static void
16866 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
16867                                    ValueDecl *var, DeclContext *DC) {
16868   DeclContext *VarDC = var->getDeclContext();
16869 
16870   //  If the parameter still belongs to the translation unit, then
16871   //  we're actually just using one parameter in the declaration of
16872   //  the next.
16873   if (isa<ParmVarDecl>(var) &&
16874       isa<TranslationUnitDecl>(VarDC))
16875     return;
16876 
16877   // For C code, don't diagnose about capture if we're not actually in code
16878   // right now; it's impossible to write a non-constant expression outside of
16879   // function context, so we'll get other (more useful) diagnostics later.
16880   //
16881   // For C++, things get a bit more nasty... it would be nice to suppress this
16882   // diagnostic for certain cases like using a local variable in an array bound
16883   // for a member of a local class, but the correct predicate is not obvious.
16884   if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
16885     return;
16886 
16887   unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
16888   unsigned ContextKind = 3; // unknown
16889   if (isa<CXXMethodDecl>(VarDC) &&
16890       cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
16891     ContextKind = 2;
16892   } else if (isa<FunctionDecl>(VarDC)) {
16893     ContextKind = 0;
16894   } else if (isa<BlockDecl>(VarDC)) {
16895     ContextKind = 1;
16896   }
16897 
16898   S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
16899     << var << ValueKind << ContextKind << VarDC;
16900   S.Diag(var->getLocation(), diag::note_entity_declared_at)
16901       << var;
16902 
16903   // FIXME: Add additional diagnostic info about class etc. which prevents
16904   // capture.
16905 }
16906 
16907 
16908 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
16909                                       bool &SubCapturesAreNested,
16910                                       QualType &CaptureType,
16911                                       QualType &DeclRefType) {
16912    // Check whether we've already captured it.
16913   if (CSI->CaptureMap.count(Var)) {
16914     // If we found a capture, any subcaptures are nested.
16915     SubCapturesAreNested = true;
16916 
16917     // Retrieve the capture type for this variable.
16918     CaptureType = CSI->getCapture(Var).getCaptureType();
16919 
16920     // Compute the type of an expression that refers to this variable.
16921     DeclRefType = CaptureType.getNonReferenceType();
16922 
16923     // Similarly to mutable captures in lambda, all the OpenMP captures by copy
16924     // are mutable in the sense that user can change their value - they are
16925     // private instances of the captured declarations.
16926     const Capture &Cap = CSI->getCapture(Var);
16927     if (Cap.isCopyCapture() &&
16928         !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
16929         !(isa<CapturedRegionScopeInfo>(CSI) &&
16930           cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
16931       DeclRefType.addConst();
16932     return true;
16933   }
16934   return false;
16935 }
16936 
16937 // Only block literals, captured statements, and lambda expressions can
16938 // capture; other scopes don't work.
16939 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
16940                                  SourceLocation Loc,
16941                                  const bool Diagnose, Sema &S) {
16942   if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
16943     return getLambdaAwareParentOfDeclContext(DC);
16944   else if (Var->hasLocalStorage()) {
16945     if (Diagnose)
16946        diagnoseUncapturableValueReference(S, Loc, Var, DC);
16947   }
16948   return nullptr;
16949 }
16950 
16951 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
16952 // certain types of variables (unnamed, variably modified types etc.)
16953 // so check for eligibility.
16954 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
16955                                  SourceLocation Loc,
16956                                  const bool Diagnose, Sema &S) {
16957 
16958   bool IsBlock = isa<BlockScopeInfo>(CSI);
16959   bool IsLambda = isa<LambdaScopeInfo>(CSI);
16960 
16961   // Lambdas are not allowed to capture unnamed variables
16962   // (e.g. anonymous unions).
16963   // FIXME: The C++11 rule don't actually state this explicitly, but I'm
16964   // assuming that's the intent.
16965   if (IsLambda && !Var->getDeclName()) {
16966     if (Diagnose) {
16967       S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
16968       S.Diag(Var->getLocation(), diag::note_declared_at);
16969     }
16970     return false;
16971   }
16972 
16973   // Prohibit variably-modified types in blocks; they're difficult to deal with.
16974   if (Var->getType()->isVariablyModifiedType() && IsBlock) {
16975     if (Diagnose) {
16976       S.Diag(Loc, diag::err_ref_vm_type);
16977       S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
16978     }
16979     return false;
16980   }
16981   // Prohibit structs with flexible array members too.
16982   // We cannot capture what is in the tail end of the struct.
16983   if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
16984     if (VTTy->getDecl()->hasFlexibleArrayMember()) {
16985       if (Diagnose) {
16986         if (IsBlock)
16987           S.Diag(Loc, diag::err_ref_flexarray_type);
16988         else
16989           S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var;
16990         S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
16991       }
16992       return false;
16993     }
16994   }
16995   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
16996   // Lambdas and captured statements are not allowed to capture __block
16997   // variables; they don't support the expected semantics.
16998   if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
16999     if (Diagnose) {
17000       S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda;
17001       S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17002     }
17003     return false;
17004   }
17005   // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
17006   if (S.getLangOpts().OpenCL && IsBlock &&
17007       Var->getType()->isBlockPointerType()) {
17008     if (Diagnose)
17009       S.Diag(Loc, diag::err_opencl_block_ref_block);
17010     return false;
17011   }
17012 
17013   return true;
17014 }
17015 
17016 // Returns true if the capture by block was successful.
17017 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
17018                                  SourceLocation Loc,
17019                                  const bool BuildAndDiagnose,
17020                                  QualType &CaptureType,
17021                                  QualType &DeclRefType,
17022                                  const bool Nested,
17023                                  Sema &S, bool Invalid) {
17024   bool ByRef = false;
17025 
17026   // Blocks are not allowed to capture arrays, excepting OpenCL.
17027   // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
17028   // (decayed to pointers).
17029   if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
17030     if (BuildAndDiagnose) {
17031       S.Diag(Loc, diag::err_ref_array_type);
17032       S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17033       Invalid = true;
17034     } else {
17035       return false;
17036     }
17037   }
17038 
17039   // Forbid the block-capture of autoreleasing variables.
17040   if (!Invalid &&
17041       CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
17042     if (BuildAndDiagnose) {
17043       S.Diag(Loc, diag::err_arc_autoreleasing_capture)
17044         << /*block*/ 0;
17045       S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17046       Invalid = true;
17047     } else {
17048       return false;
17049     }
17050   }
17051 
17052   // Warn about implicitly autoreleasing indirect parameters captured by blocks.
17053   if (const auto *PT = CaptureType->getAs<PointerType>()) {
17054     QualType PointeeTy = PT->getPointeeType();
17055 
17056     if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() &&
17057         PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
17058         !S.Context.hasDirectOwnershipQualifier(PointeeTy)) {
17059       if (BuildAndDiagnose) {
17060         SourceLocation VarLoc = Var->getLocation();
17061         S.Diag(Loc, diag::warn_block_capture_autoreleasing);
17062         S.Diag(VarLoc, diag::note_declare_parameter_strong);
17063       }
17064     }
17065   }
17066 
17067   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
17068   if (HasBlocksAttr || CaptureType->isReferenceType() ||
17069       (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) {
17070     // Block capture by reference does not change the capture or
17071     // declaration reference types.
17072     ByRef = true;
17073   } else {
17074     // Block capture by copy introduces 'const'.
17075     CaptureType = CaptureType.getNonReferenceType().withConst();
17076     DeclRefType = CaptureType;
17077   }
17078 
17079   // Actually capture the variable.
17080   if (BuildAndDiagnose)
17081     BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(),
17082                     CaptureType, Invalid);
17083 
17084   return !Invalid;
17085 }
17086 
17087 
17088 /// Capture the given variable in the captured region.
17089 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
17090                                     VarDecl *Var,
17091                                     SourceLocation Loc,
17092                                     const bool BuildAndDiagnose,
17093                                     QualType &CaptureType,
17094                                     QualType &DeclRefType,
17095                                     const bool RefersToCapturedVariable,
17096                                     Sema &S, bool Invalid) {
17097   // By default, capture variables by reference.
17098   bool ByRef = true;
17099   // Using an LValue reference type is consistent with Lambdas (see below).
17100   if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
17101     if (S.isOpenMPCapturedDecl(Var)) {
17102       bool HasConst = DeclRefType.isConstQualified();
17103       DeclRefType = DeclRefType.getUnqualifiedType();
17104       // Don't lose diagnostics about assignments to const.
17105       if (HasConst)
17106         DeclRefType.addConst();
17107     }
17108     // Do not capture firstprivates in tasks.
17109     if (S.isOpenMPPrivateDecl(Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel) !=
17110         OMPC_unknown)
17111       return true;
17112     ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel,
17113                                     RSI->OpenMPCaptureLevel);
17114   }
17115 
17116   if (ByRef)
17117     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
17118   else
17119     CaptureType = DeclRefType;
17120 
17121   // Actually capture the variable.
17122   if (BuildAndDiagnose)
17123     RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable,
17124                     Loc, SourceLocation(), CaptureType, Invalid);
17125 
17126   return !Invalid;
17127 }
17128 
17129 /// Capture the given variable in the lambda.
17130 static bool captureInLambda(LambdaScopeInfo *LSI,
17131                             VarDecl *Var,
17132                             SourceLocation Loc,
17133                             const bool BuildAndDiagnose,
17134                             QualType &CaptureType,
17135                             QualType &DeclRefType,
17136                             const bool RefersToCapturedVariable,
17137                             const Sema::TryCaptureKind Kind,
17138                             SourceLocation EllipsisLoc,
17139                             const bool IsTopScope,
17140                             Sema &S, bool Invalid) {
17141   // Determine whether we are capturing by reference or by value.
17142   bool ByRef = false;
17143   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
17144     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
17145   } else {
17146     ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
17147   }
17148 
17149   // Compute the type of the field that will capture this variable.
17150   if (ByRef) {
17151     // C++11 [expr.prim.lambda]p15:
17152     //   An entity is captured by reference if it is implicitly or
17153     //   explicitly captured but not captured by copy. It is
17154     //   unspecified whether additional unnamed non-static data
17155     //   members are declared in the closure type for entities
17156     //   captured by reference.
17157     //
17158     // FIXME: It is not clear whether we want to build an lvalue reference
17159     // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
17160     // to do the former, while EDG does the latter. Core issue 1249 will
17161     // clarify, but for now we follow GCC because it's a more permissive and
17162     // easily defensible position.
17163     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
17164   } else {
17165     // C++11 [expr.prim.lambda]p14:
17166     //   For each entity captured by copy, an unnamed non-static
17167     //   data member is declared in the closure type. The
17168     //   declaration order of these members is unspecified. The type
17169     //   of such a data member is the type of the corresponding
17170     //   captured entity if the entity is not a reference to an
17171     //   object, or the referenced type otherwise. [Note: If the
17172     //   captured entity is a reference to a function, the
17173     //   corresponding data member is also a reference to a
17174     //   function. - end note ]
17175     if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
17176       if (!RefType->getPointeeType()->isFunctionType())
17177         CaptureType = RefType->getPointeeType();
17178     }
17179 
17180     // Forbid the lambda copy-capture of autoreleasing variables.
17181     if (!Invalid &&
17182         CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
17183       if (BuildAndDiagnose) {
17184         S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
17185         S.Diag(Var->getLocation(), diag::note_previous_decl)
17186           << Var->getDeclName();
17187         Invalid = true;
17188       } else {
17189         return false;
17190       }
17191     }
17192 
17193     // Make sure that by-copy captures are of a complete and non-abstract type.
17194     if (!Invalid && BuildAndDiagnose) {
17195       if (!CaptureType->isDependentType() &&
17196           S.RequireCompleteSizedType(
17197               Loc, CaptureType,
17198               diag::err_capture_of_incomplete_or_sizeless_type,
17199               Var->getDeclName()))
17200         Invalid = true;
17201       else if (S.RequireNonAbstractType(Loc, CaptureType,
17202                                         diag::err_capture_of_abstract_type))
17203         Invalid = true;
17204     }
17205   }
17206 
17207   // Compute the type of a reference to this captured variable.
17208   if (ByRef)
17209     DeclRefType = CaptureType.getNonReferenceType();
17210   else {
17211     // C++ [expr.prim.lambda]p5:
17212     //   The closure type for a lambda-expression has a public inline
17213     //   function call operator [...]. This function call operator is
17214     //   declared const (9.3.1) if and only if the lambda-expression's
17215     //   parameter-declaration-clause is not followed by mutable.
17216     DeclRefType = CaptureType.getNonReferenceType();
17217     if (!LSI->Mutable && !CaptureType->isReferenceType())
17218       DeclRefType.addConst();
17219   }
17220 
17221   // Add the capture.
17222   if (BuildAndDiagnose)
17223     LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable,
17224                     Loc, EllipsisLoc, CaptureType, Invalid);
17225 
17226   return !Invalid;
17227 }
17228 
17229 bool Sema::tryCaptureVariable(
17230     VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
17231     SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
17232     QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
17233   // An init-capture is notionally from the context surrounding its
17234   // declaration, but its parent DC is the lambda class.
17235   DeclContext *VarDC = Var->getDeclContext();
17236   if (Var->isInitCapture())
17237     VarDC = VarDC->getParent();
17238 
17239   DeclContext *DC = CurContext;
17240   const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
17241       ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
17242   // We need to sync up the Declaration Context with the
17243   // FunctionScopeIndexToStopAt
17244   if (FunctionScopeIndexToStopAt) {
17245     unsigned FSIndex = FunctionScopes.size() - 1;
17246     while (FSIndex != MaxFunctionScopesIndex) {
17247       DC = getLambdaAwareParentOfDeclContext(DC);
17248       --FSIndex;
17249     }
17250   }
17251 
17252 
17253   // If the variable is declared in the current context, there is no need to
17254   // capture it.
17255   if (VarDC == DC) return true;
17256 
17257   // Capture global variables if it is required to use private copy of this
17258   // variable.
17259   bool IsGlobal = !Var->hasLocalStorage();
17260   if (IsGlobal &&
17261       !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true,
17262                                                 MaxFunctionScopesIndex)))
17263     return true;
17264   Var = Var->getCanonicalDecl();
17265 
17266   // Walk up the stack to determine whether we can capture the variable,
17267   // performing the "simple" checks that don't depend on type. We stop when
17268   // we've either hit the declared scope of the variable or find an existing
17269   // capture of that variable.  We start from the innermost capturing-entity
17270   // (the DC) and ensure that all intervening capturing-entities
17271   // (blocks/lambdas etc.) between the innermost capturer and the variable`s
17272   // declcontext can either capture the variable or have already captured
17273   // the variable.
17274   CaptureType = Var->getType();
17275   DeclRefType = CaptureType.getNonReferenceType();
17276   bool Nested = false;
17277   bool Explicit = (Kind != TryCapture_Implicit);
17278   unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
17279   do {
17280     // Only block literals, captured statements, and lambda expressions can
17281     // capture; other scopes don't work.
17282     DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
17283                                                               ExprLoc,
17284                                                               BuildAndDiagnose,
17285                                                               *this);
17286     // We need to check for the parent *first* because, if we *have*
17287     // private-captured a global variable, we need to recursively capture it in
17288     // intermediate blocks, lambdas, etc.
17289     if (!ParentDC) {
17290       if (IsGlobal) {
17291         FunctionScopesIndex = MaxFunctionScopesIndex - 1;
17292         break;
17293       }
17294       return true;
17295     }
17296 
17297     FunctionScopeInfo  *FSI = FunctionScopes[FunctionScopesIndex];
17298     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
17299 
17300 
17301     // Check whether we've already captured it.
17302     if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
17303                                              DeclRefType)) {
17304       CSI->getCapture(Var).markUsed(BuildAndDiagnose);
17305       break;
17306     }
17307     // If we are instantiating a generic lambda call operator body,
17308     // we do not want to capture new variables.  What was captured
17309     // during either a lambdas transformation or initial parsing
17310     // should be used.
17311     if (isGenericLambdaCallOperatorSpecialization(DC)) {
17312       if (BuildAndDiagnose) {
17313         LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
17314         if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
17315           Diag(ExprLoc, diag::err_lambda_impcap) << Var;
17316           Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17317           Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
17318         } else
17319           diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
17320       }
17321       return true;
17322     }
17323 
17324     // Try to capture variable-length arrays types.
17325     if (Var->getType()->isVariablyModifiedType()) {
17326       // We're going to walk down into the type and look for VLA
17327       // expressions.
17328       QualType QTy = Var->getType();
17329       if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
17330         QTy = PVD->getOriginalType();
17331       captureVariablyModifiedType(Context, QTy, CSI);
17332     }
17333 
17334     if (getLangOpts().OpenMP) {
17335       if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
17336         // OpenMP private variables should not be captured in outer scope, so
17337         // just break here. Similarly, global variables that are captured in a
17338         // target region should not be captured outside the scope of the region.
17339         if (RSI->CapRegionKind == CR_OpenMP) {
17340           OpenMPClauseKind IsOpenMPPrivateDecl = isOpenMPPrivateDecl(
17341               Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel);
17342           // If the variable is private (i.e. not captured) and has variably
17343           // modified type, we still need to capture the type for correct
17344           // codegen in all regions, associated with the construct. Currently,
17345           // it is captured in the innermost captured region only.
17346           if (IsOpenMPPrivateDecl != OMPC_unknown &&
17347               Var->getType()->isVariablyModifiedType()) {
17348             QualType QTy = Var->getType();
17349             if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
17350               QTy = PVD->getOriginalType();
17351             for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel);
17352                  I < E; ++I) {
17353               auto *OuterRSI = cast<CapturedRegionScopeInfo>(
17354                   FunctionScopes[FunctionScopesIndex - I]);
17355               assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel &&
17356                      "Wrong number of captured regions associated with the "
17357                      "OpenMP construct.");
17358               captureVariablyModifiedType(Context, QTy, OuterRSI);
17359             }
17360           }
17361           bool IsTargetCap =
17362               IsOpenMPPrivateDecl != OMPC_private &&
17363               isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel,
17364                                          RSI->OpenMPCaptureLevel);
17365           // Do not capture global if it is not privatized in outer regions.
17366           bool IsGlobalCap =
17367               IsGlobal && isOpenMPGlobalCapturedDecl(Var, RSI->OpenMPLevel,
17368                                                      RSI->OpenMPCaptureLevel);
17369 
17370           // When we detect target captures we are looking from inside the
17371           // target region, therefore we need to propagate the capture from the
17372           // enclosing region. Therefore, the capture is not initially nested.
17373           if (IsTargetCap)
17374             adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel);
17375 
17376           if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private ||
17377               (IsGlobal && !IsGlobalCap)) {
17378             Nested = !IsTargetCap;
17379             DeclRefType = DeclRefType.getUnqualifiedType();
17380             CaptureType = Context.getLValueReferenceType(DeclRefType);
17381             break;
17382           }
17383         }
17384       }
17385     }
17386     if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
17387       // No capture-default, and this is not an explicit capture
17388       // so cannot capture this variable.
17389       if (BuildAndDiagnose) {
17390         Diag(ExprLoc, diag::err_lambda_impcap) << Var;
17391         Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17392         if (cast<LambdaScopeInfo>(CSI)->Lambda)
17393           Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getBeginLoc(),
17394                diag::note_lambda_decl);
17395         // FIXME: If we error out because an outer lambda can not implicitly
17396         // capture a variable that an inner lambda explicitly captures, we
17397         // should have the inner lambda do the explicit capture - because
17398         // it makes for cleaner diagnostics later.  This would purely be done
17399         // so that the diagnostic does not misleadingly claim that a variable
17400         // can not be captured by a lambda implicitly even though it is captured
17401         // explicitly.  Suggestion:
17402         //  - create const bool VariableCaptureWasInitiallyExplicit = Explicit
17403         //    at the function head
17404         //  - cache the StartingDeclContext - this must be a lambda
17405         //  - captureInLambda in the innermost lambda the variable.
17406       }
17407       return true;
17408     }
17409 
17410     FunctionScopesIndex--;
17411     DC = ParentDC;
17412     Explicit = false;
17413   } while (!VarDC->Equals(DC));
17414 
17415   // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
17416   // computing the type of the capture at each step, checking type-specific
17417   // requirements, and adding captures if requested.
17418   // If the variable had already been captured previously, we start capturing
17419   // at the lambda nested within that one.
17420   bool Invalid = false;
17421   for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
17422        ++I) {
17423     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
17424 
17425     // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
17426     // certain types of variables (unnamed, variably modified types etc.)
17427     // so check for eligibility.
17428     if (!Invalid)
17429       Invalid =
17430           !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this);
17431 
17432     // After encountering an error, if we're actually supposed to capture, keep
17433     // capturing in nested contexts to suppress any follow-on diagnostics.
17434     if (Invalid && !BuildAndDiagnose)
17435       return true;
17436 
17437     if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
17438       Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
17439                                DeclRefType, Nested, *this, Invalid);
17440       Nested = true;
17441     } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
17442       Invalid = !captureInCapturedRegion(RSI, Var, ExprLoc, BuildAndDiagnose,
17443                                          CaptureType, DeclRefType, Nested,
17444                                          *this, Invalid);
17445       Nested = true;
17446     } else {
17447       LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
17448       Invalid =
17449           !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
17450                            DeclRefType, Nested, Kind, EllipsisLoc,
17451                            /*IsTopScope*/ I == N - 1, *this, Invalid);
17452       Nested = true;
17453     }
17454 
17455     if (Invalid && !BuildAndDiagnose)
17456       return true;
17457   }
17458   return Invalid;
17459 }
17460 
17461 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
17462                               TryCaptureKind Kind, SourceLocation EllipsisLoc) {
17463   QualType CaptureType;
17464   QualType DeclRefType;
17465   return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
17466                             /*BuildAndDiagnose=*/true, CaptureType,
17467                             DeclRefType, nullptr);
17468 }
17469 
17470 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
17471   QualType CaptureType;
17472   QualType DeclRefType;
17473   return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
17474                              /*BuildAndDiagnose=*/false, CaptureType,
17475                              DeclRefType, nullptr);
17476 }
17477 
17478 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
17479   QualType CaptureType;
17480   QualType DeclRefType;
17481 
17482   // Determine whether we can capture this variable.
17483   if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
17484                          /*BuildAndDiagnose=*/false, CaptureType,
17485                          DeclRefType, nullptr))
17486     return QualType();
17487 
17488   return DeclRefType;
17489 }
17490 
17491 namespace {
17492 // Helper to copy the template arguments from a DeclRefExpr or MemberExpr.
17493 // The produced TemplateArgumentListInfo* points to data stored within this
17494 // object, so should only be used in contexts where the pointer will not be
17495 // used after the CopiedTemplateArgs object is destroyed.
17496 class CopiedTemplateArgs {
17497   bool HasArgs;
17498   TemplateArgumentListInfo TemplateArgStorage;
17499 public:
17500   template<typename RefExpr>
17501   CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) {
17502     if (HasArgs)
17503       E->copyTemplateArgumentsInto(TemplateArgStorage);
17504   }
17505   operator TemplateArgumentListInfo*()
17506 #ifdef __has_cpp_attribute
17507 #if __has_cpp_attribute(clang::lifetimebound)
17508   [[clang::lifetimebound]]
17509 #endif
17510 #endif
17511   {
17512     return HasArgs ? &TemplateArgStorage : nullptr;
17513   }
17514 };
17515 }
17516 
17517 /// Walk the set of potential results of an expression and mark them all as
17518 /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason.
17519 ///
17520 /// \return A new expression if we found any potential results, ExprEmpty() if
17521 ///         not, and ExprError() if we diagnosed an error.
17522 static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E,
17523                                                       NonOdrUseReason NOUR) {
17524   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
17525   // an object that satisfies the requirements for appearing in a
17526   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
17527   // is immediately applied."  This function handles the lvalue-to-rvalue
17528   // conversion part.
17529   //
17530   // If we encounter a node that claims to be an odr-use but shouldn't be, we
17531   // transform it into the relevant kind of non-odr-use node and rebuild the
17532   // tree of nodes leading to it.
17533   //
17534   // This is a mini-TreeTransform that only transforms a restricted subset of
17535   // nodes (and only certain operands of them).
17536 
17537   // Rebuild a subexpression.
17538   auto Rebuild = [&](Expr *Sub) {
17539     return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR);
17540   };
17541 
17542   // Check whether a potential result satisfies the requirements of NOUR.
17543   auto IsPotentialResultOdrUsed = [&](NamedDecl *D) {
17544     // Any entity other than a VarDecl is always odr-used whenever it's named
17545     // in a potentially-evaluated expression.
17546     auto *VD = dyn_cast<VarDecl>(D);
17547     if (!VD)
17548       return true;
17549 
17550     // C++2a [basic.def.odr]p4:
17551     //   A variable x whose name appears as a potentially-evalauted expression
17552     //   e is odr-used by e unless
17553     //   -- x is a reference that is usable in constant expressions, or
17554     //   -- x is a variable of non-reference type that is usable in constant
17555     //      expressions and has no mutable subobjects, and e is an element of
17556     //      the set of potential results of an expression of
17557     //      non-volatile-qualified non-class type to which the lvalue-to-rvalue
17558     //      conversion is applied, or
17559     //   -- x is a variable of non-reference type, and e is an element of the
17560     //      set of potential results of a discarded-value expression to which
17561     //      the lvalue-to-rvalue conversion is not applied
17562     //
17563     // We check the first bullet and the "potentially-evaluated" condition in
17564     // BuildDeclRefExpr. We check the type requirements in the second bullet
17565     // in CheckLValueToRValueConversionOperand below.
17566     switch (NOUR) {
17567     case NOUR_None:
17568     case NOUR_Unevaluated:
17569       llvm_unreachable("unexpected non-odr-use-reason");
17570 
17571     case NOUR_Constant:
17572       // Constant references were handled when they were built.
17573       if (VD->getType()->isReferenceType())
17574         return true;
17575       if (auto *RD = VD->getType()->getAsCXXRecordDecl())
17576         if (RD->hasMutableFields())
17577           return true;
17578       if (!VD->isUsableInConstantExpressions(S.Context))
17579         return true;
17580       break;
17581 
17582     case NOUR_Discarded:
17583       if (VD->getType()->isReferenceType())
17584         return true;
17585       break;
17586     }
17587     return false;
17588   };
17589 
17590   // Mark that this expression does not constitute an odr-use.
17591   auto MarkNotOdrUsed = [&] {
17592     S.MaybeODRUseExprs.remove(E);
17593     if (LambdaScopeInfo *LSI = S.getCurLambda())
17594       LSI->markVariableExprAsNonODRUsed(E);
17595   };
17596 
17597   // C++2a [basic.def.odr]p2:
17598   //   The set of potential results of an expression e is defined as follows:
17599   switch (E->getStmtClass()) {
17600   //   -- If e is an id-expression, ...
17601   case Expr::DeclRefExprClass: {
17602     auto *DRE = cast<DeclRefExpr>(E);
17603     if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl()))
17604       break;
17605 
17606     // Rebuild as a non-odr-use DeclRefExpr.
17607     MarkNotOdrUsed();
17608     return DeclRefExpr::Create(
17609         S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(),
17610         DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(),
17611         DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(),
17612         DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR);
17613   }
17614 
17615   case Expr::FunctionParmPackExprClass: {
17616     auto *FPPE = cast<FunctionParmPackExpr>(E);
17617     // If any of the declarations in the pack is odr-used, then the expression
17618     // as a whole constitutes an odr-use.
17619     for (VarDecl *D : *FPPE)
17620       if (IsPotentialResultOdrUsed(D))
17621         return ExprEmpty();
17622 
17623     // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice,
17624     // nothing cares about whether we marked this as an odr-use, but it might
17625     // be useful for non-compiler tools.
17626     MarkNotOdrUsed();
17627     break;
17628   }
17629 
17630   //   -- If e is a subscripting operation with an array operand...
17631   case Expr::ArraySubscriptExprClass: {
17632     auto *ASE = cast<ArraySubscriptExpr>(E);
17633     Expr *OldBase = ASE->getBase()->IgnoreImplicit();
17634     if (!OldBase->getType()->isArrayType())
17635       break;
17636     ExprResult Base = Rebuild(OldBase);
17637     if (!Base.isUsable())
17638       return Base;
17639     Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS();
17640     Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS();
17641     SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored.
17642     return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS,
17643                                      ASE->getRBracketLoc());
17644   }
17645 
17646   case Expr::MemberExprClass: {
17647     auto *ME = cast<MemberExpr>(E);
17648     // -- If e is a class member access expression [...] naming a non-static
17649     //    data member...
17650     if (isa<FieldDecl>(ME->getMemberDecl())) {
17651       ExprResult Base = Rebuild(ME->getBase());
17652       if (!Base.isUsable())
17653         return Base;
17654       return MemberExpr::Create(
17655           S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(),
17656           ME->getQualifierLoc(), ME->getTemplateKeywordLoc(),
17657           ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(),
17658           CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(),
17659           ME->getObjectKind(), ME->isNonOdrUse());
17660     }
17661 
17662     if (ME->getMemberDecl()->isCXXInstanceMember())
17663       break;
17664 
17665     // -- If e is a class member access expression naming a static data member,
17666     //    ...
17667     if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl()))
17668       break;
17669 
17670     // Rebuild as a non-odr-use MemberExpr.
17671     MarkNotOdrUsed();
17672     return MemberExpr::Create(
17673         S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(),
17674         ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(),
17675         ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME),
17676         ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR);
17677     return ExprEmpty();
17678   }
17679 
17680   case Expr::BinaryOperatorClass: {
17681     auto *BO = cast<BinaryOperator>(E);
17682     Expr *LHS = BO->getLHS();
17683     Expr *RHS = BO->getRHS();
17684     // -- If e is a pointer-to-member expression of the form e1 .* e2 ...
17685     if (BO->getOpcode() == BO_PtrMemD) {
17686       ExprResult Sub = Rebuild(LHS);
17687       if (!Sub.isUsable())
17688         return Sub;
17689       LHS = Sub.get();
17690     //   -- If e is a comma expression, ...
17691     } else if (BO->getOpcode() == BO_Comma) {
17692       ExprResult Sub = Rebuild(RHS);
17693       if (!Sub.isUsable())
17694         return Sub;
17695       RHS = Sub.get();
17696     } else {
17697       break;
17698     }
17699     return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(),
17700                         LHS, RHS);
17701   }
17702 
17703   //   -- If e has the form (e1)...
17704   case Expr::ParenExprClass: {
17705     auto *PE = cast<ParenExpr>(E);
17706     ExprResult Sub = Rebuild(PE->getSubExpr());
17707     if (!Sub.isUsable())
17708       return Sub;
17709     return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get());
17710   }
17711 
17712   //   -- If e is a glvalue conditional expression, ...
17713   // We don't apply this to a binary conditional operator. FIXME: Should we?
17714   case Expr::ConditionalOperatorClass: {
17715     auto *CO = cast<ConditionalOperator>(E);
17716     ExprResult LHS = Rebuild(CO->getLHS());
17717     if (LHS.isInvalid())
17718       return ExprError();
17719     ExprResult RHS = Rebuild(CO->getRHS());
17720     if (RHS.isInvalid())
17721       return ExprError();
17722     if (!LHS.isUsable() && !RHS.isUsable())
17723       return ExprEmpty();
17724     if (!LHS.isUsable())
17725       LHS = CO->getLHS();
17726     if (!RHS.isUsable())
17727       RHS = CO->getRHS();
17728     return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(),
17729                                 CO->getCond(), LHS.get(), RHS.get());
17730   }
17731 
17732   // [Clang extension]
17733   //   -- If e has the form __extension__ e1...
17734   case Expr::UnaryOperatorClass: {
17735     auto *UO = cast<UnaryOperator>(E);
17736     if (UO->getOpcode() != UO_Extension)
17737       break;
17738     ExprResult Sub = Rebuild(UO->getSubExpr());
17739     if (!Sub.isUsable())
17740       return Sub;
17741     return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension,
17742                           Sub.get());
17743   }
17744 
17745   // [Clang extension]
17746   //   -- If e has the form _Generic(...), the set of potential results is the
17747   //      union of the sets of potential results of the associated expressions.
17748   case Expr::GenericSelectionExprClass: {
17749     auto *GSE = cast<GenericSelectionExpr>(E);
17750 
17751     SmallVector<Expr *, 4> AssocExprs;
17752     bool AnyChanged = false;
17753     for (Expr *OrigAssocExpr : GSE->getAssocExprs()) {
17754       ExprResult AssocExpr = Rebuild(OrigAssocExpr);
17755       if (AssocExpr.isInvalid())
17756         return ExprError();
17757       if (AssocExpr.isUsable()) {
17758         AssocExprs.push_back(AssocExpr.get());
17759         AnyChanged = true;
17760       } else {
17761         AssocExprs.push_back(OrigAssocExpr);
17762       }
17763     }
17764 
17765     return AnyChanged ? S.CreateGenericSelectionExpr(
17766                             GSE->getGenericLoc(), GSE->getDefaultLoc(),
17767                             GSE->getRParenLoc(), GSE->getControllingExpr(),
17768                             GSE->getAssocTypeSourceInfos(), AssocExprs)
17769                       : ExprEmpty();
17770   }
17771 
17772   // [Clang extension]
17773   //   -- If e has the form __builtin_choose_expr(...), the set of potential
17774   //      results is the union of the sets of potential results of the
17775   //      second and third subexpressions.
17776   case Expr::ChooseExprClass: {
17777     auto *CE = cast<ChooseExpr>(E);
17778 
17779     ExprResult LHS = Rebuild(CE->getLHS());
17780     if (LHS.isInvalid())
17781       return ExprError();
17782 
17783     ExprResult RHS = Rebuild(CE->getLHS());
17784     if (RHS.isInvalid())
17785       return ExprError();
17786 
17787     if (!LHS.get() && !RHS.get())
17788       return ExprEmpty();
17789     if (!LHS.isUsable())
17790       LHS = CE->getLHS();
17791     if (!RHS.isUsable())
17792       RHS = CE->getRHS();
17793 
17794     return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(),
17795                              RHS.get(), CE->getRParenLoc());
17796   }
17797 
17798   // Step through non-syntactic nodes.
17799   case Expr::ConstantExprClass: {
17800     auto *CE = cast<ConstantExpr>(E);
17801     ExprResult Sub = Rebuild(CE->getSubExpr());
17802     if (!Sub.isUsable())
17803       return Sub;
17804     return ConstantExpr::Create(S.Context, Sub.get());
17805   }
17806 
17807   // We could mostly rely on the recursive rebuilding to rebuild implicit
17808   // casts, but not at the top level, so rebuild them here.
17809   case Expr::ImplicitCastExprClass: {
17810     auto *ICE = cast<ImplicitCastExpr>(E);
17811     // Only step through the narrow set of cast kinds we expect to encounter.
17812     // Anything else suggests we've left the region in which potential results
17813     // can be found.
17814     switch (ICE->getCastKind()) {
17815     case CK_NoOp:
17816     case CK_DerivedToBase:
17817     case CK_UncheckedDerivedToBase: {
17818       ExprResult Sub = Rebuild(ICE->getSubExpr());
17819       if (!Sub.isUsable())
17820         return Sub;
17821       CXXCastPath Path(ICE->path());
17822       return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(),
17823                                  ICE->getValueKind(), &Path);
17824     }
17825 
17826     default:
17827       break;
17828     }
17829     break;
17830   }
17831 
17832   default:
17833     break;
17834   }
17835 
17836   // Can't traverse through this node. Nothing to do.
17837   return ExprEmpty();
17838 }
17839 
17840 ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) {
17841   // Check whether the operand is or contains an object of non-trivial C union
17842   // type.
17843   if (E->getType().isVolatileQualified() &&
17844       (E->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
17845        E->getType().hasNonTrivialToPrimitiveCopyCUnion()))
17846     checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
17847                           Sema::NTCUC_LValueToRValueVolatile,
17848                           NTCUK_Destruct|NTCUK_Copy);
17849 
17850   // C++2a [basic.def.odr]p4:
17851   //   [...] an expression of non-volatile-qualified non-class type to which
17852   //   the lvalue-to-rvalue conversion is applied [...]
17853   if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>())
17854     return E;
17855 
17856   ExprResult Result =
17857       rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant);
17858   if (Result.isInvalid())
17859     return ExprError();
17860   return Result.get() ? Result : E;
17861 }
17862 
17863 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
17864   Res = CorrectDelayedTyposInExpr(Res);
17865 
17866   if (!Res.isUsable())
17867     return Res;
17868 
17869   // If a constant-expression is a reference to a variable where we delay
17870   // deciding whether it is an odr-use, just assume we will apply the
17871   // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
17872   // (a non-type template argument), we have special handling anyway.
17873   return CheckLValueToRValueConversionOperand(Res.get());
17874 }
17875 
17876 void Sema::CleanupVarDeclMarking() {
17877   // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
17878   // call.
17879   MaybeODRUseExprSet LocalMaybeODRUseExprs;
17880   std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs);
17881 
17882   for (Expr *E : LocalMaybeODRUseExprs) {
17883     if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
17884       MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()),
17885                          DRE->getLocation(), *this);
17886     } else if (auto *ME = dyn_cast<MemberExpr>(E)) {
17887       MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(),
17888                          *this);
17889     } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) {
17890       for (VarDecl *VD : *FP)
17891         MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this);
17892     } else {
17893       llvm_unreachable("Unexpected expression");
17894     }
17895   }
17896 
17897   assert(MaybeODRUseExprs.empty() &&
17898          "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?");
17899 }
17900 
17901 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
17902                                     VarDecl *Var, Expr *E) {
17903   assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||
17904           isa<FunctionParmPackExpr>(E)) &&
17905          "Invalid Expr argument to DoMarkVarDeclReferenced");
17906   Var->setReferenced();
17907 
17908   if (Var->isInvalidDecl())
17909     return;
17910 
17911   // Record a CUDA/HIP static device/constant variable if it is referenced
17912   // by host code. This is done conservatively, when the variable is referenced
17913   // in any of the following contexts:
17914   //   - a non-function context
17915   //   - a host function
17916   //   - a host device function
17917   // This also requires the reference of the static device/constant variable by
17918   // host code to be visible in the device compilation for the compiler to be
17919   // able to externalize the static device/constant variable.
17920   if (SemaRef.getASTContext().mayExternalizeStaticVar(Var)) {
17921     auto *CurContext = SemaRef.CurContext;
17922     if (!CurContext || !isa<FunctionDecl>(CurContext) ||
17923         cast<FunctionDecl>(CurContext)->hasAttr<CUDAHostAttr>() ||
17924         (!cast<FunctionDecl>(CurContext)->hasAttr<CUDADeviceAttr>() &&
17925          !cast<FunctionDecl>(CurContext)->hasAttr<CUDAGlobalAttr>()))
17926       SemaRef.getASTContext().CUDAStaticDeviceVarReferencedByHost.insert(Var);
17927   }
17928 
17929   auto *MSI = Var->getMemberSpecializationInfo();
17930   TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind()
17931                                        : Var->getTemplateSpecializationKind();
17932 
17933   OdrUseContext OdrUse = isOdrUseContext(SemaRef);
17934   bool UsableInConstantExpr =
17935       Var->mightBeUsableInConstantExpressions(SemaRef.Context);
17936 
17937   // C++20 [expr.const]p12:
17938   //   A variable [...] is needed for constant evaluation if it is [...] a
17939   //   variable whose name appears as a potentially constant evaluated
17940   //   expression that is either a contexpr variable or is of non-volatile
17941   //   const-qualified integral type or of reference type
17942   bool NeededForConstantEvaluation =
17943       isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr;
17944 
17945   bool NeedDefinition =
17946       OdrUse == OdrUseContext::Used || NeededForConstantEvaluation;
17947 
17948   assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
17949          "Can't instantiate a partial template specialization.");
17950 
17951   // If this might be a member specialization of a static data member, check
17952   // the specialization is visible. We already did the checks for variable
17953   // template specializations when we created them.
17954   if (NeedDefinition && TSK != TSK_Undeclared &&
17955       !isa<VarTemplateSpecializationDecl>(Var))
17956     SemaRef.checkSpecializationVisibility(Loc, Var);
17957 
17958   // Perform implicit instantiation of static data members, static data member
17959   // templates of class templates, and variable template specializations. Delay
17960   // instantiations of variable templates, except for those that could be used
17961   // in a constant expression.
17962   if (NeedDefinition && isTemplateInstantiation(TSK)) {
17963     // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
17964     // instantiation declaration if a variable is usable in a constant
17965     // expression (among other cases).
17966     bool TryInstantiating =
17967         TSK == TSK_ImplicitInstantiation ||
17968         (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
17969 
17970     if (TryInstantiating) {
17971       SourceLocation PointOfInstantiation =
17972           MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation();
17973       bool FirstInstantiation = PointOfInstantiation.isInvalid();
17974       if (FirstInstantiation) {
17975         PointOfInstantiation = Loc;
17976         if (MSI)
17977           MSI->setPointOfInstantiation(PointOfInstantiation);
17978         else
17979           Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
17980       }
17981 
17982       if (UsableInConstantExpr) {
17983         // Do not defer instantiations of variables that could be used in a
17984         // constant expression.
17985         SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] {
17986           SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
17987         });
17988       } else if (FirstInstantiation ||
17989                  isa<VarTemplateSpecializationDecl>(Var)) {
17990         // FIXME: For a specialization of a variable template, we don't
17991         // distinguish between "declaration and type implicitly instantiated"
17992         // and "implicit instantiation of definition requested", so we have
17993         // no direct way to avoid enqueueing the pending instantiation
17994         // multiple times.
17995         SemaRef.PendingInstantiations
17996             .push_back(std::make_pair(Var, PointOfInstantiation));
17997       }
17998     }
17999   }
18000 
18001   // C++2a [basic.def.odr]p4:
18002   //   A variable x whose name appears as a potentially-evaluated expression e
18003   //   is odr-used by e unless
18004   //   -- x is a reference that is usable in constant expressions
18005   //   -- x is a variable of non-reference type that is usable in constant
18006   //      expressions and has no mutable subobjects [FIXME], and e is an
18007   //      element of the set of potential results of an expression of
18008   //      non-volatile-qualified non-class type to which the lvalue-to-rvalue
18009   //      conversion is applied
18010   //   -- x is a variable of non-reference type, and e is an element of the set
18011   //      of potential results of a discarded-value expression to which the
18012   //      lvalue-to-rvalue conversion is not applied [FIXME]
18013   //
18014   // We check the first part of the second bullet here, and
18015   // Sema::CheckLValueToRValueConversionOperand deals with the second part.
18016   // FIXME: To get the third bullet right, we need to delay this even for
18017   // variables that are not usable in constant expressions.
18018 
18019   // If we already know this isn't an odr-use, there's nothing more to do.
18020   if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E))
18021     if (DRE->isNonOdrUse())
18022       return;
18023   if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E))
18024     if (ME->isNonOdrUse())
18025       return;
18026 
18027   switch (OdrUse) {
18028   case OdrUseContext::None:
18029     assert((!E || isa<FunctionParmPackExpr>(E)) &&
18030            "missing non-odr-use marking for unevaluated decl ref");
18031     break;
18032 
18033   case OdrUseContext::FormallyOdrUsed:
18034     // FIXME: Ignoring formal odr-uses results in incorrect lambda capture
18035     // behavior.
18036     break;
18037 
18038   case OdrUseContext::Used:
18039     // If we might later find that this expression isn't actually an odr-use,
18040     // delay the marking.
18041     if (E && Var->isUsableInConstantExpressions(SemaRef.Context))
18042       SemaRef.MaybeODRUseExprs.insert(E);
18043     else
18044       MarkVarDeclODRUsed(Var, Loc, SemaRef);
18045     break;
18046 
18047   case OdrUseContext::Dependent:
18048     // If this is a dependent context, we don't need to mark variables as
18049     // odr-used, but we may still need to track them for lambda capture.
18050     // FIXME: Do we also need to do this inside dependent typeid expressions
18051     // (which are modeled as unevaluated at this point)?
18052     const bool RefersToEnclosingScope =
18053         (SemaRef.CurContext != Var->getDeclContext() &&
18054          Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
18055     if (RefersToEnclosingScope) {
18056       LambdaScopeInfo *const LSI =
18057           SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
18058       if (LSI && (!LSI->CallOperator ||
18059                   !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
18060         // If a variable could potentially be odr-used, defer marking it so
18061         // until we finish analyzing the full expression for any
18062         // lvalue-to-rvalue
18063         // or discarded value conversions that would obviate odr-use.
18064         // Add it to the list of potential captures that will be analyzed
18065         // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
18066         // unless the variable is a reference that was initialized by a constant
18067         // expression (this will never need to be captured or odr-used).
18068         //
18069         // FIXME: We can simplify this a lot after implementing P0588R1.
18070         assert(E && "Capture variable should be used in an expression.");
18071         if (!Var->getType()->isReferenceType() ||
18072             !Var->isUsableInConstantExpressions(SemaRef.Context))
18073           LSI->addPotentialCapture(E->IgnoreParens());
18074       }
18075     }
18076     break;
18077   }
18078 }
18079 
18080 /// Mark a variable referenced, and check whether it is odr-used
18081 /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
18082 /// used directly for normal expressions referring to VarDecl.
18083 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
18084   DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
18085 }
18086 
18087 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
18088                                Decl *D, Expr *E, bool MightBeOdrUse) {
18089   if (SemaRef.isInOpenMPDeclareTargetContext())
18090     SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
18091 
18092   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
18093     DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
18094     return;
18095   }
18096 
18097   SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
18098 
18099   // If this is a call to a method via a cast, also mark the method in the
18100   // derived class used in case codegen can devirtualize the call.
18101   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
18102   if (!ME)
18103     return;
18104   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
18105   if (!MD)
18106     return;
18107   // Only attempt to devirtualize if this is truly a virtual call.
18108   bool IsVirtualCall = MD->isVirtual() &&
18109                           ME->performsVirtualDispatch(SemaRef.getLangOpts());
18110   if (!IsVirtualCall)
18111     return;
18112 
18113   // If it's possible to devirtualize the call, mark the called function
18114   // referenced.
18115   CXXMethodDecl *DM = MD->getDevirtualizedMethod(
18116       ME->getBase(), SemaRef.getLangOpts().AppleKext);
18117   if (DM)
18118     SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
18119 }
18120 
18121 /// Perform reference-marking and odr-use handling for a DeclRefExpr.
18122 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) {
18123   // TODO: update this with DR# once a defect report is filed.
18124   // C++11 defect. The address of a pure member should not be an ODR use, even
18125   // if it's a qualified reference.
18126   bool OdrUse = true;
18127   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
18128     if (Method->isVirtual() &&
18129         !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
18130       OdrUse = false;
18131 
18132   if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl()))
18133     if (!isConstantEvaluated() && FD->isConsteval() &&
18134         !RebuildingImmediateInvocation)
18135       ExprEvalContexts.back().ReferenceToConsteval.insert(E);
18136   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
18137 }
18138 
18139 /// Perform reference-marking and odr-use handling for a MemberExpr.
18140 void Sema::MarkMemberReferenced(MemberExpr *E) {
18141   // C++11 [basic.def.odr]p2:
18142   //   A non-overloaded function whose name appears as a potentially-evaluated
18143   //   expression or a member of a set of candidate functions, if selected by
18144   //   overload resolution when referred to from a potentially-evaluated
18145   //   expression, is odr-used, unless it is a pure virtual function and its
18146   //   name is not explicitly qualified.
18147   bool MightBeOdrUse = true;
18148   if (E->performsVirtualDispatch(getLangOpts())) {
18149     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
18150       if (Method->isPure())
18151         MightBeOdrUse = false;
18152   }
18153   SourceLocation Loc =
18154       E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
18155   MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse);
18156 }
18157 
18158 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr.
18159 void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) {
18160   for (VarDecl *VD : *E)
18161     MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true);
18162 }
18163 
18164 /// Perform marking for a reference to an arbitrary declaration.  It
18165 /// marks the declaration referenced, and performs odr-use checking for
18166 /// functions and variables. This method should not be used when building a
18167 /// normal expression which refers to a variable.
18168 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
18169                                  bool MightBeOdrUse) {
18170   if (MightBeOdrUse) {
18171     if (auto *VD = dyn_cast<VarDecl>(D)) {
18172       MarkVariableReferenced(Loc, VD);
18173       return;
18174     }
18175   }
18176   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
18177     MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
18178     return;
18179   }
18180   D->setReferenced();
18181 }
18182 
18183 namespace {
18184   // Mark all of the declarations used by a type as referenced.
18185   // FIXME: Not fully implemented yet! We need to have a better understanding
18186   // of when we're entering a context we should not recurse into.
18187   // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
18188   // TreeTransforms rebuilding the type in a new context. Rather than
18189   // duplicating the TreeTransform logic, we should consider reusing it here.
18190   // Currently that causes problems when rebuilding LambdaExprs.
18191   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
18192     Sema &S;
18193     SourceLocation Loc;
18194 
18195   public:
18196     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
18197 
18198     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
18199 
18200     bool TraverseTemplateArgument(const TemplateArgument &Arg);
18201   };
18202 }
18203 
18204 bool MarkReferencedDecls::TraverseTemplateArgument(
18205     const TemplateArgument &Arg) {
18206   {
18207     // A non-type template argument is a constant-evaluated context.
18208     EnterExpressionEvaluationContext Evaluated(
18209         S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
18210     if (Arg.getKind() == TemplateArgument::Declaration) {
18211       if (Decl *D = Arg.getAsDecl())
18212         S.MarkAnyDeclReferenced(Loc, D, true);
18213     } else if (Arg.getKind() == TemplateArgument::Expression) {
18214       S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false);
18215     }
18216   }
18217 
18218   return Inherited::TraverseTemplateArgument(Arg);
18219 }
18220 
18221 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
18222   MarkReferencedDecls Marker(*this, Loc);
18223   Marker.TraverseType(T);
18224 }
18225 
18226 namespace {
18227 /// Helper class that marks all of the declarations referenced by
18228 /// potentially-evaluated subexpressions as "referenced".
18229 class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> {
18230 public:
18231   typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited;
18232   bool SkipLocalVariables;
18233 
18234   EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
18235       : Inherited(S), SkipLocalVariables(SkipLocalVariables) {}
18236 
18237   void visitUsedDecl(SourceLocation Loc, Decl *D) {
18238     S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D));
18239   }
18240 
18241   void VisitDeclRefExpr(DeclRefExpr *E) {
18242     // If we were asked not to visit local variables, don't.
18243     if (SkipLocalVariables) {
18244       if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
18245         if (VD->hasLocalStorage())
18246           return;
18247     }
18248     S.MarkDeclRefReferenced(E);
18249   }
18250 
18251   void VisitMemberExpr(MemberExpr *E) {
18252     S.MarkMemberReferenced(E);
18253     Visit(E->getBase());
18254   }
18255 };
18256 } // namespace
18257 
18258 /// Mark any declarations that appear within this expression or any
18259 /// potentially-evaluated subexpressions as "referenced".
18260 ///
18261 /// \param SkipLocalVariables If true, don't mark local variables as
18262 /// 'referenced'.
18263 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
18264                                             bool SkipLocalVariables) {
18265   EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
18266 }
18267 
18268 /// Emit a diagnostic that describes an effect on the run-time behavior
18269 /// of the program being compiled.
18270 ///
18271 /// This routine emits the given diagnostic when the code currently being
18272 /// type-checked is "potentially evaluated", meaning that there is a
18273 /// possibility that the code will actually be executable. Code in sizeof()
18274 /// expressions, code used only during overload resolution, etc., are not
18275 /// potentially evaluated. This routine will suppress such diagnostics or,
18276 /// in the absolutely nutty case of potentially potentially evaluated
18277 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
18278 /// later.
18279 ///
18280 /// This routine should be used for all diagnostics that describe the run-time
18281 /// behavior of a program, such as passing a non-POD value through an ellipsis.
18282 /// Failure to do so will likely result in spurious diagnostics or failures
18283 /// during overload resolution or within sizeof/alignof/typeof/typeid.
18284 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts,
18285                                const PartialDiagnostic &PD) {
18286   switch (ExprEvalContexts.back().Context) {
18287   case ExpressionEvaluationContext::Unevaluated:
18288   case ExpressionEvaluationContext::UnevaluatedList:
18289   case ExpressionEvaluationContext::UnevaluatedAbstract:
18290   case ExpressionEvaluationContext::DiscardedStatement:
18291     // The argument will never be evaluated, so don't complain.
18292     break;
18293 
18294   case ExpressionEvaluationContext::ConstantEvaluated:
18295     // Relevant diagnostics should be produced by constant evaluation.
18296     break;
18297 
18298   case ExpressionEvaluationContext::PotentiallyEvaluated:
18299   case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
18300     if (!Stmts.empty() && getCurFunctionOrMethodDecl()) {
18301       FunctionScopes.back()->PossiblyUnreachableDiags.
18302         push_back(sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
18303       return true;
18304     }
18305 
18306     // The initializer of a constexpr variable or of the first declaration of a
18307     // static data member is not syntactically a constant evaluated constant,
18308     // but nonetheless is always required to be a constant expression, so we
18309     // can skip diagnosing.
18310     // FIXME: Using the mangling context here is a hack.
18311     if (auto *VD = dyn_cast_or_null<VarDecl>(
18312             ExprEvalContexts.back().ManglingContextDecl)) {
18313       if (VD->isConstexpr() ||
18314           (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline()))
18315         break;
18316       // FIXME: For any other kind of variable, we should build a CFG for its
18317       // initializer and check whether the context in question is reachable.
18318     }
18319 
18320     Diag(Loc, PD);
18321     return true;
18322   }
18323 
18324   return false;
18325 }
18326 
18327 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
18328                                const PartialDiagnostic &PD) {
18329   return DiagRuntimeBehavior(
18330       Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD);
18331 }
18332 
18333 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
18334                                CallExpr *CE, FunctionDecl *FD) {
18335   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
18336     return false;
18337 
18338   // If we're inside a decltype's expression, don't check for a valid return
18339   // type or construct temporaries until we know whether this is the last call.
18340   if (ExprEvalContexts.back().ExprContext ==
18341       ExpressionEvaluationContextRecord::EK_Decltype) {
18342     ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
18343     return false;
18344   }
18345 
18346   class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
18347     FunctionDecl *FD;
18348     CallExpr *CE;
18349 
18350   public:
18351     CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
18352       : FD(FD), CE(CE) { }
18353 
18354     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
18355       if (!FD) {
18356         S.Diag(Loc, diag::err_call_incomplete_return)
18357           << T << CE->getSourceRange();
18358         return;
18359       }
18360 
18361       S.Diag(Loc, diag::err_call_function_incomplete_return)
18362           << CE->getSourceRange() << FD << T;
18363       S.Diag(FD->getLocation(), diag::note_entity_declared_at)
18364           << FD->getDeclName();
18365     }
18366   } Diagnoser(FD, CE);
18367 
18368   if (RequireCompleteType(Loc, ReturnType, Diagnoser))
18369     return true;
18370 
18371   return false;
18372 }
18373 
18374 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
18375 // will prevent this condition from triggering, which is what we want.
18376 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
18377   SourceLocation Loc;
18378 
18379   unsigned diagnostic = diag::warn_condition_is_assignment;
18380   bool IsOrAssign = false;
18381 
18382   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
18383     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
18384       return;
18385 
18386     IsOrAssign = Op->getOpcode() == BO_OrAssign;
18387 
18388     // Greylist some idioms by putting them into a warning subcategory.
18389     if (ObjCMessageExpr *ME
18390           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
18391       Selector Sel = ME->getSelector();
18392 
18393       // self = [<foo> init...]
18394       if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
18395         diagnostic = diag::warn_condition_is_idiomatic_assignment;
18396 
18397       // <foo> = [<bar> nextObject]
18398       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
18399         diagnostic = diag::warn_condition_is_idiomatic_assignment;
18400     }
18401 
18402     Loc = Op->getOperatorLoc();
18403   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
18404     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
18405       return;
18406 
18407     IsOrAssign = Op->getOperator() == OO_PipeEqual;
18408     Loc = Op->getOperatorLoc();
18409   } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
18410     return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
18411   else {
18412     // Not an assignment.
18413     return;
18414   }
18415 
18416   Diag(Loc, diagnostic) << E->getSourceRange();
18417 
18418   SourceLocation Open = E->getBeginLoc();
18419   SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
18420   Diag(Loc, diag::note_condition_assign_silence)
18421         << FixItHint::CreateInsertion(Open, "(")
18422         << FixItHint::CreateInsertion(Close, ")");
18423 
18424   if (IsOrAssign)
18425     Diag(Loc, diag::note_condition_or_assign_to_comparison)
18426       << FixItHint::CreateReplacement(Loc, "!=");
18427   else
18428     Diag(Loc, diag::note_condition_assign_to_comparison)
18429       << FixItHint::CreateReplacement(Loc, "==");
18430 }
18431 
18432 /// Redundant parentheses over an equality comparison can indicate
18433 /// that the user intended an assignment used as condition.
18434 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
18435   // Don't warn if the parens came from a macro.
18436   SourceLocation parenLoc = ParenE->getBeginLoc();
18437   if (parenLoc.isInvalid() || parenLoc.isMacroID())
18438     return;
18439   // Don't warn for dependent expressions.
18440   if (ParenE->isTypeDependent())
18441     return;
18442 
18443   Expr *E = ParenE->IgnoreParens();
18444 
18445   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
18446     if (opE->getOpcode() == BO_EQ &&
18447         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
18448                                                            == Expr::MLV_Valid) {
18449       SourceLocation Loc = opE->getOperatorLoc();
18450 
18451       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
18452       SourceRange ParenERange = ParenE->getSourceRange();
18453       Diag(Loc, diag::note_equality_comparison_silence)
18454         << FixItHint::CreateRemoval(ParenERange.getBegin())
18455         << FixItHint::CreateRemoval(ParenERange.getEnd());
18456       Diag(Loc, diag::note_equality_comparison_to_assign)
18457         << FixItHint::CreateReplacement(Loc, "=");
18458     }
18459 }
18460 
18461 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
18462                                        bool IsConstexpr) {
18463   DiagnoseAssignmentAsCondition(E);
18464   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
18465     DiagnoseEqualityWithExtraParens(parenE);
18466 
18467   ExprResult result = CheckPlaceholderExpr(E);
18468   if (result.isInvalid()) return ExprError();
18469   E = result.get();
18470 
18471   if (!E->isTypeDependent()) {
18472     if (getLangOpts().CPlusPlus)
18473       return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
18474 
18475     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
18476     if (ERes.isInvalid())
18477       return ExprError();
18478     E = ERes.get();
18479 
18480     QualType T = E->getType();
18481     if (!T->isScalarType()) { // C99 6.8.4.1p1
18482       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
18483         << T << E->getSourceRange();
18484       return ExprError();
18485     }
18486     CheckBoolLikeConversion(E, Loc);
18487   }
18488 
18489   return E;
18490 }
18491 
18492 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
18493                                            Expr *SubExpr, ConditionKind CK) {
18494   // Empty conditions are valid in for-statements.
18495   if (!SubExpr)
18496     return ConditionResult();
18497 
18498   ExprResult Cond;
18499   switch (CK) {
18500   case ConditionKind::Boolean:
18501     Cond = CheckBooleanCondition(Loc, SubExpr);
18502     break;
18503 
18504   case ConditionKind::ConstexprIf:
18505     Cond = CheckBooleanCondition(Loc, SubExpr, true);
18506     break;
18507 
18508   case ConditionKind::Switch:
18509     Cond = CheckSwitchCondition(Loc, SubExpr);
18510     break;
18511   }
18512   if (Cond.isInvalid()) {
18513     Cond = CreateRecoveryExpr(SubExpr->getBeginLoc(), SubExpr->getEndLoc(),
18514                               {SubExpr});
18515     if (!Cond.get())
18516       return ConditionError();
18517   }
18518   // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
18519   FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
18520   if (!FullExpr.get())
18521     return ConditionError();
18522 
18523   return ConditionResult(*this, nullptr, FullExpr,
18524                          CK == ConditionKind::ConstexprIf);
18525 }
18526 
18527 namespace {
18528   /// A visitor for rebuilding a call to an __unknown_any expression
18529   /// to have an appropriate type.
18530   struct RebuildUnknownAnyFunction
18531     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
18532 
18533     Sema &S;
18534 
18535     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
18536 
18537     ExprResult VisitStmt(Stmt *S) {
18538       llvm_unreachable("unexpected statement!");
18539     }
18540 
18541     ExprResult VisitExpr(Expr *E) {
18542       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
18543         << E->getSourceRange();
18544       return ExprError();
18545     }
18546 
18547     /// Rebuild an expression which simply semantically wraps another
18548     /// expression which it shares the type and value kind of.
18549     template <class T> ExprResult rebuildSugarExpr(T *E) {
18550       ExprResult SubResult = Visit(E->getSubExpr());
18551       if (SubResult.isInvalid()) return ExprError();
18552 
18553       Expr *SubExpr = SubResult.get();
18554       E->setSubExpr(SubExpr);
18555       E->setType(SubExpr->getType());
18556       E->setValueKind(SubExpr->getValueKind());
18557       assert(E->getObjectKind() == OK_Ordinary);
18558       return E;
18559     }
18560 
18561     ExprResult VisitParenExpr(ParenExpr *E) {
18562       return rebuildSugarExpr(E);
18563     }
18564 
18565     ExprResult VisitUnaryExtension(UnaryOperator *E) {
18566       return rebuildSugarExpr(E);
18567     }
18568 
18569     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
18570       ExprResult SubResult = Visit(E->getSubExpr());
18571       if (SubResult.isInvalid()) return ExprError();
18572 
18573       Expr *SubExpr = SubResult.get();
18574       E->setSubExpr(SubExpr);
18575       E->setType(S.Context.getPointerType(SubExpr->getType()));
18576       assert(E->getValueKind() == VK_RValue);
18577       assert(E->getObjectKind() == OK_Ordinary);
18578       return E;
18579     }
18580 
18581     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
18582       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
18583 
18584       E->setType(VD->getType());
18585 
18586       assert(E->getValueKind() == VK_RValue);
18587       if (S.getLangOpts().CPlusPlus &&
18588           !(isa<CXXMethodDecl>(VD) &&
18589             cast<CXXMethodDecl>(VD)->isInstance()))
18590         E->setValueKind(VK_LValue);
18591 
18592       return E;
18593     }
18594 
18595     ExprResult VisitMemberExpr(MemberExpr *E) {
18596       return resolveDecl(E, E->getMemberDecl());
18597     }
18598 
18599     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
18600       return resolveDecl(E, E->getDecl());
18601     }
18602   };
18603 }
18604 
18605 /// Given a function expression of unknown-any type, try to rebuild it
18606 /// to have a function type.
18607 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
18608   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
18609   if (Result.isInvalid()) return ExprError();
18610   return S.DefaultFunctionArrayConversion(Result.get());
18611 }
18612 
18613 namespace {
18614   /// A visitor for rebuilding an expression of type __unknown_anytype
18615   /// into one which resolves the type directly on the referring
18616   /// expression.  Strict preservation of the original source
18617   /// structure is not a goal.
18618   struct RebuildUnknownAnyExpr
18619     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
18620 
18621     Sema &S;
18622 
18623     /// The current destination type.
18624     QualType DestType;
18625 
18626     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
18627       : S(S), DestType(CastType) {}
18628 
18629     ExprResult VisitStmt(Stmt *S) {
18630       llvm_unreachable("unexpected statement!");
18631     }
18632 
18633     ExprResult VisitExpr(Expr *E) {
18634       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
18635         << E->getSourceRange();
18636       return ExprError();
18637     }
18638 
18639     ExprResult VisitCallExpr(CallExpr *E);
18640     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
18641 
18642     /// Rebuild an expression which simply semantically wraps another
18643     /// expression which it shares the type and value kind of.
18644     template <class T> ExprResult rebuildSugarExpr(T *E) {
18645       ExprResult SubResult = Visit(E->getSubExpr());
18646       if (SubResult.isInvalid()) return ExprError();
18647       Expr *SubExpr = SubResult.get();
18648       E->setSubExpr(SubExpr);
18649       E->setType(SubExpr->getType());
18650       E->setValueKind(SubExpr->getValueKind());
18651       assert(E->getObjectKind() == OK_Ordinary);
18652       return E;
18653     }
18654 
18655     ExprResult VisitParenExpr(ParenExpr *E) {
18656       return rebuildSugarExpr(E);
18657     }
18658 
18659     ExprResult VisitUnaryExtension(UnaryOperator *E) {
18660       return rebuildSugarExpr(E);
18661     }
18662 
18663     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
18664       const PointerType *Ptr = DestType->getAs<PointerType>();
18665       if (!Ptr) {
18666         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
18667           << E->getSourceRange();
18668         return ExprError();
18669       }
18670 
18671       if (isa<CallExpr>(E->getSubExpr())) {
18672         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
18673           << E->getSourceRange();
18674         return ExprError();
18675       }
18676 
18677       assert(E->getValueKind() == VK_RValue);
18678       assert(E->getObjectKind() == OK_Ordinary);
18679       E->setType(DestType);
18680 
18681       // Build the sub-expression as if it were an object of the pointee type.
18682       DestType = Ptr->getPointeeType();
18683       ExprResult SubResult = Visit(E->getSubExpr());
18684       if (SubResult.isInvalid()) return ExprError();
18685       E->setSubExpr(SubResult.get());
18686       return E;
18687     }
18688 
18689     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
18690 
18691     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
18692 
18693     ExprResult VisitMemberExpr(MemberExpr *E) {
18694       return resolveDecl(E, E->getMemberDecl());
18695     }
18696 
18697     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
18698       return resolveDecl(E, E->getDecl());
18699     }
18700   };
18701 }
18702 
18703 /// Rebuilds a call expression which yielded __unknown_anytype.
18704 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
18705   Expr *CalleeExpr = E->getCallee();
18706 
18707   enum FnKind {
18708     FK_MemberFunction,
18709     FK_FunctionPointer,
18710     FK_BlockPointer
18711   };
18712 
18713   FnKind Kind;
18714   QualType CalleeType = CalleeExpr->getType();
18715   if (CalleeType == S.Context.BoundMemberTy) {
18716     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
18717     Kind = FK_MemberFunction;
18718     CalleeType = Expr::findBoundMemberType(CalleeExpr);
18719   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
18720     CalleeType = Ptr->getPointeeType();
18721     Kind = FK_FunctionPointer;
18722   } else {
18723     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
18724     Kind = FK_BlockPointer;
18725   }
18726   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
18727 
18728   // Verify that this is a legal result type of a function.
18729   if (DestType->isArrayType() || DestType->isFunctionType()) {
18730     unsigned diagID = diag::err_func_returning_array_function;
18731     if (Kind == FK_BlockPointer)
18732       diagID = diag::err_block_returning_array_function;
18733 
18734     S.Diag(E->getExprLoc(), diagID)
18735       << DestType->isFunctionType() << DestType;
18736     return ExprError();
18737   }
18738 
18739   // Otherwise, go ahead and set DestType as the call's result.
18740   E->setType(DestType.getNonLValueExprType(S.Context));
18741   E->setValueKind(Expr::getValueKindForType(DestType));
18742   assert(E->getObjectKind() == OK_Ordinary);
18743 
18744   // Rebuild the function type, replacing the result type with DestType.
18745   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
18746   if (Proto) {
18747     // __unknown_anytype(...) is a special case used by the debugger when
18748     // it has no idea what a function's signature is.
18749     //
18750     // We want to build this call essentially under the K&R
18751     // unprototyped rules, but making a FunctionNoProtoType in C++
18752     // would foul up all sorts of assumptions.  However, we cannot
18753     // simply pass all arguments as variadic arguments, nor can we
18754     // portably just call the function under a non-variadic type; see
18755     // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
18756     // However, it turns out that in practice it is generally safe to
18757     // call a function declared as "A foo(B,C,D);" under the prototype
18758     // "A foo(B,C,D,...);".  The only known exception is with the
18759     // Windows ABI, where any variadic function is implicitly cdecl
18760     // regardless of its normal CC.  Therefore we change the parameter
18761     // types to match the types of the arguments.
18762     //
18763     // This is a hack, but it is far superior to moving the
18764     // corresponding target-specific code from IR-gen to Sema/AST.
18765 
18766     ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
18767     SmallVector<QualType, 8> ArgTypes;
18768     if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
18769       ArgTypes.reserve(E->getNumArgs());
18770       for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
18771         Expr *Arg = E->getArg(i);
18772         QualType ArgType = Arg->getType();
18773         if (E->isLValue()) {
18774           ArgType = S.Context.getLValueReferenceType(ArgType);
18775         } else if (E->isXValue()) {
18776           ArgType = S.Context.getRValueReferenceType(ArgType);
18777         }
18778         ArgTypes.push_back(ArgType);
18779       }
18780       ParamTypes = ArgTypes;
18781     }
18782     DestType = S.Context.getFunctionType(DestType, ParamTypes,
18783                                          Proto->getExtProtoInfo());
18784   } else {
18785     DestType = S.Context.getFunctionNoProtoType(DestType,
18786                                                 FnType->getExtInfo());
18787   }
18788 
18789   // Rebuild the appropriate pointer-to-function type.
18790   switch (Kind) {
18791   case FK_MemberFunction:
18792     // Nothing to do.
18793     break;
18794 
18795   case FK_FunctionPointer:
18796     DestType = S.Context.getPointerType(DestType);
18797     break;
18798 
18799   case FK_BlockPointer:
18800     DestType = S.Context.getBlockPointerType(DestType);
18801     break;
18802   }
18803 
18804   // Finally, we can recurse.
18805   ExprResult CalleeResult = Visit(CalleeExpr);
18806   if (!CalleeResult.isUsable()) return ExprError();
18807   E->setCallee(CalleeResult.get());
18808 
18809   // Bind a temporary if necessary.
18810   return S.MaybeBindToTemporary(E);
18811 }
18812 
18813 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
18814   // Verify that this is a legal result type of a call.
18815   if (DestType->isArrayType() || DestType->isFunctionType()) {
18816     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
18817       << DestType->isFunctionType() << DestType;
18818     return ExprError();
18819   }
18820 
18821   // Rewrite the method result type if available.
18822   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
18823     assert(Method->getReturnType() == S.Context.UnknownAnyTy);
18824     Method->setReturnType(DestType);
18825   }
18826 
18827   // Change the type of the message.
18828   E->setType(DestType.getNonReferenceType());
18829   E->setValueKind(Expr::getValueKindForType(DestType));
18830 
18831   return S.MaybeBindToTemporary(E);
18832 }
18833 
18834 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
18835   // The only case we should ever see here is a function-to-pointer decay.
18836   if (E->getCastKind() == CK_FunctionToPointerDecay) {
18837     assert(E->getValueKind() == VK_RValue);
18838     assert(E->getObjectKind() == OK_Ordinary);
18839 
18840     E->setType(DestType);
18841 
18842     // Rebuild the sub-expression as the pointee (function) type.
18843     DestType = DestType->castAs<PointerType>()->getPointeeType();
18844 
18845     ExprResult Result = Visit(E->getSubExpr());
18846     if (!Result.isUsable()) return ExprError();
18847 
18848     E->setSubExpr(Result.get());
18849     return E;
18850   } else if (E->getCastKind() == CK_LValueToRValue) {
18851     assert(E->getValueKind() == VK_RValue);
18852     assert(E->getObjectKind() == OK_Ordinary);
18853 
18854     assert(isa<BlockPointerType>(E->getType()));
18855 
18856     E->setType(DestType);
18857 
18858     // The sub-expression has to be a lvalue reference, so rebuild it as such.
18859     DestType = S.Context.getLValueReferenceType(DestType);
18860 
18861     ExprResult Result = Visit(E->getSubExpr());
18862     if (!Result.isUsable()) return ExprError();
18863 
18864     E->setSubExpr(Result.get());
18865     return E;
18866   } else {
18867     llvm_unreachable("Unhandled cast type!");
18868   }
18869 }
18870 
18871 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
18872   ExprValueKind ValueKind = VK_LValue;
18873   QualType Type = DestType;
18874 
18875   // We know how to make this work for certain kinds of decls:
18876 
18877   //  - functions
18878   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
18879     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
18880       DestType = Ptr->getPointeeType();
18881       ExprResult Result = resolveDecl(E, VD);
18882       if (Result.isInvalid()) return ExprError();
18883       return S.ImpCastExprToType(Result.get(), Type,
18884                                  CK_FunctionToPointerDecay, VK_RValue);
18885     }
18886 
18887     if (!Type->isFunctionType()) {
18888       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
18889         << VD << E->getSourceRange();
18890       return ExprError();
18891     }
18892     if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
18893       // We must match the FunctionDecl's type to the hack introduced in
18894       // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
18895       // type. See the lengthy commentary in that routine.
18896       QualType FDT = FD->getType();
18897       const FunctionType *FnType = FDT->castAs<FunctionType>();
18898       const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
18899       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
18900       if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
18901         SourceLocation Loc = FD->getLocation();
18902         FunctionDecl *NewFD = FunctionDecl::Create(
18903             S.Context, FD->getDeclContext(), Loc, Loc,
18904             FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(),
18905             SC_None, false /*isInlineSpecified*/, FD->hasPrototype(),
18906             /*ConstexprKind*/ CSK_unspecified);
18907 
18908         if (FD->getQualifier())
18909           NewFD->setQualifierInfo(FD->getQualifierLoc());
18910 
18911         SmallVector<ParmVarDecl*, 16> Params;
18912         for (const auto &AI : FT->param_types()) {
18913           ParmVarDecl *Param =
18914             S.BuildParmVarDeclForTypedef(FD, Loc, AI);
18915           Param->setScopeInfo(0, Params.size());
18916           Params.push_back(Param);
18917         }
18918         NewFD->setParams(Params);
18919         DRE->setDecl(NewFD);
18920         VD = DRE->getDecl();
18921       }
18922     }
18923 
18924     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
18925       if (MD->isInstance()) {
18926         ValueKind = VK_RValue;
18927         Type = S.Context.BoundMemberTy;
18928       }
18929 
18930     // Function references aren't l-values in C.
18931     if (!S.getLangOpts().CPlusPlus)
18932       ValueKind = VK_RValue;
18933 
18934   //  - variables
18935   } else if (isa<VarDecl>(VD)) {
18936     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
18937       Type = RefTy->getPointeeType();
18938     } else if (Type->isFunctionType()) {
18939       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
18940         << VD << E->getSourceRange();
18941       return ExprError();
18942     }
18943 
18944   //  - nothing else
18945   } else {
18946     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
18947       << VD << E->getSourceRange();
18948     return ExprError();
18949   }
18950 
18951   // Modifying the declaration like this is friendly to IR-gen but
18952   // also really dangerous.
18953   VD->setType(DestType);
18954   E->setType(Type);
18955   E->setValueKind(ValueKind);
18956   return E;
18957 }
18958 
18959 /// Check a cast of an unknown-any type.  We intentionally only
18960 /// trigger this for C-style casts.
18961 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
18962                                      Expr *CastExpr, CastKind &CastKind,
18963                                      ExprValueKind &VK, CXXCastPath &Path) {
18964   // The type we're casting to must be either void or complete.
18965   if (!CastType->isVoidType() &&
18966       RequireCompleteType(TypeRange.getBegin(), CastType,
18967                           diag::err_typecheck_cast_to_incomplete))
18968     return ExprError();
18969 
18970   // Rewrite the casted expression from scratch.
18971   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
18972   if (!result.isUsable()) return ExprError();
18973 
18974   CastExpr = result.get();
18975   VK = CastExpr->getValueKind();
18976   CastKind = CK_NoOp;
18977 
18978   return CastExpr;
18979 }
18980 
18981 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
18982   return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
18983 }
18984 
18985 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
18986                                     Expr *arg, QualType &paramType) {
18987   // If the syntactic form of the argument is not an explicit cast of
18988   // any sort, just do default argument promotion.
18989   ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
18990   if (!castArg) {
18991     ExprResult result = DefaultArgumentPromotion(arg);
18992     if (result.isInvalid()) return ExprError();
18993     paramType = result.get()->getType();
18994     return result;
18995   }
18996 
18997   // Otherwise, use the type that was written in the explicit cast.
18998   assert(!arg->hasPlaceholderType());
18999   paramType = castArg->getTypeAsWritten();
19000 
19001   // Copy-initialize a parameter of that type.
19002   InitializedEntity entity =
19003     InitializedEntity::InitializeParameter(Context, paramType,
19004                                            /*consumed*/ false);
19005   return PerformCopyInitialization(entity, callLoc, arg);
19006 }
19007 
19008 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
19009   Expr *orig = E;
19010   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
19011   while (true) {
19012     E = E->IgnoreParenImpCasts();
19013     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
19014       E = call->getCallee();
19015       diagID = diag::err_uncasted_call_of_unknown_any;
19016     } else {
19017       break;
19018     }
19019   }
19020 
19021   SourceLocation loc;
19022   NamedDecl *d;
19023   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
19024     loc = ref->getLocation();
19025     d = ref->getDecl();
19026   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
19027     loc = mem->getMemberLoc();
19028     d = mem->getMemberDecl();
19029   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
19030     diagID = diag::err_uncasted_call_of_unknown_any;
19031     loc = msg->getSelectorStartLoc();
19032     d = msg->getMethodDecl();
19033     if (!d) {
19034       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
19035         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
19036         << orig->getSourceRange();
19037       return ExprError();
19038     }
19039   } else {
19040     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
19041       << E->getSourceRange();
19042     return ExprError();
19043   }
19044 
19045   S.Diag(loc, diagID) << d << orig->getSourceRange();
19046 
19047   // Never recoverable.
19048   return ExprError();
19049 }
19050 
19051 /// Check for operands with placeholder types and complain if found.
19052 /// Returns ExprError() if there was an error and no recovery was possible.
19053 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
19054   if (!getLangOpts().CPlusPlus) {
19055     // C cannot handle TypoExpr nodes on either side of a binop because it
19056     // doesn't handle dependent types properly, so make sure any TypoExprs have
19057     // been dealt with before checking the operands.
19058     ExprResult Result = CorrectDelayedTyposInExpr(E);
19059     if (!Result.isUsable()) return ExprError();
19060     E = Result.get();
19061   }
19062 
19063   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
19064   if (!placeholderType) return E;
19065 
19066   switch (placeholderType->getKind()) {
19067 
19068   // Overloaded expressions.
19069   case BuiltinType::Overload: {
19070     // Try to resolve a single function template specialization.
19071     // This is obligatory.
19072     ExprResult Result = E;
19073     if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
19074       return Result;
19075 
19076     // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
19077     // leaves Result unchanged on failure.
19078     Result = E;
19079     if (resolveAndFixAddressOfSingleOverloadCandidate(Result))
19080       return Result;
19081 
19082     // If that failed, try to recover with a call.
19083     tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
19084                          /*complain*/ true);
19085     return Result;
19086   }
19087 
19088   // Bound member functions.
19089   case BuiltinType::BoundMember: {
19090     ExprResult result = E;
19091     const Expr *BME = E->IgnoreParens();
19092     PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
19093     // Try to give a nicer diagnostic if it is a bound member that we recognize.
19094     if (isa<CXXPseudoDestructorExpr>(BME)) {
19095       PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
19096     } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
19097       if (ME->getMemberNameInfo().getName().getNameKind() ==
19098           DeclarationName::CXXDestructorName)
19099         PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
19100     }
19101     tryToRecoverWithCall(result, PD,
19102                          /*complain*/ true);
19103     return result;
19104   }
19105 
19106   // ARC unbridged casts.
19107   case BuiltinType::ARCUnbridgedCast: {
19108     Expr *realCast = stripARCUnbridgedCast(E);
19109     diagnoseARCUnbridgedCast(realCast);
19110     return realCast;
19111   }
19112 
19113   // Expressions of unknown type.
19114   case BuiltinType::UnknownAny:
19115     return diagnoseUnknownAnyExpr(*this, E);
19116 
19117   // Pseudo-objects.
19118   case BuiltinType::PseudoObject:
19119     return checkPseudoObjectRValue(E);
19120 
19121   case BuiltinType::BuiltinFn: {
19122     // Accept __noop without parens by implicitly converting it to a call expr.
19123     auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
19124     if (DRE) {
19125       auto *FD = cast<FunctionDecl>(DRE->getDecl());
19126       if (FD->getBuiltinID() == Builtin::BI__noop) {
19127         E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
19128                               CK_BuiltinFnToFnPtr)
19129                 .get();
19130         return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy,
19131                                 VK_RValue, SourceLocation(),
19132                                 FPOptionsOverride());
19133       }
19134     }
19135 
19136     Diag(E->getBeginLoc(), diag::err_builtin_fn_use);
19137     return ExprError();
19138   }
19139 
19140   case BuiltinType::IncompleteMatrixIdx:
19141     Diag(cast<MatrixSubscriptExpr>(E->IgnoreParens())
19142              ->getRowIdx()
19143              ->getBeginLoc(),
19144          diag::err_matrix_incomplete_index);
19145     return ExprError();
19146 
19147   // Expressions of unknown type.
19148   case BuiltinType::OMPArraySection:
19149     Diag(E->getBeginLoc(), diag::err_omp_array_section_use);
19150     return ExprError();
19151 
19152   // Expressions of unknown type.
19153   case BuiltinType::OMPArrayShaping:
19154     return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use));
19155 
19156   case BuiltinType::OMPIterator:
19157     return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use));
19158 
19159   // Everything else should be impossible.
19160 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
19161   case BuiltinType::Id:
19162 #include "clang/Basic/OpenCLImageTypes.def"
19163 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
19164   case BuiltinType::Id:
19165 #include "clang/Basic/OpenCLExtensionTypes.def"
19166 #define SVE_TYPE(Name, Id, SingletonId) \
19167   case BuiltinType::Id:
19168 #include "clang/Basic/AArch64SVEACLETypes.def"
19169 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
19170 #define PLACEHOLDER_TYPE(Id, SingletonId)
19171 #include "clang/AST/BuiltinTypes.def"
19172     break;
19173   }
19174 
19175   llvm_unreachable("invalid placeholder type!");
19176 }
19177 
19178 bool Sema::CheckCaseExpression(Expr *E) {
19179   if (E->isTypeDependent())
19180     return true;
19181   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
19182     return E->getType()->isIntegralOrEnumerationType();
19183   return false;
19184 }
19185 
19186 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
19187 ExprResult
19188 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
19189   assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
19190          "Unknown Objective-C Boolean value!");
19191   QualType BoolT = Context.ObjCBuiltinBoolTy;
19192   if (!Context.getBOOLDecl()) {
19193     LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
19194                         Sema::LookupOrdinaryName);
19195     if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
19196       NamedDecl *ND = Result.getFoundDecl();
19197       if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
19198         Context.setBOOLDecl(TD);
19199     }
19200   }
19201   if (Context.getBOOLDecl())
19202     BoolT = Context.getBOOLType();
19203   return new (Context)
19204       ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
19205 }
19206 
19207 ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
19208     llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
19209     SourceLocation RParen) {
19210 
19211   StringRef Platform = getASTContext().getTargetInfo().getPlatformName();
19212 
19213   auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) {
19214     return Spec.getPlatform() == Platform;
19215   });
19216 
19217   VersionTuple Version;
19218   if (Spec != AvailSpecs.end())
19219     Version = Spec->getVersion();
19220 
19221   // The use of `@available` in the enclosing function should be analyzed to
19222   // warn when it's used inappropriately (i.e. not if(@available)).
19223   if (getCurFunctionOrMethodDecl())
19224     getEnclosingFunction()->HasPotentialAvailabilityViolations = true;
19225   else if (getCurBlock() || getCurLambda())
19226     getCurFunction()->HasPotentialAvailabilityViolations = true;
19227 
19228   return new (Context)
19229       ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
19230 }
19231 
19232 ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End,
19233                                     ArrayRef<Expr *> SubExprs, QualType T) {
19234   if (!Context.getLangOpts().RecoveryAST)
19235     return ExprError();
19236 
19237   if (isSFINAEContext())
19238     return ExprError();
19239 
19240   if (T.isNull() || !Context.getLangOpts().RecoveryASTType)
19241     // We don't know the concrete type, fallback to dependent type.
19242     T = Context.DependentTy;
19243   return RecoveryExpr::Create(Context, T, Begin, End, SubExprs);
19244 }
19245