1 //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file implements semantic analysis for expressions.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "TreeTransform.h"
14 #include "UsedDeclVisitor.h"
15 #include "clang/AST/ASTConsumer.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/ASTLambda.h"
18 #include "clang/AST/ASTMutationListener.h"
19 #include "clang/AST/CXXInheritance.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "clang/AST/DeclTemplate.h"
22 #include "clang/AST/EvaluatedExprVisitor.h"
23 #include "clang/AST/Expr.h"
24 #include "clang/AST/ExprCXX.h"
25 #include "clang/AST/ExprObjC.h"
26 #include "clang/AST/ExprOpenMP.h"
27 #include "clang/AST/RecursiveASTVisitor.h"
28 #include "clang/AST/TypeLoc.h"
29 #include "clang/Basic/Builtins.h"
30 #include "clang/Basic/FixedPoint.h"
31 #include "clang/Basic/PartialDiagnostic.h"
32 #include "clang/Basic/SourceManager.h"
33 #include "clang/Basic/TargetInfo.h"
34 #include "clang/Lex/LiteralSupport.h"
35 #include "clang/Lex/Preprocessor.h"
36 #include "clang/Sema/AnalysisBasedWarnings.h"
37 #include "clang/Sema/DeclSpec.h"
38 #include "clang/Sema/DelayedDiagnostic.h"
39 #include "clang/Sema/Designator.h"
40 #include "clang/Sema/Initialization.h"
41 #include "clang/Sema/Lookup.h"
42 #include "clang/Sema/Overload.h"
43 #include "clang/Sema/ParsedTemplate.h"
44 #include "clang/Sema/Scope.h"
45 #include "clang/Sema/ScopeInfo.h"
46 #include "clang/Sema/SemaFixItUtils.h"
47 #include "clang/Sema/SemaInternal.h"
48 #include "clang/Sema/Template.h"
49 #include "llvm/Support/ConvertUTF.h"
50 #include "llvm/Support/SaveAndRestore.h"
51 using namespace clang;
52 using namespace sema;
53 using llvm::RoundingMode;
54 
55 /// Determine whether the use of this declaration is valid, without
56 /// emitting diagnostics.
57 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
58   // See if this is an auto-typed variable whose initializer we are parsing.
59   if (ParsingInitForAutoVars.count(D))
60     return false;
61 
62   // See if this is a deleted function.
63   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
64     if (FD->isDeleted())
65       return false;
66 
67     // If the function has a deduced return type, and we can't deduce it,
68     // then we can't use it either.
69     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
70         DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
71       return false;
72 
73     // See if this is an aligned allocation/deallocation function that is
74     // unavailable.
75     if (TreatUnavailableAsInvalid &&
76         isUnavailableAlignedAllocationFunction(*FD))
77       return false;
78   }
79 
80   // See if this function is unavailable.
81   if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
82       cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
83     return false;
84 
85   return true;
86 }
87 
88 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
89   // Warn if this is used but marked unused.
90   if (const auto *A = D->getAttr<UnusedAttr>()) {
91     // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
92     // should diagnose them.
93     if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused &&
94         A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) {
95       const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext());
96       if (DC && !DC->hasAttr<UnusedAttr>())
97         S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
98     }
99   }
100 }
101 
102 /// Emit a note explaining that this function is deleted.
103 void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
104   assert(Decl && Decl->isDeleted());
105 
106   if (Decl->isDefaulted()) {
107     // If the method was explicitly defaulted, point at that declaration.
108     if (!Decl->isImplicit())
109       Diag(Decl->getLocation(), diag::note_implicitly_deleted);
110 
111     // Try to diagnose why this special member function was implicitly
112     // deleted. This might fail, if that reason no longer applies.
113     DiagnoseDeletedDefaultedFunction(Decl);
114     return;
115   }
116 
117   auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
118   if (Ctor && Ctor->isInheritingConstructor())
119     return NoteDeletedInheritingConstructor(Ctor);
120 
121   Diag(Decl->getLocation(), diag::note_availability_specified_here)
122     << Decl << 1;
123 }
124 
125 /// Determine whether a FunctionDecl was ever declared with an
126 /// explicit storage class.
127 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
128   for (auto I : D->redecls()) {
129     if (I->getStorageClass() != SC_None)
130       return true;
131   }
132   return false;
133 }
134 
135 /// Check whether we're in an extern inline function and referring to a
136 /// variable or function with internal linkage (C11 6.7.4p3).
137 ///
138 /// This is only a warning because we used to silently accept this code, but
139 /// in many cases it will not behave correctly. This is not enabled in C++ mode
140 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
141 /// and so while there may still be user mistakes, most of the time we can't
142 /// prove that there are errors.
143 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
144                                                       const NamedDecl *D,
145                                                       SourceLocation Loc) {
146   // This is disabled under C++; there are too many ways for this to fire in
147   // contexts where the warning is a false positive, or where it is technically
148   // correct but benign.
149   if (S.getLangOpts().CPlusPlus)
150     return;
151 
152   // Check if this is an inlined function or method.
153   FunctionDecl *Current = S.getCurFunctionDecl();
154   if (!Current)
155     return;
156   if (!Current->isInlined())
157     return;
158   if (!Current->isExternallyVisible())
159     return;
160 
161   // Check if the decl has internal linkage.
162   if (D->getFormalLinkage() != InternalLinkage)
163     return;
164 
165   // Downgrade from ExtWarn to Extension if
166   //  (1) the supposedly external inline function is in the main file,
167   //      and probably won't be included anywhere else.
168   //  (2) the thing we're referencing is a pure function.
169   //  (3) the thing we're referencing is another inline function.
170   // This last can give us false negatives, but it's better than warning on
171   // wrappers for simple C library functions.
172   const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
173   bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
174   if (!DowngradeWarning && UsedFn)
175     DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
176 
177   S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
178                                : diag::ext_internal_in_extern_inline)
179     << /*IsVar=*/!UsedFn << D;
180 
181   S.MaybeSuggestAddingStaticToDecl(Current);
182 
183   S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
184       << D;
185 }
186 
187 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
188   const FunctionDecl *First = Cur->getFirstDecl();
189 
190   // Suggest "static" on the function, if possible.
191   if (!hasAnyExplicitStorageClass(First)) {
192     SourceLocation DeclBegin = First->getSourceRange().getBegin();
193     Diag(DeclBegin, diag::note_convert_inline_to_static)
194       << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
195   }
196 }
197 
198 /// Determine whether the use of this declaration is valid, and
199 /// emit any corresponding diagnostics.
200 ///
201 /// This routine diagnoses various problems with referencing
202 /// declarations that can occur when using a declaration. For example,
203 /// it might warn if a deprecated or unavailable declaration is being
204 /// used, or produce an error (and return true) if a C++0x deleted
205 /// function is being used.
206 ///
207 /// \returns true if there was an error (this declaration cannot be
208 /// referenced), false otherwise.
209 ///
210 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
211                              const ObjCInterfaceDecl *UnknownObjCClass,
212                              bool ObjCPropertyAccess,
213                              bool AvoidPartialAvailabilityChecks,
214                              ObjCInterfaceDecl *ClassReceiver) {
215   SourceLocation Loc = Locs.front();
216   if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
217     // If there were any diagnostics suppressed by template argument deduction,
218     // emit them now.
219     auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
220     if (Pos != SuppressedDiagnostics.end()) {
221       for (const PartialDiagnosticAt &Suppressed : Pos->second)
222         Diag(Suppressed.first, Suppressed.second);
223 
224       // Clear out the list of suppressed diagnostics, so that we don't emit
225       // them again for this specialization. However, we don't obsolete this
226       // entry from the table, because we want to avoid ever emitting these
227       // diagnostics again.
228       Pos->second.clear();
229     }
230 
231     // C++ [basic.start.main]p3:
232     //   The function 'main' shall not be used within a program.
233     if (cast<FunctionDecl>(D)->isMain())
234       Diag(Loc, diag::ext_main_used);
235 
236     diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc);
237   }
238 
239   // See if this is an auto-typed variable whose initializer we are parsing.
240   if (ParsingInitForAutoVars.count(D)) {
241     if (isa<BindingDecl>(D)) {
242       Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
243         << D->getDeclName();
244     } else {
245       Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
246         << D->getDeclName() << cast<VarDecl>(D)->getType();
247     }
248     return true;
249   }
250 
251   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
252     // See if this is a deleted function.
253     if (FD->isDeleted()) {
254       auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
255       if (Ctor && Ctor->isInheritingConstructor())
256         Diag(Loc, diag::err_deleted_inherited_ctor_use)
257             << Ctor->getParent()
258             << Ctor->getInheritedConstructor().getConstructor()->getParent();
259       else
260         Diag(Loc, diag::err_deleted_function_use);
261       NoteDeletedFunction(FD);
262       return true;
263     }
264 
265     // [expr.prim.id]p4
266     //   A program that refers explicitly or implicitly to a function with a
267     //   trailing requires-clause whose constraint-expression is not satisfied,
268     //   other than to declare it, is ill-formed. [...]
269     //
270     // See if this is a function with constraints that need to be satisfied.
271     // Check this before deducing the return type, as it might instantiate the
272     // definition.
273     if (FD->getTrailingRequiresClause()) {
274       ConstraintSatisfaction Satisfaction;
275       if (CheckFunctionConstraints(FD, Satisfaction, Loc))
276         // A diagnostic will have already been generated (non-constant
277         // constraint expression, for example)
278         return true;
279       if (!Satisfaction.IsSatisfied) {
280         Diag(Loc,
281              diag::err_reference_to_function_with_unsatisfied_constraints)
282             << D;
283         DiagnoseUnsatisfiedConstraint(Satisfaction);
284         return true;
285       }
286     }
287 
288     // If the function has a deduced return type, and we can't deduce it,
289     // then we can't use it either.
290     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
291         DeduceReturnType(FD, Loc))
292       return true;
293 
294     if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD))
295       return true;
296   }
297 
298   if (auto *MD = dyn_cast<CXXMethodDecl>(D)) {
299     // Lambdas are only default-constructible or assignable in C++2a onwards.
300     if (MD->getParent()->isLambda() &&
301         ((isa<CXXConstructorDecl>(MD) &&
302           cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) ||
303          MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) {
304       Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign)
305         << !isa<CXXConstructorDecl>(MD);
306     }
307   }
308 
309   auto getReferencedObjCProp = [](const NamedDecl *D) ->
310                                       const ObjCPropertyDecl * {
311     if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
312       return MD->findPropertyDecl();
313     return nullptr;
314   };
315   if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
316     if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc))
317       return true;
318   } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) {
319       return true;
320   }
321 
322   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
323   // Only the variables omp_in and omp_out are allowed in the combiner.
324   // Only the variables omp_priv and omp_orig are allowed in the
325   // initializer-clause.
326   auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
327   if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
328       isa<VarDecl>(D)) {
329     Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
330         << getCurFunction()->HasOMPDeclareReductionCombiner;
331     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
332     return true;
333   }
334 
335   // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions
336   //  List-items in map clauses on this construct may only refer to the declared
337   //  variable var and entities that could be referenced by a procedure defined
338   //  at the same location
339   auto *DMD = dyn_cast<OMPDeclareMapperDecl>(CurContext);
340   if (LangOpts.OpenMP && DMD && !CurContext->containsDecl(D) &&
341       isa<VarDecl>(D)) {
342     Diag(Loc, diag::err_omp_declare_mapper_wrong_var)
343         << DMD->getVarName().getAsString();
344     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
345     return true;
346   }
347 
348   DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,
349                              AvoidPartialAvailabilityChecks, ClassReceiver);
350 
351   DiagnoseUnusedOfDecl(*this, D, Loc);
352 
353   diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
354 
355   if (isa<ParmVarDecl>(D) && isa<RequiresExprBodyDecl>(D->getDeclContext()) &&
356       !isUnevaluatedContext()) {
357     // C++ [expr.prim.req.nested] p3
358     //   A local parameter shall only appear as an unevaluated operand
359     //   (Clause 8) within the constraint-expression.
360     Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context)
361         << D;
362     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
363     return true;
364   }
365 
366   return false;
367 }
368 
369 /// DiagnoseSentinelCalls - This routine checks whether a call or
370 /// message-send is to a declaration with the sentinel attribute, and
371 /// if so, it checks that the requirements of the sentinel are
372 /// satisfied.
373 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
374                                  ArrayRef<Expr *> Args) {
375   const SentinelAttr *attr = D->getAttr<SentinelAttr>();
376   if (!attr)
377     return;
378 
379   // The number of formal parameters of the declaration.
380   unsigned numFormalParams;
381 
382   // The kind of declaration.  This is also an index into a %select in
383   // the diagnostic.
384   enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
385 
386   if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
387     numFormalParams = MD->param_size();
388     calleeType = CT_Method;
389   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
390     numFormalParams = FD->param_size();
391     calleeType = CT_Function;
392   } else if (isa<VarDecl>(D)) {
393     QualType type = cast<ValueDecl>(D)->getType();
394     const FunctionType *fn = nullptr;
395     if (const PointerType *ptr = type->getAs<PointerType>()) {
396       fn = ptr->getPointeeType()->getAs<FunctionType>();
397       if (!fn) return;
398       calleeType = CT_Function;
399     } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
400       fn = ptr->getPointeeType()->castAs<FunctionType>();
401       calleeType = CT_Block;
402     } else {
403       return;
404     }
405 
406     if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
407       numFormalParams = proto->getNumParams();
408     } else {
409       numFormalParams = 0;
410     }
411   } else {
412     return;
413   }
414 
415   // "nullPos" is the number of formal parameters at the end which
416   // effectively count as part of the variadic arguments.  This is
417   // useful if you would prefer to not have *any* formal parameters,
418   // but the language forces you to have at least one.
419   unsigned nullPos = attr->getNullPos();
420   assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
421   numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
422 
423   // The number of arguments which should follow the sentinel.
424   unsigned numArgsAfterSentinel = attr->getSentinel();
425 
426   // If there aren't enough arguments for all the formal parameters,
427   // the sentinel, and the args after the sentinel, complain.
428   if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
429     Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
430     Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
431     return;
432   }
433 
434   // Otherwise, find the sentinel expression.
435   Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
436   if (!sentinelExpr) return;
437   if (sentinelExpr->isValueDependent()) return;
438   if (Context.isSentinelNullExpr(sentinelExpr)) return;
439 
440   // Pick a reasonable string to insert.  Optimistically use 'nil', 'nullptr',
441   // or 'NULL' if those are actually defined in the context.  Only use
442   // 'nil' for ObjC methods, where it's much more likely that the
443   // variadic arguments form a list of object pointers.
444   SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc());
445   std::string NullValue;
446   if (calleeType == CT_Method && PP.isMacroDefined("nil"))
447     NullValue = "nil";
448   else if (getLangOpts().CPlusPlus11)
449     NullValue = "nullptr";
450   else if (PP.isMacroDefined("NULL"))
451     NullValue = "NULL";
452   else
453     NullValue = "(void*) 0";
454 
455   if (MissingNilLoc.isInvalid())
456     Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
457   else
458     Diag(MissingNilLoc, diag::warn_missing_sentinel)
459       << int(calleeType)
460       << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
461   Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
462 }
463 
464 SourceRange Sema::getExprRange(Expr *E) const {
465   return E ? E->getSourceRange() : SourceRange();
466 }
467 
468 //===----------------------------------------------------------------------===//
469 //  Standard Promotions and Conversions
470 //===----------------------------------------------------------------------===//
471 
472 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
473 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
474   // Handle any placeholder expressions which made it here.
475   if (E->getType()->isPlaceholderType()) {
476     ExprResult result = CheckPlaceholderExpr(E);
477     if (result.isInvalid()) return ExprError();
478     E = result.get();
479   }
480 
481   QualType Ty = E->getType();
482   assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
483 
484   if (Ty->isFunctionType()) {
485     if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
486       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
487         if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
488           return ExprError();
489 
490     E = ImpCastExprToType(E, Context.getPointerType(Ty),
491                           CK_FunctionToPointerDecay).get();
492   } else if (Ty->isArrayType()) {
493     // In C90 mode, arrays only promote to pointers if the array expression is
494     // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
495     // type 'array of type' is converted to an expression that has type 'pointer
496     // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
497     // that has type 'array of type' ...".  The relevant change is "an lvalue"
498     // (C90) to "an expression" (C99).
499     //
500     // C++ 4.2p1:
501     // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
502     // T" can be converted to an rvalue of type "pointer to T".
503     //
504     if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
505       E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
506                             CK_ArrayToPointerDecay).get();
507   }
508   return E;
509 }
510 
511 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
512   // Check to see if we are dereferencing a null pointer.  If so,
513   // and if not volatile-qualified, this is undefined behavior that the
514   // optimizer will delete, so warn about it.  People sometimes try to use this
515   // to get a deterministic trap and are surprised by clang's behavior.  This
516   // only handles the pattern "*null", which is a very syntactic check.
517   const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts());
518   if (UO && UO->getOpcode() == UO_Deref &&
519       UO->getSubExpr()->getType()->isPointerType()) {
520     const LangAS AS =
521         UO->getSubExpr()->getType()->getPointeeType().getAddressSpace();
522     if ((!isTargetAddressSpace(AS) ||
523          (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) &&
524         UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant(
525             S.Context, Expr::NPC_ValueDependentIsNotNull) &&
526         !UO->getType().isVolatileQualified()) {
527       S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
528                             S.PDiag(diag::warn_indirection_through_null)
529                                 << UO->getSubExpr()->getSourceRange());
530       S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
531                             S.PDiag(diag::note_indirection_through_null));
532     }
533   }
534 }
535 
536 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
537                                     SourceLocation AssignLoc,
538                                     const Expr* RHS) {
539   const ObjCIvarDecl *IV = OIRE->getDecl();
540   if (!IV)
541     return;
542 
543   DeclarationName MemberName = IV->getDeclName();
544   IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
545   if (!Member || !Member->isStr("isa"))
546     return;
547 
548   const Expr *Base = OIRE->getBase();
549   QualType BaseType = Base->getType();
550   if (OIRE->isArrow())
551     BaseType = BaseType->getPointeeType();
552   if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
553     if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
554       ObjCInterfaceDecl *ClassDeclared = nullptr;
555       ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
556       if (!ClassDeclared->getSuperClass()
557           && (*ClassDeclared->ivar_begin()) == IV) {
558         if (RHS) {
559           NamedDecl *ObjectSetClass =
560             S.LookupSingleName(S.TUScope,
561                                &S.Context.Idents.get("object_setClass"),
562                                SourceLocation(), S.LookupOrdinaryName);
563           if (ObjectSetClass) {
564             SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc());
565             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign)
566                 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
567                                               "object_setClass(")
568                 << FixItHint::CreateReplacement(
569                        SourceRange(OIRE->getOpLoc(), AssignLoc), ",")
570                 << FixItHint::CreateInsertion(RHSLocEnd, ")");
571           }
572           else
573             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
574         } else {
575           NamedDecl *ObjectGetClass =
576             S.LookupSingleName(S.TUScope,
577                                &S.Context.Idents.get("object_getClass"),
578                                SourceLocation(), S.LookupOrdinaryName);
579           if (ObjectGetClass)
580             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use)
581                 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
582                                               "object_getClass(")
583                 << FixItHint::CreateReplacement(
584                        SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")");
585           else
586             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
587         }
588         S.Diag(IV->getLocation(), diag::note_ivar_decl);
589       }
590     }
591 }
592 
593 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
594   // Handle any placeholder expressions which made it here.
595   if (E->getType()->isPlaceholderType()) {
596     ExprResult result = CheckPlaceholderExpr(E);
597     if (result.isInvalid()) return ExprError();
598     E = result.get();
599   }
600 
601   // C++ [conv.lval]p1:
602   //   A glvalue of a non-function, non-array type T can be
603   //   converted to a prvalue.
604   if (!E->isGLValue()) return E;
605 
606   QualType T = E->getType();
607   assert(!T.isNull() && "r-value conversion on typeless expression?");
608 
609   // We don't want to throw lvalue-to-rvalue casts on top of
610   // expressions of certain types in C++.
611   if (getLangOpts().CPlusPlus &&
612       (E->getType() == Context.OverloadTy ||
613        T->isDependentType() ||
614        T->isRecordType()))
615     return E;
616 
617   // The C standard is actually really unclear on this point, and
618   // DR106 tells us what the result should be but not why.  It's
619   // generally best to say that void types just doesn't undergo
620   // lvalue-to-rvalue at all.  Note that expressions of unqualified
621   // 'void' type are never l-values, but qualified void can be.
622   if (T->isVoidType())
623     return E;
624 
625   // OpenCL usually rejects direct accesses to values of 'half' type.
626   if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
627       T->isHalfType()) {
628     Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
629       << 0 << T;
630     return ExprError();
631   }
632 
633   CheckForNullPointerDereference(*this, E);
634   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
635     NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
636                                      &Context.Idents.get("object_getClass"),
637                                      SourceLocation(), LookupOrdinaryName);
638     if (ObjectGetClass)
639       Diag(E->getExprLoc(), diag::warn_objc_isa_use)
640           << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(")
641           << FixItHint::CreateReplacement(
642                  SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
643     else
644       Diag(E->getExprLoc(), diag::warn_objc_isa_use);
645   }
646   else if (const ObjCIvarRefExpr *OIRE =
647             dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
648     DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
649 
650   // C++ [conv.lval]p1:
651   //   [...] If T is a non-class type, the type of the prvalue is the
652   //   cv-unqualified version of T. Otherwise, the type of the
653   //   rvalue is T.
654   //
655   // C99 6.3.2.1p2:
656   //   If the lvalue has qualified type, the value has the unqualified
657   //   version of the type of the lvalue; otherwise, the value has the
658   //   type of the lvalue.
659   if (T.hasQualifiers())
660     T = T.getUnqualifiedType();
661 
662   // Under the MS ABI, lock down the inheritance model now.
663   if (T->isMemberPointerType() &&
664       Context.getTargetInfo().getCXXABI().isMicrosoft())
665     (void)isCompleteType(E->getExprLoc(), T);
666 
667   ExprResult Res = CheckLValueToRValueConversionOperand(E);
668   if (Res.isInvalid())
669     return Res;
670   E = Res.get();
671 
672   // Loading a __weak object implicitly retains the value, so we need a cleanup to
673   // balance that.
674   if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
675     Cleanup.setExprNeedsCleanups(true);
676 
677   if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
678     Cleanup.setExprNeedsCleanups(true);
679 
680   // C++ [conv.lval]p3:
681   //   If T is cv std::nullptr_t, the result is a null pointer constant.
682   CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue;
683   Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_RValue);
684 
685   // C11 6.3.2.1p2:
686   //   ... if the lvalue has atomic type, the value has the non-atomic version
687   //   of the type of the lvalue ...
688   if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
689     T = Atomic->getValueType().getUnqualifiedType();
690     Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
691                                    nullptr, VK_RValue);
692   }
693 
694   return Res;
695 }
696 
697 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
698   ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
699   if (Res.isInvalid())
700     return ExprError();
701   Res = DefaultLvalueConversion(Res.get());
702   if (Res.isInvalid())
703     return ExprError();
704   return Res;
705 }
706 
707 /// CallExprUnaryConversions - a special case of an unary conversion
708 /// performed on a function designator of a call expression.
709 ExprResult Sema::CallExprUnaryConversions(Expr *E) {
710   QualType Ty = E->getType();
711   ExprResult Res = E;
712   // Only do implicit cast for a function type, but not for a pointer
713   // to function type.
714   if (Ty->isFunctionType()) {
715     Res = ImpCastExprToType(E, Context.getPointerType(Ty),
716                             CK_FunctionToPointerDecay).get();
717     if (Res.isInvalid())
718       return ExprError();
719   }
720   Res = DefaultLvalueConversion(Res.get());
721   if (Res.isInvalid())
722     return ExprError();
723   return Res.get();
724 }
725 
726 /// UsualUnaryConversions - Performs various conversions that are common to most
727 /// operators (C99 6.3). The conversions of array and function types are
728 /// sometimes suppressed. For example, the array->pointer conversion doesn't
729 /// apply if the array is an argument to the sizeof or address (&) operators.
730 /// In these instances, this routine should *not* be called.
731 ExprResult Sema::UsualUnaryConversions(Expr *E) {
732   // First, convert to an r-value.
733   ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
734   if (Res.isInvalid())
735     return ExprError();
736   E = Res.get();
737 
738   QualType Ty = E->getType();
739   assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
740 
741   // Half FP have to be promoted to float unless it is natively supported
742   if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
743     return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
744 
745   // Try to perform integral promotions if the object has a theoretically
746   // promotable type.
747   if (Ty->isIntegralOrUnscopedEnumerationType()) {
748     // C99 6.3.1.1p2:
749     //
750     //   The following may be used in an expression wherever an int or
751     //   unsigned int may be used:
752     //     - an object or expression with an integer type whose integer
753     //       conversion rank is less than or equal to the rank of int
754     //       and unsigned int.
755     //     - A bit-field of type _Bool, int, signed int, or unsigned int.
756     //
757     //   If an int can represent all values of the original type, the
758     //   value is converted to an int; otherwise, it is converted to an
759     //   unsigned int. These are called the integer promotions. All
760     //   other types are unchanged by the integer promotions.
761 
762     QualType PTy = Context.isPromotableBitField(E);
763     if (!PTy.isNull()) {
764       E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
765       return E;
766     }
767     if (Ty->isPromotableIntegerType()) {
768       QualType PT = Context.getPromotedIntegerType(Ty);
769       E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
770       return E;
771     }
772   }
773   return E;
774 }
775 
776 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
777 /// do not have a prototype. Arguments that have type float or __fp16
778 /// are promoted to double. All other argument types are converted by
779 /// UsualUnaryConversions().
780 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
781   QualType Ty = E->getType();
782   assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
783 
784   ExprResult Res = UsualUnaryConversions(E);
785   if (Res.isInvalid())
786     return ExprError();
787   E = Res.get();
788 
789   // If this is a 'float'  or '__fp16' (CVR qualified or typedef)
790   // promote to double.
791   // Note that default argument promotion applies only to float (and
792   // half/fp16); it does not apply to _Float16.
793   const BuiltinType *BTy = Ty->getAs<BuiltinType>();
794   if (BTy && (BTy->getKind() == BuiltinType::Half ||
795               BTy->getKind() == BuiltinType::Float)) {
796     if (getLangOpts().OpenCL &&
797         !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
798         if (BTy->getKind() == BuiltinType::Half) {
799             E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
800         }
801     } else {
802       E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
803     }
804   }
805 
806   // C++ performs lvalue-to-rvalue conversion as a default argument
807   // promotion, even on class types, but note:
808   //   C++11 [conv.lval]p2:
809   //     When an lvalue-to-rvalue conversion occurs in an unevaluated
810   //     operand or a subexpression thereof the value contained in the
811   //     referenced object is not accessed. Otherwise, if the glvalue
812   //     has a class type, the conversion copy-initializes a temporary
813   //     of type T from the glvalue and the result of the conversion
814   //     is a prvalue for the temporary.
815   // FIXME: add some way to gate this entire thing for correctness in
816   // potentially potentially evaluated contexts.
817   if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
818     ExprResult Temp = PerformCopyInitialization(
819                        InitializedEntity::InitializeTemporary(E->getType()),
820                                                 E->getExprLoc(), E);
821     if (Temp.isInvalid())
822       return ExprError();
823     E = Temp.get();
824   }
825 
826   return E;
827 }
828 
829 /// Determine the degree of POD-ness for an expression.
830 /// Incomplete types are considered POD, since this check can be performed
831 /// when we're in an unevaluated context.
832 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
833   if (Ty->isIncompleteType()) {
834     // C++11 [expr.call]p7:
835     //   After these conversions, if the argument does not have arithmetic,
836     //   enumeration, pointer, pointer to member, or class type, the program
837     //   is ill-formed.
838     //
839     // Since we've already performed array-to-pointer and function-to-pointer
840     // decay, the only such type in C++ is cv void. This also handles
841     // initializer lists as variadic arguments.
842     if (Ty->isVoidType())
843       return VAK_Invalid;
844 
845     if (Ty->isObjCObjectType())
846       return VAK_Invalid;
847     return VAK_Valid;
848   }
849 
850   if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
851     return VAK_Invalid;
852 
853   if (Ty.isCXX98PODType(Context))
854     return VAK_Valid;
855 
856   // C++11 [expr.call]p7:
857   //   Passing a potentially-evaluated argument of class type (Clause 9)
858   //   having a non-trivial copy constructor, a non-trivial move constructor,
859   //   or a non-trivial destructor, with no corresponding parameter,
860   //   is conditionally-supported with implementation-defined semantics.
861   if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
862     if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
863       if (!Record->hasNonTrivialCopyConstructor() &&
864           !Record->hasNonTrivialMoveConstructor() &&
865           !Record->hasNonTrivialDestructor())
866         return VAK_ValidInCXX11;
867 
868   if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
869     return VAK_Valid;
870 
871   if (Ty->isObjCObjectType())
872     return VAK_Invalid;
873 
874   if (getLangOpts().MSVCCompat)
875     return VAK_MSVCUndefined;
876 
877   // FIXME: In C++11, these cases are conditionally-supported, meaning we're
878   // permitted to reject them. We should consider doing so.
879   return VAK_Undefined;
880 }
881 
882 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
883   // Don't allow one to pass an Objective-C interface to a vararg.
884   const QualType &Ty = E->getType();
885   VarArgKind VAK = isValidVarArgType(Ty);
886 
887   // Complain about passing non-POD types through varargs.
888   switch (VAK) {
889   case VAK_ValidInCXX11:
890     DiagRuntimeBehavior(
891         E->getBeginLoc(), nullptr,
892         PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT);
893     LLVM_FALLTHROUGH;
894   case VAK_Valid:
895     if (Ty->isRecordType()) {
896       // This is unlikely to be what the user intended. If the class has a
897       // 'c_str' member function, the user probably meant to call that.
898       DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
899                           PDiag(diag::warn_pass_class_arg_to_vararg)
900                               << Ty << CT << hasCStrMethod(E) << ".c_str()");
901     }
902     break;
903 
904   case VAK_Undefined:
905   case VAK_MSVCUndefined:
906     DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
907                         PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
908                             << getLangOpts().CPlusPlus11 << Ty << CT);
909     break;
910 
911   case VAK_Invalid:
912     if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
913       Diag(E->getBeginLoc(),
914            diag::err_cannot_pass_non_trivial_c_struct_to_vararg)
915           << Ty << CT;
916     else if (Ty->isObjCObjectType())
917       DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
918                           PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
919                               << Ty << CT);
920     else
921       Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg)
922           << isa<InitListExpr>(E) << Ty << CT;
923     break;
924   }
925 }
926 
927 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
928 /// will create a trap if the resulting type is not a POD type.
929 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
930                                                   FunctionDecl *FDecl) {
931   if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
932     // Strip the unbridged-cast placeholder expression off, if applicable.
933     if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
934         (CT == VariadicMethod ||
935          (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
936       E = stripARCUnbridgedCast(E);
937 
938     // Otherwise, do normal placeholder checking.
939     } else {
940       ExprResult ExprRes = CheckPlaceholderExpr(E);
941       if (ExprRes.isInvalid())
942         return ExprError();
943       E = ExprRes.get();
944     }
945   }
946 
947   ExprResult ExprRes = DefaultArgumentPromotion(E);
948   if (ExprRes.isInvalid())
949     return ExprError();
950   E = ExprRes.get();
951 
952   // Diagnostics regarding non-POD argument types are
953   // emitted along with format string checking in Sema::CheckFunctionCall().
954   if (isValidVarArgType(E->getType()) == VAK_Undefined) {
955     // Turn this into a trap.
956     CXXScopeSpec SS;
957     SourceLocation TemplateKWLoc;
958     UnqualifiedId Name;
959     Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
960                        E->getBeginLoc());
961     ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name,
962                                           /*HasTrailingLParen=*/true,
963                                           /*IsAddressOfOperand=*/false);
964     if (TrapFn.isInvalid())
965       return ExprError();
966 
967     ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(),
968                                     None, E->getEndLoc());
969     if (Call.isInvalid())
970       return ExprError();
971 
972     ExprResult Comma =
973         ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E);
974     if (Comma.isInvalid())
975       return ExprError();
976     return Comma.get();
977   }
978 
979   if (!getLangOpts().CPlusPlus &&
980       RequireCompleteType(E->getExprLoc(), E->getType(),
981                           diag::err_call_incomplete_argument))
982     return ExprError();
983 
984   return E;
985 }
986 
987 /// Converts an integer to complex float type.  Helper function of
988 /// UsualArithmeticConversions()
989 ///
990 /// \return false if the integer expression is an integer type and is
991 /// successfully converted to the complex type.
992 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
993                                                   ExprResult &ComplexExpr,
994                                                   QualType IntTy,
995                                                   QualType ComplexTy,
996                                                   bool SkipCast) {
997   if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
998   if (SkipCast) return false;
999   if (IntTy->isIntegerType()) {
1000     QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
1001     IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
1002     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1003                                   CK_FloatingRealToComplex);
1004   } else {
1005     assert(IntTy->isComplexIntegerType());
1006     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1007                                   CK_IntegralComplexToFloatingComplex);
1008   }
1009   return false;
1010 }
1011 
1012 /// Handle arithmetic conversion with complex types.  Helper function of
1013 /// UsualArithmeticConversions()
1014 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
1015                                              ExprResult &RHS, QualType LHSType,
1016                                              QualType RHSType,
1017                                              bool IsCompAssign) {
1018   // if we have an integer operand, the result is the complex type.
1019   if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
1020                                              /*skipCast*/false))
1021     return LHSType;
1022   if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
1023                                              /*skipCast*/IsCompAssign))
1024     return RHSType;
1025 
1026   // This handles complex/complex, complex/float, or float/complex.
1027   // When both operands are complex, the shorter operand is converted to the
1028   // type of the longer, and that is the type of the result. This corresponds
1029   // to what is done when combining two real floating-point operands.
1030   // The fun begins when size promotion occur across type domains.
1031   // From H&S 6.3.4: When one operand is complex and the other is a real
1032   // floating-point type, the less precise type is converted, within it's
1033   // real or complex domain, to the precision of the other type. For example,
1034   // when combining a "long double" with a "double _Complex", the
1035   // "double _Complex" is promoted to "long double _Complex".
1036 
1037   // Compute the rank of the two types, regardless of whether they are complex.
1038   int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1039 
1040   auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
1041   auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
1042   QualType LHSElementType =
1043       LHSComplexType ? LHSComplexType->getElementType() : LHSType;
1044   QualType RHSElementType =
1045       RHSComplexType ? RHSComplexType->getElementType() : RHSType;
1046 
1047   QualType ResultType = S.Context.getComplexType(LHSElementType);
1048   if (Order < 0) {
1049     // Promote the precision of the LHS if not an assignment.
1050     ResultType = S.Context.getComplexType(RHSElementType);
1051     if (!IsCompAssign) {
1052       if (LHSComplexType)
1053         LHS =
1054             S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
1055       else
1056         LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
1057     }
1058   } else if (Order > 0) {
1059     // Promote the precision of the RHS.
1060     if (RHSComplexType)
1061       RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
1062     else
1063       RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
1064   }
1065   return ResultType;
1066 }
1067 
1068 /// Handle arithmetic conversion from integer to float.  Helper function
1069 /// of UsualArithmeticConversions()
1070 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1071                                            ExprResult &IntExpr,
1072                                            QualType FloatTy, QualType IntTy,
1073                                            bool ConvertFloat, bool ConvertInt) {
1074   if (IntTy->isIntegerType()) {
1075     if (ConvertInt)
1076       // Convert intExpr to the lhs floating point type.
1077       IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1078                                     CK_IntegralToFloating);
1079     return FloatTy;
1080   }
1081 
1082   // Convert both sides to the appropriate complex float.
1083   assert(IntTy->isComplexIntegerType());
1084   QualType result = S.Context.getComplexType(FloatTy);
1085 
1086   // _Complex int -> _Complex float
1087   if (ConvertInt)
1088     IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1089                                   CK_IntegralComplexToFloatingComplex);
1090 
1091   // float -> _Complex float
1092   if (ConvertFloat)
1093     FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1094                                     CK_FloatingRealToComplex);
1095 
1096   return result;
1097 }
1098 
1099 /// Handle arithmethic conversion with floating point types.  Helper
1100 /// function of UsualArithmeticConversions()
1101 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1102                                       ExprResult &RHS, QualType LHSType,
1103                                       QualType RHSType, bool IsCompAssign) {
1104   bool LHSFloat = LHSType->isRealFloatingType();
1105   bool RHSFloat = RHSType->isRealFloatingType();
1106 
1107   // If we have two real floating types, convert the smaller operand
1108   // to the bigger result.
1109   if (LHSFloat && RHSFloat) {
1110     int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1111     if (order > 0) {
1112       RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1113       return LHSType;
1114     }
1115 
1116     assert(order < 0 && "illegal float comparison");
1117     if (!IsCompAssign)
1118       LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1119     return RHSType;
1120   }
1121 
1122   if (LHSFloat) {
1123     // Half FP has to be promoted to float unless it is natively supported
1124     if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1125       LHSType = S.Context.FloatTy;
1126 
1127     return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1128                                       /*ConvertFloat=*/!IsCompAssign,
1129                                       /*ConvertInt=*/ true);
1130   }
1131   assert(RHSFloat);
1132   return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1133                                     /*convertInt=*/ true,
1134                                     /*convertFloat=*/!IsCompAssign);
1135 }
1136 
1137 /// Diagnose attempts to convert between __float128 and long double if
1138 /// there is no support for such conversion. Helper function of
1139 /// UsualArithmeticConversions().
1140 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1141                                       QualType RHSType) {
1142   /*  No issue converting if at least one of the types is not a floating point
1143       type or the two types have the same rank.
1144   */
1145   if (!LHSType->isFloatingType() || !RHSType->isFloatingType() ||
1146       S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0)
1147     return false;
1148 
1149   assert(LHSType->isFloatingType() && RHSType->isFloatingType() &&
1150          "The remaining types must be floating point types.");
1151 
1152   auto *LHSComplex = LHSType->getAs<ComplexType>();
1153   auto *RHSComplex = RHSType->getAs<ComplexType>();
1154 
1155   QualType LHSElemType = LHSComplex ?
1156     LHSComplex->getElementType() : LHSType;
1157   QualType RHSElemType = RHSComplex ?
1158     RHSComplex->getElementType() : RHSType;
1159 
1160   // No issue if the two types have the same representation
1161   if (&S.Context.getFloatTypeSemantics(LHSElemType) ==
1162       &S.Context.getFloatTypeSemantics(RHSElemType))
1163     return false;
1164 
1165   bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty &&
1166                                 RHSElemType == S.Context.LongDoubleTy);
1167   Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy &&
1168                             RHSElemType == S.Context.Float128Ty);
1169 
1170   // We've handled the situation where __float128 and long double have the same
1171   // representation. We allow all conversions for all possible long double types
1172   // except PPC's double double.
1173   return Float128AndLongDouble &&
1174     (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) ==
1175      &llvm::APFloat::PPCDoubleDouble());
1176 }
1177 
1178 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1179 
1180 namespace {
1181 /// These helper callbacks are placed in an anonymous namespace to
1182 /// permit their use as function template parameters.
1183 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1184   return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1185 }
1186 
1187 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1188   return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1189                              CK_IntegralComplexCast);
1190 }
1191 }
1192 
1193 /// Handle integer arithmetic conversions.  Helper function of
1194 /// UsualArithmeticConversions()
1195 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1196 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1197                                         ExprResult &RHS, QualType LHSType,
1198                                         QualType RHSType, bool IsCompAssign) {
1199   // The rules for this case are in C99 6.3.1.8
1200   int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1201   bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1202   bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1203   if (LHSSigned == RHSSigned) {
1204     // Same signedness; use the higher-ranked type
1205     if (order >= 0) {
1206       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1207       return LHSType;
1208     } else if (!IsCompAssign)
1209       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1210     return RHSType;
1211   } else if (order != (LHSSigned ? 1 : -1)) {
1212     // The unsigned type has greater than or equal rank to the
1213     // signed type, so use the unsigned type
1214     if (RHSSigned) {
1215       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1216       return LHSType;
1217     } else if (!IsCompAssign)
1218       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1219     return RHSType;
1220   } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1221     // The two types are different widths; if we are here, that
1222     // means the signed type is larger than the unsigned type, so
1223     // use the signed type.
1224     if (LHSSigned) {
1225       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1226       return LHSType;
1227     } else if (!IsCompAssign)
1228       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1229     return RHSType;
1230   } else {
1231     // The signed type is higher-ranked than the unsigned type,
1232     // but isn't actually any bigger (like unsigned int and long
1233     // on most 32-bit systems).  Use the unsigned type corresponding
1234     // to the signed type.
1235     QualType result =
1236       S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1237     RHS = (*doRHSCast)(S, RHS.get(), result);
1238     if (!IsCompAssign)
1239       LHS = (*doLHSCast)(S, LHS.get(), result);
1240     return result;
1241   }
1242 }
1243 
1244 /// Handle conversions with GCC complex int extension.  Helper function
1245 /// of UsualArithmeticConversions()
1246 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1247                                            ExprResult &RHS, QualType LHSType,
1248                                            QualType RHSType,
1249                                            bool IsCompAssign) {
1250   const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1251   const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1252 
1253   if (LHSComplexInt && RHSComplexInt) {
1254     QualType LHSEltType = LHSComplexInt->getElementType();
1255     QualType RHSEltType = RHSComplexInt->getElementType();
1256     QualType ScalarType =
1257       handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1258         (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1259 
1260     return S.Context.getComplexType(ScalarType);
1261   }
1262 
1263   if (LHSComplexInt) {
1264     QualType LHSEltType = LHSComplexInt->getElementType();
1265     QualType ScalarType =
1266       handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1267         (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1268     QualType ComplexType = S.Context.getComplexType(ScalarType);
1269     RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1270                               CK_IntegralRealToComplex);
1271 
1272     return ComplexType;
1273   }
1274 
1275   assert(RHSComplexInt);
1276 
1277   QualType RHSEltType = RHSComplexInt->getElementType();
1278   QualType ScalarType =
1279     handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1280       (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1281   QualType ComplexType = S.Context.getComplexType(ScalarType);
1282 
1283   if (!IsCompAssign)
1284     LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1285                               CK_IntegralRealToComplex);
1286   return ComplexType;
1287 }
1288 
1289 /// Return the rank of a given fixed point or integer type. The value itself
1290 /// doesn't matter, but the values must be increasing with proper increasing
1291 /// rank as described in N1169 4.1.1.
1292 static unsigned GetFixedPointRank(QualType Ty) {
1293   const auto *BTy = Ty->getAs<BuiltinType>();
1294   assert(BTy && "Expected a builtin type.");
1295 
1296   switch (BTy->getKind()) {
1297   case BuiltinType::ShortFract:
1298   case BuiltinType::UShortFract:
1299   case BuiltinType::SatShortFract:
1300   case BuiltinType::SatUShortFract:
1301     return 1;
1302   case BuiltinType::Fract:
1303   case BuiltinType::UFract:
1304   case BuiltinType::SatFract:
1305   case BuiltinType::SatUFract:
1306     return 2;
1307   case BuiltinType::LongFract:
1308   case BuiltinType::ULongFract:
1309   case BuiltinType::SatLongFract:
1310   case BuiltinType::SatULongFract:
1311     return 3;
1312   case BuiltinType::ShortAccum:
1313   case BuiltinType::UShortAccum:
1314   case BuiltinType::SatShortAccum:
1315   case BuiltinType::SatUShortAccum:
1316     return 4;
1317   case BuiltinType::Accum:
1318   case BuiltinType::UAccum:
1319   case BuiltinType::SatAccum:
1320   case BuiltinType::SatUAccum:
1321     return 5;
1322   case BuiltinType::LongAccum:
1323   case BuiltinType::ULongAccum:
1324   case BuiltinType::SatLongAccum:
1325   case BuiltinType::SatULongAccum:
1326     return 6;
1327   default:
1328     if (BTy->isInteger())
1329       return 0;
1330     llvm_unreachable("Unexpected fixed point or integer type");
1331   }
1332 }
1333 
1334 /// handleFixedPointConversion - Fixed point operations between fixed
1335 /// point types and integers or other fixed point types do not fall under
1336 /// usual arithmetic conversion since these conversions could result in loss
1337 /// of precsision (N1169 4.1.4). These operations should be calculated with
1338 /// the full precision of their result type (N1169 4.1.6.2.1).
1339 static QualType handleFixedPointConversion(Sema &S, QualType LHSTy,
1340                                            QualType RHSTy) {
1341   assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) &&
1342          "Expected at least one of the operands to be a fixed point type");
1343   assert((LHSTy->isFixedPointOrIntegerType() ||
1344           RHSTy->isFixedPointOrIntegerType()) &&
1345          "Special fixed point arithmetic operation conversions are only "
1346          "applied to ints or other fixed point types");
1347 
1348   // If one operand has signed fixed-point type and the other operand has
1349   // unsigned fixed-point type, then the unsigned fixed-point operand is
1350   // converted to its corresponding signed fixed-point type and the resulting
1351   // type is the type of the converted operand.
1352   if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType())
1353     LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy);
1354   else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType())
1355     RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy);
1356 
1357   // The result type is the type with the highest rank, whereby a fixed-point
1358   // conversion rank is always greater than an integer conversion rank; if the
1359   // type of either of the operands is a saturating fixedpoint type, the result
1360   // type shall be the saturating fixed-point type corresponding to the type
1361   // with the highest rank; the resulting value is converted (taking into
1362   // account rounding and overflow) to the precision of the resulting type.
1363   // Same ranks between signed and unsigned types are resolved earlier, so both
1364   // types are either signed or both unsigned at this point.
1365   unsigned LHSTyRank = GetFixedPointRank(LHSTy);
1366   unsigned RHSTyRank = GetFixedPointRank(RHSTy);
1367 
1368   QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy;
1369 
1370   if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType())
1371     ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy);
1372 
1373   return ResultTy;
1374 }
1375 
1376 /// Check that the usual arithmetic conversions can be performed on this pair of
1377 /// expressions that might be of enumeration type.
1378 static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS,
1379                                            SourceLocation Loc,
1380                                            Sema::ArithConvKind ACK) {
1381   // C++2a [expr.arith.conv]p1:
1382   //   If one operand is of enumeration type and the other operand is of a
1383   //   different enumeration type or a floating-point type, this behavior is
1384   //   deprecated ([depr.arith.conv.enum]).
1385   //
1386   // Warn on this in all language modes. Produce a deprecation warning in C++20.
1387   // Eventually we will presumably reject these cases (in C++23 onwards?).
1388   QualType L = LHS->getType(), R = RHS->getType();
1389   bool LEnum = L->isUnscopedEnumerationType(),
1390        REnum = R->isUnscopedEnumerationType();
1391   bool IsCompAssign = ACK == Sema::ACK_CompAssign;
1392   if ((!IsCompAssign && LEnum && R->isFloatingType()) ||
1393       (REnum && L->isFloatingType())) {
1394     S.Diag(Loc, S.getLangOpts().CPlusPlus2a
1395                     ? diag::warn_arith_conv_enum_float_cxx2a
1396                     : diag::warn_arith_conv_enum_float)
1397         << LHS->getSourceRange() << RHS->getSourceRange()
1398         << (int)ACK << LEnum << L << R;
1399   } else if (!IsCompAssign && LEnum && REnum &&
1400              !S.Context.hasSameUnqualifiedType(L, R)) {
1401     unsigned DiagID;
1402     if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() ||
1403         !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) {
1404       // If either enumeration type is unnamed, it's less likely that the
1405       // user cares about this, but this situation is still deprecated in
1406       // C++2a. Use a different warning group.
1407       DiagID = S.getLangOpts().CPlusPlus2a
1408                     ? diag::warn_arith_conv_mixed_anon_enum_types_cxx2a
1409                     : diag::warn_arith_conv_mixed_anon_enum_types;
1410     } else if (ACK == Sema::ACK_Conditional) {
1411       // Conditional expressions are separated out because they have
1412       // historically had a different warning flag.
1413       DiagID = S.getLangOpts().CPlusPlus2a
1414                    ? diag::warn_conditional_mixed_enum_types_cxx2a
1415                    : diag::warn_conditional_mixed_enum_types;
1416     } else if (ACK == Sema::ACK_Comparison) {
1417       // Comparison expressions are separated out because they have
1418       // historically had a different warning flag.
1419       DiagID = S.getLangOpts().CPlusPlus2a
1420                    ? diag::warn_comparison_mixed_enum_types_cxx2a
1421                    : diag::warn_comparison_mixed_enum_types;
1422     } else {
1423       DiagID = S.getLangOpts().CPlusPlus2a
1424                    ? diag::warn_arith_conv_mixed_enum_types_cxx2a
1425                    : diag::warn_arith_conv_mixed_enum_types;
1426     }
1427     S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
1428                         << (int)ACK << L << R;
1429   }
1430 }
1431 
1432 /// UsualArithmeticConversions - Performs various conversions that are common to
1433 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1434 /// routine returns the first non-arithmetic type found. The client is
1435 /// responsible for emitting appropriate error diagnostics.
1436 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1437                                           SourceLocation Loc,
1438                                           ArithConvKind ACK) {
1439   checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK);
1440 
1441   if (ACK != ACK_CompAssign) {
1442     LHS = UsualUnaryConversions(LHS.get());
1443     if (LHS.isInvalid())
1444       return QualType();
1445   }
1446 
1447   RHS = UsualUnaryConversions(RHS.get());
1448   if (RHS.isInvalid())
1449     return QualType();
1450 
1451   // For conversion purposes, we ignore any qualifiers.
1452   // For example, "const float" and "float" are equivalent.
1453   QualType LHSType =
1454     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1455   QualType RHSType =
1456     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1457 
1458   // For conversion purposes, we ignore any atomic qualifier on the LHS.
1459   if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1460     LHSType = AtomicLHS->getValueType();
1461 
1462   // If both types are identical, no conversion is needed.
1463   if (LHSType == RHSType)
1464     return LHSType;
1465 
1466   // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1467   // The caller can deal with this (e.g. pointer + int).
1468   if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1469     return QualType();
1470 
1471   // Apply unary and bitfield promotions to the LHS's type.
1472   QualType LHSUnpromotedType = LHSType;
1473   if (LHSType->isPromotableIntegerType())
1474     LHSType = Context.getPromotedIntegerType(LHSType);
1475   QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1476   if (!LHSBitfieldPromoteTy.isNull())
1477     LHSType = LHSBitfieldPromoteTy;
1478   if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign)
1479     LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1480 
1481   // If both types are identical, no conversion is needed.
1482   if (LHSType == RHSType)
1483     return LHSType;
1484 
1485   // At this point, we have two different arithmetic types.
1486 
1487   // Diagnose attempts to convert between __float128 and long double where
1488   // such conversions currently can't be handled.
1489   if (unsupportedTypeConversion(*this, LHSType, RHSType))
1490     return QualType();
1491 
1492   // Handle complex types first (C99 6.3.1.8p1).
1493   if (LHSType->isComplexType() || RHSType->isComplexType())
1494     return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1495                                         ACK == ACK_CompAssign);
1496 
1497   // Now handle "real" floating types (i.e. float, double, long double).
1498   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1499     return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1500                                  ACK == ACK_CompAssign);
1501 
1502   // Handle GCC complex int extension.
1503   if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1504     return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1505                                       ACK == ACK_CompAssign);
1506 
1507   if (LHSType->isFixedPointType() || RHSType->isFixedPointType())
1508     return handleFixedPointConversion(*this, LHSType, RHSType);
1509 
1510   // Finally, we have two differing integer types.
1511   return handleIntegerConversion<doIntegralCast, doIntegralCast>
1512            (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign);
1513 }
1514 
1515 //===----------------------------------------------------------------------===//
1516 //  Semantic Analysis for various Expression Types
1517 //===----------------------------------------------------------------------===//
1518 
1519 
1520 ExprResult
1521 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1522                                 SourceLocation DefaultLoc,
1523                                 SourceLocation RParenLoc,
1524                                 Expr *ControllingExpr,
1525                                 ArrayRef<ParsedType> ArgTypes,
1526                                 ArrayRef<Expr *> ArgExprs) {
1527   unsigned NumAssocs = ArgTypes.size();
1528   assert(NumAssocs == ArgExprs.size());
1529 
1530   TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1531   for (unsigned i = 0; i < NumAssocs; ++i) {
1532     if (ArgTypes[i])
1533       (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1534     else
1535       Types[i] = nullptr;
1536   }
1537 
1538   ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1539                                              ControllingExpr,
1540                                              llvm::makeArrayRef(Types, NumAssocs),
1541                                              ArgExprs);
1542   delete [] Types;
1543   return ER;
1544 }
1545 
1546 ExprResult
1547 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1548                                  SourceLocation DefaultLoc,
1549                                  SourceLocation RParenLoc,
1550                                  Expr *ControllingExpr,
1551                                  ArrayRef<TypeSourceInfo *> Types,
1552                                  ArrayRef<Expr *> Exprs) {
1553   unsigned NumAssocs = Types.size();
1554   assert(NumAssocs == Exprs.size());
1555 
1556   // Decay and strip qualifiers for the controlling expression type, and handle
1557   // placeholder type replacement. See committee discussion from WG14 DR423.
1558   {
1559     EnterExpressionEvaluationContext Unevaluated(
1560         *this, Sema::ExpressionEvaluationContext::Unevaluated);
1561     ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
1562     if (R.isInvalid())
1563       return ExprError();
1564     ControllingExpr = R.get();
1565   }
1566 
1567   // The controlling expression is an unevaluated operand, so side effects are
1568   // likely unintended.
1569   if (!inTemplateInstantiation() &&
1570       ControllingExpr->HasSideEffects(Context, false))
1571     Diag(ControllingExpr->getExprLoc(),
1572          diag::warn_side_effects_unevaluated_context);
1573 
1574   bool TypeErrorFound = false,
1575        IsResultDependent = ControllingExpr->isTypeDependent(),
1576        ContainsUnexpandedParameterPack
1577          = ControllingExpr->containsUnexpandedParameterPack();
1578 
1579   for (unsigned i = 0; i < NumAssocs; ++i) {
1580     if (Exprs[i]->containsUnexpandedParameterPack())
1581       ContainsUnexpandedParameterPack = true;
1582 
1583     if (Types[i]) {
1584       if (Types[i]->getType()->containsUnexpandedParameterPack())
1585         ContainsUnexpandedParameterPack = true;
1586 
1587       if (Types[i]->getType()->isDependentType()) {
1588         IsResultDependent = true;
1589       } else {
1590         // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1591         // complete object type other than a variably modified type."
1592         unsigned D = 0;
1593         if (Types[i]->getType()->isIncompleteType())
1594           D = diag::err_assoc_type_incomplete;
1595         else if (!Types[i]->getType()->isObjectType())
1596           D = diag::err_assoc_type_nonobject;
1597         else if (Types[i]->getType()->isVariablyModifiedType())
1598           D = diag::err_assoc_type_variably_modified;
1599 
1600         if (D != 0) {
1601           Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1602             << Types[i]->getTypeLoc().getSourceRange()
1603             << Types[i]->getType();
1604           TypeErrorFound = true;
1605         }
1606 
1607         // C11 6.5.1.1p2 "No two generic associations in the same generic
1608         // selection shall specify compatible types."
1609         for (unsigned j = i+1; j < NumAssocs; ++j)
1610           if (Types[j] && !Types[j]->getType()->isDependentType() &&
1611               Context.typesAreCompatible(Types[i]->getType(),
1612                                          Types[j]->getType())) {
1613             Diag(Types[j]->getTypeLoc().getBeginLoc(),
1614                  diag::err_assoc_compatible_types)
1615               << Types[j]->getTypeLoc().getSourceRange()
1616               << Types[j]->getType()
1617               << Types[i]->getType();
1618             Diag(Types[i]->getTypeLoc().getBeginLoc(),
1619                  diag::note_compat_assoc)
1620               << Types[i]->getTypeLoc().getSourceRange()
1621               << Types[i]->getType();
1622             TypeErrorFound = true;
1623           }
1624       }
1625     }
1626   }
1627   if (TypeErrorFound)
1628     return ExprError();
1629 
1630   // If we determined that the generic selection is result-dependent, don't
1631   // try to compute the result expression.
1632   if (IsResultDependent)
1633     return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types,
1634                                         Exprs, DefaultLoc, RParenLoc,
1635                                         ContainsUnexpandedParameterPack);
1636 
1637   SmallVector<unsigned, 1> CompatIndices;
1638   unsigned DefaultIndex = -1U;
1639   for (unsigned i = 0; i < NumAssocs; ++i) {
1640     if (!Types[i])
1641       DefaultIndex = i;
1642     else if (Context.typesAreCompatible(ControllingExpr->getType(),
1643                                         Types[i]->getType()))
1644       CompatIndices.push_back(i);
1645   }
1646 
1647   // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1648   // type compatible with at most one of the types named in its generic
1649   // association list."
1650   if (CompatIndices.size() > 1) {
1651     // We strip parens here because the controlling expression is typically
1652     // parenthesized in macro definitions.
1653     ControllingExpr = ControllingExpr->IgnoreParens();
1654     Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match)
1655         << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1656         << (unsigned)CompatIndices.size();
1657     for (unsigned I : CompatIndices) {
1658       Diag(Types[I]->getTypeLoc().getBeginLoc(),
1659            diag::note_compat_assoc)
1660         << Types[I]->getTypeLoc().getSourceRange()
1661         << Types[I]->getType();
1662     }
1663     return ExprError();
1664   }
1665 
1666   // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1667   // its controlling expression shall have type compatible with exactly one of
1668   // the types named in its generic association list."
1669   if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1670     // We strip parens here because the controlling expression is typically
1671     // parenthesized in macro definitions.
1672     ControllingExpr = ControllingExpr->IgnoreParens();
1673     Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match)
1674         << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1675     return ExprError();
1676   }
1677 
1678   // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1679   // type name that is compatible with the type of the controlling expression,
1680   // then the result expression of the generic selection is the expression
1681   // in that generic association. Otherwise, the result expression of the
1682   // generic selection is the expression in the default generic association."
1683   unsigned ResultIndex =
1684     CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1685 
1686   return GenericSelectionExpr::Create(
1687       Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1688       ContainsUnexpandedParameterPack, ResultIndex);
1689 }
1690 
1691 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1692 /// location of the token and the offset of the ud-suffix within it.
1693 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1694                                      unsigned Offset) {
1695   return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1696                                         S.getLangOpts());
1697 }
1698 
1699 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1700 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
1701 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1702                                                  IdentifierInfo *UDSuffix,
1703                                                  SourceLocation UDSuffixLoc,
1704                                                  ArrayRef<Expr*> Args,
1705                                                  SourceLocation LitEndLoc) {
1706   assert(Args.size() <= 2 && "too many arguments for literal operator");
1707 
1708   QualType ArgTy[2];
1709   for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1710     ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1711     if (ArgTy[ArgIdx]->isArrayType())
1712       ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1713   }
1714 
1715   DeclarationName OpName =
1716     S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1717   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1718   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1719 
1720   LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1721   if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1722                               /*AllowRaw*/ false, /*AllowTemplate*/ false,
1723                               /*AllowStringTemplate*/ false,
1724                               /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
1725     return ExprError();
1726 
1727   return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1728 }
1729 
1730 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1731 /// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
1732 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1733 /// multiple tokens.  However, the common case is that StringToks points to one
1734 /// string.
1735 ///
1736 ExprResult
1737 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
1738   assert(!StringToks.empty() && "Must have at least one string!");
1739 
1740   StringLiteralParser Literal(StringToks, PP);
1741   if (Literal.hadError)
1742     return ExprError();
1743 
1744   SmallVector<SourceLocation, 4> StringTokLocs;
1745   for (const Token &Tok : StringToks)
1746     StringTokLocs.push_back(Tok.getLocation());
1747 
1748   QualType CharTy = Context.CharTy;
1749   StringLiteral::StringKind Kind = StringLiteral::Ascii;
1750   if (Literal.isWide()) {
1751     CharTy = Context.getWideCharType();
1752     Kind = StringLiteral::Wide;
1753   } else if (Literal.isUTF8()) {
1754     if (getLangOpts().Char8)
1755       CharTy = Context.Char8Ty;
1756     Kind = StringLiteral::UTF8;
1757   } else if (Literal.isUTF16()) {
1758     CharTy = Context.Char16Ty;
1759     Kind = StringLiteral::UTF16;
1760   } else if (Literal.isUTF32()) {
1761     CharTy = Context.Char32Ty;
1762     Kind = StringLiteral::UTF32;
1763   } else if (Literal.isPascal()) {
1764     CharTy = Context.UnsignedCharTy;
1765   }
1766 
1767   // Warn on initializing an array of char from a u8 string literal; this
1768   // becomes ill-formed in C++2a.
1769   if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus2a &&
1770       !getLangOpts().Char8 && Kind == StringLiteral::UTF8) {
1771     Diag(StringTokLocs.front(), diag::warn_cxx2a_compat_utf8_string);
1772 
1773     // Create removals for all 'u8' prefixes in the string literal(s). This
1774     // ensures C++2a compatibility (but may change the program behavior when
1775     // built by non-Clang compilers for which the execution character set is
1776     // not always UTF-8).
1777     auto RemovalDiag = PDiag(diag::note_cxx2a_compat_utf8_string_remove_u8);
1778     SourceLocation RemovalDiagLoc;
1779     for (const Token &Tok : StringToks) {
1780       if (Tok.getKind() == tok::utf8_string_literal) {
1781         if (RemovalDiagLoc.isInvalid())
1782           RemovalDiagLoc = Tok.getLocation();
1783         RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange(
1784             Tok.getLocation(),
1785             Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2,
1786                                            getSourceManager(), getLangOpts())));
1787       }
1788     }
1789     Diag(RemovalDiagLoc, RemovalDiag);
1790   }
1791 
1792   QualType StrTy =
1793       Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars());
1794 
1795   // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1796   StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1797                                              Kind, Literal.Pascal, StrTy,
1798                                              &StringTokLocs[0],
1799                                              StringTokLocs.size());
1800   if (Literal.getUDSuffix().empty())
1801     return Lit;
1802 
1803   // We're building a user-defined literal.
1804   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1805   SourceLocation UDSuffixLoc =
1806     getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1807                    Literal.getUDSuffixOffset());
1808 
1809   // Make sure we're allowed user-defined literals here.
1810   if (!UDLScope)
1811     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1812 
1813   // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1814   //   operator "" X (str, len)
1815   QualType SizeType = Context.getSizeType();
1816 
1817   DeclarationName OpName =
1818     Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1819   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1820   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1821 
1822   QualType ArgTy[] = {
1823     Context.getArrayDecayedType(StrTy), SizeType
1824   };
1825 
1826   LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1827   switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1828                                 /*AllowRaw*/ false, /*AllowTemplate*/ false,
1829                                 /*AllowStringTemplate*/ true,
1830                                 /*DiagnoseMissing*/ true)) {
1831 
1832   case LOLR_Cooked: {
1833     llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1834     IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1835                                                     StringTokLocs[0]);
1836     Expr *Args[] = { Lit, LenArg };
1837 
1838     return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1839   }
1840 
1841   case LOLR_StringTemplate: {
1842     TemplateArgumentListInfo ExplicitArgs;
1843 
1844     unsigned CharBits = Context.getIntWidth(CharTy);
1845     bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1846     llvm::APSInt Value(CharBits, CharIsUnsigned);
1847 
1848     TemplateArgument TypeArg(CharTy);
1849     TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1850     ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1851 
1852     for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1853       Value = Lit->getCodeUnit(I);
1854       TemplateArgument Arg(Context, Value, CharTy);
1855       TemplateArgumentLocInfo ArgInfo;
1856       ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1857     }
1858     return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1859                                     &ExplicitArgs);
1860   }
1861   case LOLR_Raw:
1862   case LOLR_Template:
1863   case LOLR_ErrorNoDiagnostic:
1864     llvm_unreachable("unexpected literal operator lookup result");
1865   case LOLR_Error:
1866     return ExprError();
1867   }
1868   llvm_unreachable("unexpected literal operator lookup result");
1869 }
1870 
1871 DeclRefExpr *
1872 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1873                        SourceLocation Loc,
1874                        const CXXScopeSpec *SS) {
1875   DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1876   return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1877 }
1878 
1879 DeclRefExpr *
1880 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1881                        const DeclarationNameInfo &NameInfo,
1882                        const CXXScopeSpec *SS, NamedDecl *FoundD,
1883                        SourceLocation TemplateKWLoc,
1884                        const TemplateArgumentListInfo *TemplateArgs) {
1885   NestedNameSpecifierLoc NNS =
1886       SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc();
1887   return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc,
1888                           TemplateArgs);
1889 }
1890 
1891 NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) {
1892   // A declaration named in an unevaluated operand never constitutes an odr-use.
1893   if (isUnevaluatedContext())
1894     return NOUR_Unevaluated;
1895 
1896   // C++2a [basic.def.odr]p4:
1897   //   A variable x whose name appears as a potentially-evaluated expression e
1898   //   is odr-used by e unless [...] x is a reference that is usable in
1899   //   constant expressions.
1900   if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
1901     if (VD->getType()->isReferenceType() &&
1902         !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) &&
1903         VD->isUsableInConstantExpressions(Context))
1904       return NOUR_Constant;
1905   }
1906 
1907   // All remaining non-variable cases constitute an odr-use. For variables, we
1908   // need to wait and see how the expression is used.
1909   return NOUR_None;
1910 }
1911 
1912 /// BuildDeclRefExpr - Build an expression that references a
1913 /// declaration that does not require a closure capture.
1914 DeclRefExpr *
1915 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1916                        const DeclarationNameInfo &NameInfo,
1917                        NestedNameSpecifierLoc NNS, NamedDecl *FoundD,
1918                        SourceLocation TemplateKWLoc,
1919                        const TemplateArgumentListInfo *TemplateArgs) {
1920   bool RefersToCapturedVariable =
1921       isa<VarDecl>(D) &&
1922       NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
1923 
1924   DeclRefExpr *E = DeclRefExpr::Create(
1925       Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty,
1926       VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D));
1927   MarkDeclRefReferenced(E);
1928 
1929   // C++ [except.spec]p17:
1930   //   An exception-specification is considered to be needed when:
1931   //   - in an expression, the function is the unique lookup result or
1932   //     the selected member of a set of overloaded functions.
1933   //
1934   // We delay doing this until after we've built the function reference and
1935   // marked it as used so that:
1936   //  a) if the function is defaulted, we get errors from defining it before /
1937   //     instead of errors from computing its exception specification, and
1938   //  b) if the function is a defaulted comparison, we can use the body we
1939   //     build when defining it as input to the exception specification
1940   //     computation rather than computing a new body.
1941   if (auto *FPT = Ty->getAs<FunctionProtoType>()) {
1942     if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
1943       if (auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT))
1944         E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers()));
1945     }
1946   }
1947 
1948   if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
1949       Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() &&
1950       !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc()))
1951     getCurFunction()->recordUseOfWeak(E);
1952 
1953   FieldDecl *FD = dyn_cast<FieldDecl>(D);
1954   if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
1955     FD = IFD->getAnonField();
1956   if (FD) {
1957     UnusedPrivateFields.remove(FD);
1958     // Just in case we're building an illegal pointer-to-member.
1959     if (FD->isBitField())
1960       E->setObjectKind(OK_BitField);
1961   }
1962 
1963   // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
1964   // designates a bit-field.
1965   if (auto *BD = dyn_cast<BindingDecl>(D))
1966     if (auto *BE = BD->getBinding())
1967       E->setObjectKind(BE->getObjectKind());
1968 
1969   return E;
1970 }
1971 
1972 /// Decomposes the given name into a DeclarationNameInfo, its location, and
1973 /// possibly a list of template arguments.
1974 ///
1975 /// If this produces template arguments, it is permitted to call
1976 /// DecomposeTemplateName.
1977 ///
1978 /// This actually loses a lot of source location information for
1979 /// non-standard name kinds; we should consider preserving that in
1980 /// some way.
1981 void
1982 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1983                              TemplateArgumentListInfo &Buffer,
1984                              DeclarationNameInfo &NameInfo,
1985                              const TemplateArgumentListInfo *&TemplateArgs) {
1986   if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) {
1987     Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1988     Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1989 
1990     ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
1991                                        Id.TemplateId->NumArgs);
1992     translateTemplateArguments(TemplateArgsPtr, Buffer);
1993 
1994     TemplateName TName = Id.TemplateId->Template.get();
1995     SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1996     NameInfo = Context.getNameForTemplate(TName, TNameLoc);
1997     TemplateArgs = &Buffer;
1998   } else {
1999     NameInfo = GetNameFromUnqualifiedId(Id);
2000     TemplateArgs = nullptr;
2001   }
2002 }
2003 
2004 static void emitEmptyLookupTypoDiagnostic(
2005     const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
2006     DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
2007     unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
2008   DeclContext *Ctx =
2009       SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
2010   if (!TC) {
2011     // Emit a special diagnostic for failed member lookups.
2012     // FIXME: computing the declaration context might fail here (?)
2013     if (Ctx)
2014       SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
2015                                                  << SS.getRange();
2016     else
2017       SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
2018     return;
2019   }
2020 
2021   std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
2022   bool DroppedSpecifier =
2023       TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
2024   unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
2025                         ? diag::note_implicit_param_decl
2026                         : diag::note_previous_decl;
2027   if (!Ctx)
2028     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
2029                          SemaRef.PDiag(NoteID));
2030   else
2031     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
2032                                  << Typo << Ctx << DroppedSpecifier
2033                                  << SS.getRange(),
2034                          SemaRef.PDiag(NoteID));
2035 }
2036 
2037 /// Diagnose an empty lookup.
2038 ///
2039 /// \return false if new lookup candidates were found
2040 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
2041                                CorrectionCandidateCallback &CCC,
2042                                TemplateArgumentListInfo *ExplicitTemplateArgs,
2043                                ArrayRef<Expr *> Args, TypoExpr **Out) {
2044   DeclarationName Name = R.getLookupName();
2045 
2046   unsigned diagnostic = diag::err_undeclared_var_use;
2047   unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
2048   if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
2049       Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
2050       Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
2051     diagnostic = diag::err_undeclared_use;
2052     diagnostic_suggest = diag::err_undeclared_use_suggest;
2053   }
2054 
2055   // If the original lookup was an unqualified lookup, fake an
2056   // unqualified lookup.  This is useful when (for example) the
2057   // original lookup would not have found something because it was a
2058   // dependent name.
2059   DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
2060   while (DC) {
2061     if (isa<CXXRecordDecl>(DC)) {
2062       LookupQualifiedName(R, DC);
2063 
2064       if (!R.empty()) {
2065         // Don't give errors about ambiguities in this lookup.
2066         R.suppressDiagnostics();
2067 
2068         // During a default argument instantiation the CurContext points
2069         // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
2070         // function parameter list, hence add an explicit check.
2071         bool isDefaultArgument =
2072             !CodeSynthesisContexts.empty() &&
2073             CodeSynthesisContexts.back().Kind ==
2074                 CodeSynthesisContext::DefaultFunctionArgumentInstantiation;
2075         CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
2076         bool isInstance = CurMethod &&
2077                           CurMethod->isInstance() &&
2078                           DC == CurMethod->getParent() && !isDefaultArgument;
2079 
2080         // Give a code modification hint to insert 'this->'.
2081         // TODO: fixit for inserting 'Base<T>::' in the other cases.
2082         // Actually quite difficult!
2083         if (getLangOpts().MSVCCompat)
2084           diagnostic = diag::ext_found_via_dependent_bases_lookup;
2085         if (isInstance) {
2086           Diag(R.getNameLoc(), diagnostic) << Name
2087             << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
2088           CheckCXXThisCapture(R.getNameLoc());
2089         } else {
2090           Diag(R.getNameLoc(), diagnostic) << Name;
2091         }
2092 
2093         // Do we really want to note all of these?
2094         for (NamedDecl *D : R)
2095           Diag(D->getLocation(), diag::note_dependent_var_use);
2096 
2097         // Return true if we are inside a default argument instantiation
2098         // and the found name refers to an instance member function, otherwise
2099         // the function calling DiagnoseEmptyLookup will try to create an
2100         // implicit member call and this is wrong for default argument.
2101         if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
2102           Diag(R.getNameLoc(), diag::err_member_call_without_object);
2103           return true;
2104         }
2105 
2106         // Tell the callee to try to recover.
2107         return false;
2108       }
2109 
2110       R.clear();
2111     }
2112 
2113     DC = DC->getLookupParent();
2114   }
2115 
2116   // We didn't find anything, so try to correct for a typo.
2117   TypoCorrection Corrected;
2118   if (S && Out) {
2119     SourceLocation TypoLoc = R.getNameLoc();
2120     assert(!ExplicitTemplateArgs &&
2121            "Diagnosing an empty lookup with explicit template args!");
2122     *Out = CorrectTypoDelayed(
2123         R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
2124         [=](const TypoCorrection &TC) {
2125           emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
2126                                         diagnostic, diagnostic_suggest);
2127         },
2128         nullptr, CTK_ErrorRecovery);
2129     if (*Out)
2130       return true;
2131   } else if (S &&
2132              (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
2133                                       S, &SS, CCC, CTK_ErrorRecovery))) {
2134     std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
2135     bool DroppedSpecifier =
2136         Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
2137     R.setLookupName(Corrected.getCorrection());
2138 
2139     bool AcceptableWithRecovery = false;
2140     bool AcceptableWithoutRecovery = false;
2141     NamedDecl *ND = Corrected.getFoundDecl();
2142     if (ND) {
2143       if (Corrected.isOverloaded()) {
2144         OverloadCandidateSet OCS(R.getNameLoc(),
2145                                  OverloadCandidateSet::CSK_Normal);
2146         OverloadCandidateSet::iterator Best;
2147         for (NamedDecl *CD : Corrected) {
2148           if (FunctionTemplateDecl *FTD =
2149                    dyn_cast<FunctionTemplateDecl>(CD))
2150             AddTemplateOverloadCandidate(
2151                 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
2152                 Args, OCS);
2153           else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
2154             if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
2155               AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
2156                                    Args, OCS);
2157         }
2158         switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
2159         case OR_Success:
2160           ND = Best->FoundDecl;
2161           Corrected.setCorrectionDecl(ND);
2162           break;
2163         default:
2164           // FIXME: Arbitrarily pick the first declaration for the note.
2165           Corrected.setCorrectionDecl(ND);
2166           break;
2167         }
2168       }
2169       R.addDecl(ND);
2170       if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2171         CXXRecordDecl *Record = nullptr;
2172         if (Corrected.getCorrectionSpecifier()) {
2173           const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
2174           Record = Ty->getAsCXXRecordDecl();
2175         }
2176         if (!Record)
2177           Record = cast<CXXRecordDecl>(
2178               ND->getDeclContext()->getRedeclContext());
2179         R.setNamingClass(Record);
2180       }
2181 
2182       auto *UnderlyingND = ND->getUnderlyingDecl();
2183       AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2184                                isa<FunctionTemplateDecl>(UnderlyingND);
2185       // FIXME: If we ended up with a typo for a type name or
2186       // Objective-C class name, we're in trouble because the parser
2187       // is in the wrong place to recover. Suggest the typo
2188       // correction, but don't make it a fix-it since we're not going
2189       // to recover well anyway.
2190       AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) ||
2191                                   getAsTypeTemplateDecl(UnderlyingND) ||
2192                                   isa<ObjCInterfaceDecl>(UnderlyingND);
2193     } else {
2194       // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2195       // because we aren't able to recover.
2196       AcceptableWithoutRecovery = true;
2197     }
2198 
2199     if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2200       unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2201                             ? diag::note_implicit_param_decl
2202                             : diag::note_previous_decl;
2203       if (SS.isEmpty())
2204         diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
2205                      PDiag(NoteID), AcceptableWithRecovery);
2206       else
2207         diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
2208                                   << Name << computeDeclContext(SS, false)
2209                                   << DroppedSpecifier << SS.getRange(),
2210                      PDiag(NoteID), AcceptableWithRecovery);
2211 
2212       // Tell the callee whether to try to recover.
2213       return !AcceptableWithRecovery;
2214     }
2215   }
2216   R.clear();
2217 
2218   // Emit a special diagnostic for failed member lookups.
2219   // FIXME: computing the declaration context might fail here (?)
2220   if (!SS.isEmpty()) {
2221     Diag(R.getNameLoc(), diag::err_no_member)
2222       << Name << computeDeclContext(SS, false)
2223       << SS.getRange();
2224     return true;
2225   }
2226 
2227   // Give up, we can't recover.
2228   Diag(R.getNameLoc(), diagnostic) << Name;
2229   return true;
2230 }
2231 
2232 /// In Microsoft mode, if we are inside a template class whose parent class has
2233 /// dependent base classes, and we can't resolve an unqualified identifier, then
2234 /// assume the identifier is a member of a dependent base class.  We can only
2235 /// recover successfully in static methods, instance methods, and other contexts
2236 /// where 'this' is available.  This doesn't precisely match MSVC's
2237 /// instantiation model, but it's close enough.
2238 static Expr *
2239 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
2240                                DeclarationNameInfo &NameInfo,
2241                                SourceLocation TemplateKWLoc,
2242                                const TemplateArgumentListInfo *TemplateArgs) {
2243   // Only try to recover from lookup into dependent bases in static methods or
2244   // contexts where 'this' is available.
2245   QualType ThisType = S.getCurrentThisType();
2246   const CXXRecordDecl *RD = nullptr;
2247   if (!ThisType.isNull())
2248     RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2249   else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2250     RD = MD->getParent();
2251   if (!RD || !RD->hasAnyDependentBases())
2252     return nullptr;
2253 
2254   // Diagnose this as unqualified lookup into a dependent base class.  If 'this'
2255   // is available, suggest inserting 'this->' as a fixit.
2256   SourceLocation Loc = NameInfo.getLoc();
2257   auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2258   DB << NameInfo.getName() << RD;
2259 
2260   if (!ThisType.isNull()) {
2261     DB << FixItHint::CreateInsertion(Loc, "this->");
2262     return CXXDependentScopeMemberExpr::Create(
2263         Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2264         /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2265         /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
2266   }
2267 
2268   // Synthesize a fake NNS that points to the derived class.  This will
2269   // perform name lookup during template instantiation.
2270   CXXScopeSpec SS;
2271   auto *NNS =
2272       NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2273   SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2274   return DependentScopeDeclRefExpr::Create(
2275       Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2276       TemplateArgs);
2277 }
2278 
2279 ExprResult
2280 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2281                         SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2282                         bool HasTrailingLParen, bool IsAddressOfOperand,
2283                         CorrectionCandidateCallback *CCC,
2284                         bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2285   assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2286          "cannot be direct & operand and have a trailing lparen");
2287   if (SS.isInvalid())
2288     return ExprError();
2289 
2290   TemplateArgumentListInfo TemplateArgsBuffer;
2291 
2292   // Decompose the UnqualifiedId into the following data.
2293   DeclarationNameInfo NameInfo;
2294   const TemplateArgumentListInfo *TemplateArgs;
2295   DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2296 
2297   DeclarationName Name = NameInfo.getName();
2298   IdentifierInfo *II = Name.getAsIdentifierInfo();
2299   SourceLocation NameLoc = NameInfo.getLoc();
2300 
2301   if (II && II->isEditorPlaceholder()) {
2302     // FIXME: When typed placeholders are supported we can create a typed
2303     // placeholder expression node.
2304     return ExprError();
2305   }
2306 
2307   // C++ [temp.dep.expr]p3:
2308   //   An id-expression is type-dependent if it contains:
2309   //     -- an identifier that was declared with a dependent type,
2310   //        (note: handled after lookup)
2311   //     -- a template-id that is dependent,
2312   //        (note: handled in BuildTemplateIdExpr)
2313   //     -- a conversion-function-id that specifies a dependent type,
2314   //     -- a nested-name-specifier that contains a class-name that
2315   //        names a dependent type.
2316   // Determine whether this is a member of an unknown specialization;
2317   // we need to handle these differently.
2318   bool DependentID = false;
2319   if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2320       Name.getCXXNameType()->isDependentType()) {
2321     DependentID = true;
2322   } else if (SS.isSet()) {
2323     if (DeclContext *DC = computeDeclContext(SS, false)) {
2324       if (RequireCompleteDeclContext(SS, DC))
2325         return ExprError();
2326     } else {
2327       DependentID = true;
2328     }
2329   }
2330 
2331   if (DependentID)
2332     return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2333                                       IsAddressOfOperand, TemplateArgs);
2334 
2335   // Perform the required lookup.
2336   LookupResult R(*this, NameInfo,
2337                  (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam)
2338                      ? LookupObjCImplicitSelfParam
2339                      : LookupOrdinaryName);
2340   if (TemplateKWLoc.isValid() || TemplateArgs) {
2341     // Lookup the template name again to correctly establish the context in
2342     // which it was found. This is really unfortunate as we already did the
2343     // lookup to determine that it was a template name in the first place. If
2344     // this becomes a performance hit, we can work harder to preserve those
2345     // results until we get here but it's likely not worth it.
2346     bool MemberOfUnknownSpecialization;
2347     AssumedTemplateKind AssumedTemplate;
2348     if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2349                            MemberOfUnknownSpecialization, TemplateKWLoc,
2350                            &AssumedTemplate))
2351       return ExprError();
2352 
2353     if (MemberOfUnknownSpecialization ||
2354         (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2355       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2356                                         IsAddressOfOperand, TemplateArgs);
2357   } else {
2358     bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2359     LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2360 
2361     // If the result might be in a dependent base class, this is a dependent
2362     // id-expression.
2363     if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2364       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2365                                         IsAddressOfOperand, TemplateArgs);
2366 
2367     // If this reference is in an Objective-C method, then we need to do
2368     // some special Objective-C lookup, too.
2369     if (IvarLookupFollowUp) {
2370       ExprResult E(LookupInObjCMethod(R, S, II, true));
2371       if (E.isInvalid())
2372         return ExprError();
2373 
2374       if (Expr *Ex = E.getAs<Expr>())
2375         return Ex;
2376     }
2377   }
2378 
2379   if (R.isAmbiguous())
2380     return ExprError();
2381 
2382   // This could be an implicitly declared function reference (legal in C90,
2383   // extension in C99, forbidden in C++).
2384   if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2385     NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2386     if (D) R.addDecl(D);
2387   }
2388 
2389   // Determine whether this name might be a candidate for
2390   // argument-dependent lookup.
2391   bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2392 
2393   if (R.empty() && !ADL) {
2394     if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2395       if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2396                                                    TemplateKWLoc, TemplateArgs))
2397         return E;
2398     }
2399 
2400     // Don't diagnose an empty lookup for inline assembly.
2401     if (IsInlineAsmIdentifier)
2402       return ExprError();
2403 
2404     // If this name wasn't predeclared and if this is not a function
2405     // call, diagnose the problem.
2406     TypoExpr *TE = nullptr;
2407     DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep()
2408                                                        : nullptr);
2409     DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;
2410     assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2411            "Typo correction callback misconfigured");
2412     if (CCC) {
2413       // Make sure the callback knows what the typo being diagnosed is.
2414       CCC->setTypoName(II);
2415       if (SS.isValid())
2416         CCC->setTypoNNS(SS.getScopeRep());
2417     }
2418     // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2419     // a template name, but we happen to have always already looked up the name
2420     // before we get here if it must be a template name.
2421     if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr,
2422                             None, &TE)) {
2423       if (TE && KeywordReplacement) {
2424         auto &State = getTypoExprState(TE);
2425         auto BestTC = State.Consumer->getNextCorrection();
2426         if (BestTC.isKeyword()) {
2427           auto *II = BestTC.getCorrectionAsIdentifierInfo();
2428           if (State.DiagHandler)
2429             State.DiagHandler(BestTC);
2430           KeywordReplacement->startToken();
2431           KeywordReplacement->setKind(II->getTokenID());
2432           KeywordReplacement->setIdentifierInfo(II);
2433           KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2434           // Clean up the state associated with the TypoExpr, since it has
2435           // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2436           clearDelayedTypo(TE);
2437           // Signal that a correction to a keyword was performed by returning a
2438           // valid-but-null ExprResult.
2439           return (Expr*)nullptr;
2440         }
2441         State.Consumer->resetCorrectionStream();
2442       }
2443       return TE ? TE : ExprError();
2444     }
2445 
2446     assert(!R.empty() &&
2447            "DiagnoseEmptyLookup returned false but added no results");
2448 
2449     // If we found an Objective-C instance variable, let
2450     // LookupInObjCMethod build the appropriate expression to
2451     // reference the ivar.
2452     if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2453       R.clear();
2454       ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2455       // In a hopelessly buggy code, Objective-C instance variable
2456       // lookup fails and no expression will be built to reference it.
2457       if (!E.isInvalid() && !E.get())
2458         return ExprError();
2459       return E;
2460     }
2461   }
2462 
2463   // This is guaranteed from this point on.
2464   assert(!R.empty() || ADL);
2465 
2466   // Check whether this might be a C++ implicit instance member access.
2467   // C++ [class.mfct.non-static]p3:
2468   //   When an id-expression that is not part of a class member access
2469   //   syntax and not used to form a pointer to member is used in the
2470   //   body of a non-static member function of class X, if name lookup
2471   //   resolves the name in the id-expression to a non-static non-type
2472   //   member of some class C, the id-expression is transformed into a
2473   //   class member access expression using (*this) as the
2474   //   postfix-expression to the left of the . operator.
2475   //
2476   // But we don't actually need to do this for '&' operands if R
2477   // resolved to a function or overloaded function set, because the
2478   // expression is ill-formed if it actually works out to be a
2479   // non-static member function:
2480   //
2481   // C++ [expr.ref]p4:
2482   //   Otherwise, if E1.E2 refers to a non-static member function. . .
2483   //   [t]he expression can be used only as the left-hand operand of a
2484   //   member function call.
2485   //
2486   // There are other safeguards against such uses, but it's important
2487   // to get this right here so that we don't end up making a
2488   // spuriously dependent expression if we're inside a dependent
2489   // instance method.
2490   if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2491     bool MightBeImplicitMember;
2492     if (!IsAddressOfOperand)
2493       MightBeImplicitMember = true;
2494     else if (!SS.isEmpty())
2495       MightBeImplicitMember = false;
2496     else if (R.isOverloadedResult())
2497       MightBeImplicitMember = false;
2498     else if (R.isUnresolvableResult())
2499       MightBeImplicitMember = true;
2500     else
2501       MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2502                               isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2503                               isa<MSPropertyDecl>(R.getFoundDecl());
2504 
2505     if (MightBeImplicitMember)
2506       return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2507                                              R, TemplateArgs, S);
2508   }
2509 
2510   if (TemplateArgs || TemplateKWLoc.isValid()) {
2511 
2512     // In C++1y, if this is a variable template id, then check it
2513     // in BuildTemplateIdExpr().
2514     // The single lookup result must be a variable template declaration.
2515     if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId &&
2516         Id.TemplateId->Kind == TNK_Var_template) {
2517       assert(R.getAsSingle<VarTemplateDecl>() &&
2518              "There should only be one declaration found.");
2519     }
2520 
2521     return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2522   }
2523 
2524   return BuildDeclarationNameExpr(SS, R, ADL);
2525 }
2526 
2527 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2528 /// declaration name, generally during template instantiation.
2529 /// There's a large number of things which don't need to be done along
2530 /// this path.
2531 ExprResult Sema::BuildQualifiedDeclarationNameExpr(
2532     CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2533     bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2534   DeclContext *DC = computeDeclContext(SS, false);
2535   if (!DC)
2536     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2537                                      NameInfo, /*TemplateArgs=*/nullptr);
2538 
2539   if (RequireCompleteDeclContext(SS, DC))
2540     return ExprError();
2541 
2542   LookupResult R(*this, NameInfo, LookupOrdinaryName);
2543   LookupQualifiedName(R, DC);
2544 
2545   if (R.isAmbiguous())
2546     return ExprError();
2547 
2548   if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2549     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2550                                      NameInfo, /*TemplateArgs=*/nullptr);
2551 
2552   if (R.empty()) {
2553     Diag(NameInfo.getLoc(), diag::err_no_member)
2554       << NameInfo.getName() << DC << SS.getRange();
2555     return ExprError();
2556   }
2557 
2558   if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2559     // Diagnose a missing typename if this resolved unambiguously to a type in
2560     // a dependent context.  If we can recover with a type, downgrade this to
2561     // a warning in Microsoft compatibility mode.
2562     unsigned DiagID = diag::err_typename_missing;
2563     if (RecoveryTSI && getLangOpts().MSVCCompat)
2564       DiagID = diag::ext_typename_missing;
2565     SourceLocation Loc = SS.getBeginLoc();
2566     auto D = Diag(Loc, DiagID);
2567     D << SS.getScopeRep() << NameInfo.getName().getAsString()
2568       << SourceRange(Loc, NameInfo.getEndLoc());
2569 
2570     // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2571     // context.
2572     if (!RecoveryTSI)
2573       return ExprError();
2574 
2575     // Only issue the fixit if we're prepared to recover.
2576     D << FixItHint::CreateInsertion(Loc, "typename ");
2577 
2578     // Recover by pretending this was an elaborated type.
2579     QualType Ty = Context.getTypeDeclType(TD);
2580     TypeLocBuilder TLB;
2581     TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2582 
2583     QualType ET = getElaboratedType(ETK_None, SS, Ty);
2584     ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2585     QTL.setElaboratedKeywordLoc(SourceLocation());
2586     QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2587 
2588     *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2589 
2590     return ExprEmpty();
2591   }
2592 
2593   // Defend against this resolving to an implicit member access. We usually
2594   // won't get here if this might be a legitimate a class member (we end up in
2595   // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2596   // a pointer-to-member or in an unevaluated context in C++11.
2597   if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2598     return BuildPossibleImplicitMemberExpr(SS,
2599                                            /*TemplateKWLoc=*/SourceLocation(),
2600                                            R, /*TemplateArgs=*/nullptr, S);
2601 
2602   return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2603 }
2604 
2605 /// The parser has read a name in, and Sema has detected that we're currently
2606 /// inside an ObjC method. Perform some additional checks and determine if we
2607 /// should form a reference to an ivar.
2608 ///
2609 /// Ideally, most of this would be done by lookup, but there's
2610 /// actually quite a lot of extra work involved.
2611 DeclResult Sema::LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S,
2612                                         IdentifierInfo *II) {
2613   SourceLocation Loc = Lookup.getNameLoc();
2614   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2615 
2616   // Check for error condition which is already reported.
2617   if (!CurMethod)
2618     return DeclResult(true);
2619 
2620   // There are two cases to handle here.  1) scoped lookup could have failed,
2621   // in which case we should look for an ivar.  2) scoped lookup could have
2622   // found a decl, but that decl is outside the current instance method (i.e.
2623   // a global variable).  In these two cases, we do a lookup for an ivar with
2624   // this name, if the lookup sucedes, we replace it our current decl.
2625 
2626   // If we're in a class method, we don't normally want to look for
2627   // ivars.  But if we don't find anything else, and there's an
2628   // ivar, that's an error.
2629   bool IsClassMethod = CurMethod->isClassMethod();
2630 
2631   bool LookForIvars;
2632   if (Lookup.empty())
2633     LookForIvars = true;
2634   else if (IsClassMethod)
2635     LookForIvars = false;
2636   else
2637     LookForIvars = (Lookup.isSingleResult() &&
2638                     Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2639   ObjCInterfaceDecl *IFace = nullptr;
2640   if (LookForIvars) {
2641     IFace = CurMethod->getClassInterface();
2642     ObjCInterfaceDecl *ClassDeclared;
2643     ObjCIvarDecl *IV = nullptr;
2644     if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2645       // Diagnose using an ivar in a class method.
2646       if (IsClassMethod) {
2647         Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
2648         return DeclResult(true);
2649       }
2650 
2651       // Diagnose the use of an ivar outside of the declaring class.
2652       if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2653           !declaresSameEntity(ClassDeclared, IFace) &&
2654           !getLangOpts().DebuggerSupport)
2655         Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
2656 
2657       // Success.
2658       return IV;
2659     }
2660   } else if (CurMethod->isInstanceMethod()) {
2661     // We should warn if a local variable hides an ivar.
2662     if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2663       ObjCInterfaceDecl *ClassDeclared;
2664       if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2665         if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2666             declaresSameEntity(IFace, ClassDeclared))
2667           Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2668       }
2669     }
2670   } else if (Lookup.isSingleResult() &&
2671              Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2672     // If accessing a stand-alone ivar in a class method, this is an error.
2673     if (const ObjCIvarDecl *IV =
2674             dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) {
2675       Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
2676       return DeclResult(true);
2677     }
2678   }
2679 
2680   // Didn't encounter an error, didn't find an ivar.
2681   return DeclResult(false);
2682 }
2683 
2684 ExprResult Sema::BuildIvarRefExpr(Scope *S, SourceLocation Loc,
2685                                   ObjCIvarDecl *IV) {
2686   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2687   assert(CurMethod && CurMethod->isInstanceMethod() &&
2688          "should not reference ivar from this context");
2689 
2690   ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
2691   assert(IFace && "should not reference ivar from this context");
2692 
2693   // If we're referencing an invalid decl, just return this as a silent
2694   // error node.  The error diagnostic was already emitted on the decl.
2695   if (IV->isInvalidDecl())
2696     return ExprError();
2697 
2698   // Check if referencing a field with __attribute__((deprecated)).
2699   if (DiagnoseUseOfDecl(IV, Loc))
2700     return ExprError();
2701 
2702   // FIXME: This should use a new expr for a direct reference, don't
2703   // turn this into Self->ivar, just return a BareIVarExpr or something.
2704   IdentifierInfo &II = Context.Idents.get("self");
2705   UnqualifiedId SelfName;
2706   SelfName.setIdentifier(&II, SourceLocation());
2707   SelfName.setKind(UnqualifiedIdKind::IK_ImplicitSelfParam);
2708   CXXScopeSpec SelfScopeSpec;
2709   SourceLocation TemplateKWLoc;
2710   ExprResult SelfExpr =
2711       ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName,
2712                         /*HasTrailingLParen=*/false,
2713                         /*IsAddressOfOperand=*/false);
2714   if (SelfExpr.isInvalid())
2715     return ExprError();
2716 
2717   SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2718   if (SelfExpr.isInvalid())
2719     return ExprError();
2720 
2721   MarkAnyDeclReferenced(Loc, IV, true);
2722 
2723   ObjCMethodFamily MF = CurMethod->getMethodFamily();
2724   if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2725       !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2726     Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2727 
2728   ObjCIvarRefExpr *Result = new (Context)
2729       ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2730                       IV->getLocation(), SelfExpr.get(), true, true);
2731 
2732   if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2733     if (!isUnevaluatedContext() &&
2734         !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2735       getCurFunction()->recordUseOfWeak(Result);
2736   }
2737   if (getLangOpts().ObjCAutoRefCount)
2738     if (const BlockDecl *BD = CurContext->getInnermostBlockDecl())
2739       ImplicitlyRetainedSelfLocs.push_back({Loc, BD});
2740 
2741   return Result;
2742 }
2743 
2744 /// The parser has read a name in, and Sema has detected that we're currently
2745 /// inside an ObjC method. Perform some additional checks and determine if we
2746 /// should form a reference to an ivar. If so, build an expression referencing
2747 /// that ivar.
2748 ExprResult
2749 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2750                          IdentifierInfo *II, bool AllowBuiltinCreation) {
2751   // FIXME: Integrate this lookup step into LookupParsedName.
2752   DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II);
2753   if (Ivar.isInvalid())
2754     return ExprError();
2755   if (Ivar.isUsable())
2756     return BuildIvarRefExpr(S, Lookup.getNameLoc(),
2757                             cast<ObjCIvarDecl>(Ivar.get()));
2758 
2759   if (Lookup.empty() && II && AllowBuiltinCreation)
2760     LookupBuiltin(Lookup);
2761 
2762   // Sentinel value saying that we didn't do anything special.
2763   return ExprResult(false);
2764 }
2765 
2766 /// Cast a base object to a member's actual type.
2767 ///
2768 /// Logically this happens in three phases:
2769 ///
2770 /// * First we cast from the base type to the naming class.
2771 ///   The naming class is the class into which we were looking
2772 ///   when we found the member;  it's the qualifier type if a
2773 ///   qualifier was provided, and otherwise it's the base type.
2774 ///
2775 /// * Next we cast from the naming class to the declaring class.
2776 ///   If the member we found was brought into a class's scope by
2777 ///   a using declaration, this is that class;  otherwise it's
2778 ///   the class declaring the member.
2779 ///
2780 /// * Finally we cast from the declaring class to the "true"
2781 ///   declaring class of the member.  This conversion does not
2782 ///   obey access control.
2783 ExprResult
2784 Sema::PerformObjectMemberConversion(Expr *From,
2785                                     NestedNameSpecifier *Qualifier,
2786                                     NamedDecl *FoundDecl,
2787                                     NamedDecl *Member) {
2788   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2789   if (!RD)
2790     return From;
2791 
2792   QualType DestRecordType;
2793   QualType DestType;
2794   QualType FromRecordType;
2795   QualType FromType = From->getType();
2796   bool PointerConversions = false;
2797   if (isa<FieldDecl>(Member)) {
2798     DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2799     auto FromPtrType = FromType->getAs<PointerType>();
2800     DestRecordType = Context.getAddrSpaceQualType(
2801         DestRecordType, FromPtrType
2802                             ? FromType->getPointeeType().getAddressSpace()
2803                             : FromType.getAddressSpace());
2804 
2805     if (FromPtrType) {
2806       DestType = Context.getPointerType(DestRecordType);
2807       FromRecordType = FromPtrType->getPointeeType();
2808       PointerConversions = true;
2809     } else {
2810       DestType = DestRecordType;
2811       FromRecordType = FromType;
2812     }
2813   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2814     if (Method->isStatic())
2815       return From;
2816 
2817     DestType = Method->getThisType();
2818     DestRecordType = DestType->getPointeeType();
2819 
2820     if (FromType->getAs<PointerType>()) {
2821       FromRecordType = FromType->getPointeeType();
2822       PointerConversions = true;
2823     } else {
2824       FromRecordType = FromType;
2825       DestType = DestRecordType;
2826     }
2827 
2828     LangAS FromAS = FromRecordType.getAddressSpace();
2829     LangAS DestAS = DestRecordType.getAddressSpace();
2830     if (FromAS != DestAS) {
2831       QualType FromRecordTypeWithoutAS =
2832           Context.removeAddrSpaceQualType(FromRecordType);
2833       QualType FromTypeWithDestAS =
2834           Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS);
2835       if (PointerConversions)
2836         FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS);
2837       From = ImpCastExprToType(From, FromTypeWithDestAS,
2838                                CK_AddressSpaceConversion, From->getValueKind())
2839                  .get();
2840     }
2841   } else {
2842     // No conversion necessary.
2843     return From;
2844   }
2845 
2846   if (DestType->isDependentType() || FromType->isDependentType())
2847     return From;
2848 
2849   // If the unqualified types are the same, no conversion is necessary.
2850   if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2851     return From;
2852 
2853   SourceRange FromRange = From->getSourceRange();
2854   SourceLocation FromLoc = FromRange.getBegin();
2855 
2856   ExprValueKind VK = From->getValueKind();
2857 
2858   // C++ [class.member.lookup]p8:
2859   //   [...] Ambiguities can often be resolved by qualifying a name with its
2860   //   class name.
2861   //
2862   // If the member was a qualified name and the qualified referred to a
2863   // specific base subobject type, we'll cast to that intermediate type
2864   // first and then to the object in which the member is declared. That allows
2865   // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2866   //
2867   //   class Base { public: int x; };
2868   //   class Derived1 : public Base { };
2869   //   class Derived2 : public Base { };
2870   //   class VeryDerived : public Derived1, public Derived2 { void f(); };
2871   //
2872   //   void VeryDerived::f() {
2873   //     x = 17; // error: ambiguous base subobjects
2874   //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
2875   //   }
2876   if (Qualifier && Qualifier->getAsType()) {
2877     QualType QType = QualType(Qualifier->getAsType(), 0);
2878     assert(QType->isRecordType() && "lookup done with non-record type");
2879 
2880     QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2881 
2882     // In C++98, the qualifier type doesn't actually have to be a base
2883     // type of the object type, in which case we just ignore it.
2884     // Otherwise build the appropriate casts.
2885     if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
2886       CXXCastPath BasePath;
2887       if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2888                                        FromLoc, FromRange, &BasePath))
2889         return ExprError();
2890 
2891       if (PointerConversions)
2892         QType = Context.getPointerType(QType);
2893       From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2894                                VK, &BasePath).get();
2895 
2896       FromType = QType;
2897       FromRecordType = QRecordType;
2898 
2899       // If the qualifier type was the same as the destination type,
2900       // we're done.
2901       if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2902         return From;
2903     }
2904   }
2905 
2906   bool IgnoreAccess = false;
2907 
2908   // If we actually found the member through a using declaration, cast
2909   // down to the using declaration's type.
2910   //
2911   // Pointer equality is fine here because only one declaration of a
2912   // class ever has member declarations.
2913   if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2914     assert(isa<UsingShadowDecl>(FoundDecl));
2915     QualType URecordType = Context.getTypeDeclType(
2916                            cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2917 
2918     // We only need to do this if the naming-class to declaring-class
2919     // conversion is non-trivial.
2920     if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2921       assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType));
2922       CXXCastPath BasePath;
2923       if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2924                                        FromLoc, FromRange, &BasePath))
2925         return ExprError();
2926 
2927       QualType UType = URecordType;
2928       if (PointerConversions)
2929         UType = Context.getPointerType(UType);
2930       From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2931                                VK, &BasePath).get();
2932       FromType = UType;
2933       FromRecordType = URecordType;
2934     }
2935 
2936     // We don't do access control for the conversion from the
2937     // declaring class to the true declaring class.
2938     IgnoreAccess = true;
2939   }
2940 
2941   CXXCastPath BasePath;
2942   if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2943                                    FromLoc, FromRange, &BasePath,
2944                                    IgnoreAccess))
2945     return ExprError();
2946 
2947   return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2948                            VK, &BasePath);
2949 }
2950 
2951 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2952                                       const LookupResult &R,
2953                                       bool HasTrailingLParen) {
2954   // Only when used directly as the postfix-expression of a call.
2955   if (!HasTrailingLParen)
2956     return false;
2957 
2958   // Never if a scope specifier was provided.
2959   if (SS.isSet())
2960     return false;
2961 
2962   // Only in C++ or ObjC++.
2963   if (!getLangOpts().CPlusPlus)
2964     return false;
2965 
2966   // Turn off ADL when we find certain kinds of declarations during
2967   // normal lookup:
2968   for (NamedDecl *D : R) {
2969     // C++0x [basic.lookup.argdep]p3:
2970     //     -- a declaration of a class member
2971     // Since using decls preserve this property, we check this on the
2972     // original decl.
2973     if (D->isCXXClassMember())
2974       return false;
2975 
2976     // C++0x [basic.lookup.argdep]p3:
2977     //     -- a block-scope function declaration that is not a
2978     //        using-declaration
2979     // NOTE: we also trigger this for function templates (in fact, we
2980     // don't check the decl type at all, since all other decl types
2981     // turn off ADL anyway).
2982     if (isa<UsingShadowDecl>(D))
2983       D = cast<UsingShadowDecl>(D)->getTargetDecl();
2984     else if (D->getLexicalDeclContext()->isFunctionOrMethod())
2985       return false;
2986 
2987     // C++0x [basic.lookup.argdep]p3:
2988     //     -- a declaration that is neither a function or a function
2989     //        template
2990     // And also for builtin functions.
2991     if (isa<FunctionDecl>(D)) {
2992       FunctionDecl *FDecl = cast<FunctionDecl>(D);
2993 
2994       // But also builtin functions.
2995       if (FDecl->getBuiltinID() && FDecl->isImplicit())
2996         return false;
2997     } else if (!isa<FunctionTemplateDecl>(D))
2998       return false;
2999   }
3000 
3001   return true;
3002 }
3003 
3004 
3005 /// Diagnoses obvious problems with the use of the given declaration
3006 /// as an expression.  This is only actually called for lookups that
3007 /// were not overloaded, and it doesn't promise that the declaration
3008 /// will in fact be used.
3009 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
3010   if (D->isInvalidDecl())
3011     return true;
3012 
3013   if (isa<TypedefNameDecl>(D)) {
3014     S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
3015     return true;
3016   }
3017 
3018   if (isa<ObjCInterfaceDecl>(D)) {
3019     S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
3020     return true;
3021   }
3022 
3023   if (isa<NamespaceDecl>(D)) {
3024     S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
3025     return true;
3026   }
3027 
3028   return false;
3029 }
3030 
3031 // Certain multiversion types should be treated as overloaded even when there is
3032 // only one result.
3033 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) {
3034   assert(R.isSingleResult() && "Expected only a single result");
3035   const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
3036   return FD &&
3037          (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
3038 }
3039 
3040 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
3041                                           LookupResult &R, bool NeedsADL,
3042                                           bool AcceptInvalidDecl) {
3043   // If this is a single, fully-resolved result and we don't need ADL,
3044   // just build an ordinary singleton decl ref.
3045   if (!NeedsADL && R.isSingleResult() &&
3046       !R.getAsSingle<FunctionTemplateDecl>() &&
3047       !ShouldLookupResultBeMultiVersionOverload(R))
3048     return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
3049                                     R.getRepresentativeDecl(), nullptr,
3050                                     AcceptInvalidDecl);
3051 
3052   // We only need to check the declaration if there's exactly one
3053   // result, because in the overloaded case the results can only be
3054   // functions and function templates.
3055   if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) &&
3056       CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
3057     return ExprError();
3058 
3059   // Otherwise, just build an unresolved lookup expression.  Suppress
3060   // any lookup-related diagnostics; we'll hash these out later, when
3061   // we've picked a target.
3062   R.suppressDiagnostics();
3063 
3064   UnresolvedLookupExpr *ULE
3065     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
3066                                    SS.getWithLocInContext(Context),
3067                                    R.getLookupNameInfo(),
3068                                    NeedsADL, R.isOverloadedResult(),
3069                                    R.begin(), R.end());
3070 
3071   return ULE;
3072 }
3073 
3074 static void
3075 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
3076                                    ValueDecl *var, DeclContext *DC);
3077 
3078 /// Complete semantic analysis for a reference to the given declaration.
3079 ExprResult Sema::BuildDeclarationNameExpr(
3080     const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
3081     NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
3082     bool AcceptInvalidDecl) {
3083   assert(D && "Cannot refer to a NULL declaration");
3084   assert(!isa<FunctionTemplateDecl>(D) &&
3085          "Cannot refer unambiguously to a function template");
3086 
3087   SourceLocation Loc = NameInfo.getLoc();
3088   if (CheckDeclInExpr(*this, Loc, D))
3089     return ExprError();
3090 
3091   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
3092     // Specifically diagnose references to class templates that are missing
3093     // a template argument list.
3094     diagnoseMissingTemplateArguments(TemplateName(Template), Loc);
3095     return ExprError();
3096   }
3097 
3098   // Make sure that we're referring to a value.
3099   ValueDecl *VD = dyn_cast<ValueDecl>(D);
3100   if (!VD) {
3101     Diag(Loc, diag::err_ref_non_value)
3102       << D << SS.getRange();
3103     Diag(D->getLocation(), diag::note_declared_at);
3104     return ExprError();
3105   }
3106 
3107   // Check whether this declaration can be used. Note that we suppress
3108   // this check when we're going to perform argument-dependent lookup
3109   // on this function name, because this might not be the function
3110   // that overload resolution actually selects.
3111   if (DiagnoseUseOfDecl(VD, Loc))
3112     return ExprError();
3113 
3114   // Only create DeclRefExpr's for valid Decl's.
3115   if (VD->isInvalidDecl() && !AcceptInvalidDecl)
3116     return ExprError();
3117 
3118   // Handle members of anonymous structs and unions.  If we got here,
3119   // and the reference is to a class member indirect field, then this
3120   // must be the subject of a pointer-to-member expression.
3121   if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
3122     if (!indirectField->isCXXClassMember())
3123       return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
3124                                                       indirectField);
3125 
3126   {
3127     QualType type = VD->getType();
3128     if (type.isNull())
3129       return ExprError();
3130     ExprValueKind valueKind = VK_RValue;
3131 
3132     switch (D->getKind()) {
3133     // Ignore all the non-ValueDecl kinds.
3134 #define ABSTRACT_DECL(kind)
3135 #define VALUE(type, base)
3136 #define DECL(type, base) \
3137     case Decl::type:
3138 #include "clang/AST/DeclNodes.inc"
3139       llvm_unreachable("invalid value decl kind");
3140 
3141     // These shouldn't make it here.
3142     case Decl::ObjCAtDefsField:
3143       llvm_unreachable("forming non-member reference to ivar?");
3144 
3145     // Enum constants are always r-values and never references.
3146     // Unresolved using declarations are dependent.
3147     case Decl::EnumConstant:
3148     case Decl::UnresolvedUsingValue:
3149     case Decl::OMPDeclareReduction:
3150     case Decl::OMPDeclareMapper:
3151       valueKind = VK_RValue;
3152       break;
3153 
3154     // Fields and indirect fields that got here must be for
3155     // pointer-to-member expressions; we just call them l-values for
3156     // internal consistency, because this subexpression doesn't really
3157     // exist in the high-level semantics.
3158     case Decl::Field:
3159     case Decl::IndirectField:
3160     case Decl::ObjCIvar:
3161       assert(getLangOpts().CPlusPlus &&
3162              "building reference to field in C?");
3163 
3164       // These can't have reference type in well-formed programs, but
3165       // for internal consistency we do this anyway.
3166       type = type.getNonReferenceType();
3167       valueKind = VK_LValue;
3168       break;
3169 
3170     // Non-type template parameters are either l-values or r-values
3171     // depending on the type.
3172     case Decl::NonTypeTemplateParm: {
3173       if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
3174         type = reftype->getPointeeType();
3175         valueKind = VK_LValue; // even if the parameter is an r-value reference
3176         break;
3177       }
3178 
3179       // For non-references, we need to strip qualifiers just in case
3180       // the template parameter was declared as 'const int' or whatever.
3181       valueKind = VK_RValue;
3182       type = type.getUnqualifiedType();
3183       break;
3184     }
3185 
3186     case Decl::Var:
3187     case Decl::VarTemplateSpecialization:
3188     case Decl::VarTemplatePartialSpecialization:
3189     case Decl::Decomposition:
3190     case Decl::OMPCapturedExpr:
3191       // In C, "extern void blah;" is valid and is an r-value.
3192       if (!getLangOpts().CPlusPlus &&
3193           !type.hasQualifiers() &&
3194           type->isVoidType()) {
3195         valueKind = VK_RValue;
3196         break;
3197       }
3198       LLVM_FALLTHROUGH;
3199 
3200     case Decl::ImplicitParam:
3201     case Decl::ParmVar: {
3202       // These are always l-values.
3203       valueKind = VK_LValue;
3204       type = type.getNonReferenceType();
3205 
3206       // FIXME: Does the addition of const really only apply in
3207       // potentially-evaluated contexts? Since the variable isn't actually
3208       // captured in an unevaluated context, it seems that the answer is no.
3209       if (!isUnevaluatedContext()) {
3210         QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
3211         if (!CapturedType.isNull())
3212           type = CapturedType;
3213       }
3214 
3215       break;
3216     }
3217 
3218     case Decl::Binding: {
3219       // These are always lvalues.
3220       valueKind = VK_LValue;
3221       type = type.getNonReferenceType();
3222       // FIXME: Support lambda-capture of BindingDecls, once CWG actually
3223       // decides how that's supposed to work.
3224       auto *BD = cast<BindingDecl>(VD);
3225       if (BD->getDeclContext() != CurContext) {
3226         auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl());
3227         if (DD && DD->hasLocalStorage())
3228           diagnoseUncapturableValueReference(*this, Loc, BD, CurContext);
3229       }
3230       break;
3231     }
3232 
3233     case Decl::Function: {
3234       if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
3235         if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
3236           type = Context.BuiltinFnTy;
3237           valueKind = VK_RValue;
3238           break;
3239         }
3240       }
3241 
3242       const FunctionType *fty = type->castAs<FunctionType>();
3243 
3244       // If we're referring to a function with an __unknown_anytype
3245       // result type, make the entire expression __unknown_anytype.
3246       if (fty->getReturnType() == Context.UnknownAnyTy) {
3247         type = Context.UnknownAnyTy;
3248         valueKind = VK_RValue;
3249         break;
3250       }
3251 
3252       // Functions are l-values in C++.
3253       if (getLangOpts().CPlusPlus) {
3254         valueKind = VK_LValue;
3255         break;
3256       }
3257 
3258       // C99 DR 316 says that, if a function type comes from a
3259       // function definition (without a prototype), that type is only
3260       // used for checking compatibility. Therefore, when referencing
3261       // the function, we pretend that we don't have the full function
3262       // type.
3263       if (!cast<FunctionDecl>(VD)->hasPrototype() &&
3264           isa<FunctionProtoType>(fty))
3265         type = Context.getFunctionNoProtoType(fty->getReturnType(),
3266                                               fty->getExtInfo());
3267 
3268       // Functions are r-values in C.
3269       valueKind = VK_RValue;
3270       break;
3271     }
3272 
3273     case Decl::CXXDeductionGuide:
3274       llvm_unreachable("building reference to deduction guide");
3275 
3276     case Decl::MSProperty:
3277     case Decl::MSGuid:
3278       // FIXME: Should MSGuidDecl be subject to capture in OpenMP,
3279       // or duplicated between host and device?
3280       valueKind = VK_LValue;
3281       break;
3282 
3283     case Decl::CXXMethod:
3284       // If we're referring to a method with an __unknown_anytype
3285       // result type, make the entire expression __unknown_anytype.
3286       // This should only be possible with a type written directly.
3287       if (const FunctionProtoType *proto
3288             = dyn_cast<FunctionProtoType>(VD->getType()))
3289         if (proto->getReturnType() == Context.UnknownAnyTy) {
3290           type = Context.UnknownAnyTy;
3291           valueKind = VK_RValue;
3292           break;
3293         }
3294 
3295       // C++ methods are l-values if static, r-values if non-static.
3296       if (cast<CXXMethodDecl>(VD)->isStatic()) {
3297         valueKind = VK_LValue;
3298         break;
3299       }
3300       LLVM_FALLTHROUGH;
3301 
3302     case Decl::CXXConversion:
3303     case Decl::CXXDestructor:
3304     case Decl::CXXConstructor:
3305       valueKind = VK_RValue;
3306       break;
3307     }
3308 
3309     return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3310                             /*FIXME: TemplateKWLoc*/ SourceLocation(),
3311                             TemplateArgs);
3312   }
3313 }
3314 
3315 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3316                                     SmallString<32> &Target) {
3317   Target.resize(CharByteWidth * (Source.size() + 1));
3318   char *ResultPtr = &Target[0];
3319   const llvm::UTF8 *ErrorPtr;
3320   bool success =
3321       llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3322   (void)success;
3323   assert(success);
3324   Target.resize(ResultPtr - &Target[0]);
3325 }
3326 
3327 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3328                                      PredefinedExpr::IdentKind IK) {
3329   // Pick the current block, lambda, captured statement or function.
3330   Decl *currentDecl = nullptr;
3331   if (const BlockScopeInfo *BSI = getCurBlock())
3332     currentDecl = BSI->TheDecl;
3333   else if (const LambdaScopeInfo *LSI = getCurLambda())
3334     currentDecl = LSI->CallOperator;
3335   else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3336     currentDecl = CSI->TheCapturedDecl;
3337   else
3338     currentDecl = getCurFunctionOrMethodDecl();
3339 
3340   if (!currentDecl) {
3341     Diag(Loc, diag::ext_predef_outside_function);
3342     currentDecl = Context.getTranslationUnitDecl();
3343   }
3344 
3345   QualType ResTy;
3346   StringLiteral *SL = nullptr;
3347   if (cast<DeclContext>(currentDecl)->isDependentContext())
3348     ResTy = Context.DependentTy;
3349   else {
3350     // Pre-defined identifiers are of type char[x], where x is the length of
3351     // the string.
3352     auto Str = PredefinedExpr::ComputeName(IK, currentDecl);
3353     unsigned Length = Str.length();
3354 
3355     llvm::APInt LengthI(32, Length + 1);
3356     if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) {
3357       ResTy =
3358           Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst());
3359       SmallString<32> RawChars;
3360       ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3361                               Str, RawChars);
3362       ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3363                                            ArrayType::Normal,
3364                                            /*IndexTypeQuals*/ 0);
3365       SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3366                                  /*Pascal*/ false, ResTy, Loc);
3367     } else {
3368       ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
3369       ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3370                                            ArrayType::Normal,
3371                                            /*IndexTypeQuals*/ 0);
3372       SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3373                                  /*Pascal*/ false, ResTy, Loc);
3374     }
3375   }
3376 
3377   return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL);
3378 }
3379 
3380 static std::pair<QualType, StringLiteral *>
3381 GetUniqueStableNameInfo(ASTContext &Context, QualType OpType,
3382                         SourceLocation OpLoc, PredefinedExpr::IdentKind K) {
3383   std::pair<QualType, StringLiteral*> Result{{}, nullptr};
3384 
3385   if (OpType->isDependentType()) {
3386       Result.first = Context.DependentTy;
3387       return Result;
3388   }
3389 
3390   std::string Str = PredefinedExpr::ComputeName(Context, K, OpType);
3391   llvm::APInt Length(32, Str.length() + 1);
3392   Result.first =
3393       Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
3394   Result.first = Context.getConstantArrayType(
3395       Result.first, Length, nullptr, ArrayType::Normal, /*IndexTypeQuals*/ 0);
3396   Result.second = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3397                                         /*Pascal*/ false, Result.first, OpLoc);
3398   return Result;
3399 }
3400 
3401 ExprResult Sema::BuildUniqueStableName(SourceLocation OpLoc,
3402                                        TypeSourceInfo *Operand) {
3403   QualType ResultTy;
3404   StringLiteral *SL;
3405   std::tie(ResultTy, SL) = GetUniqueStableNameInfo(
3406       Context, Operand->getType(), OpLoc, PredefinedExpr::UniqueStableNameType);
3407 
3408   return PredefinedExpr::Create(Context, OpLoc, ResultTy,
3409                                 PredefinedExpr::UniqueStableNameType, SL,
3410                                 Operand);
3411 }
3412 
3413 ExprResult Sema::BuildUniqueStableName(SourceLocation OpLoc,
3414                                        Expr *E) {
3415   QualType ResultTy;
3416   StringLiteral *SL;
3417   std::tie(ResultTy, SL) = GetUniqueStableNameInfo(
3418       Context, E->getType(), OpLoc, PredefinedExpr::UniqueStableNameExpr);
3419 
3420   return PredefinedExpr::Create(Context, OpLoc, ResultTy,
3421                                 PredefinedExpr::UniqueStableNameExpr, SL, E);
3422 }
3423 
3424 ExprResult Sema::ActOnUniqueStableNameExpr(SourceLocation OpLoc,
3425                                            SourceLocation L, SourceLocation R,
3426                                            ParsedType Ty) {
3427   TypeSourceInfo *TInfo = nullptr;
3428   QualType T = GetTypeFromParser(Ty, &TInfo);
3429 
3430   if (T.isNull())
3431     return ExprError();
3432   if (!TInfo)
3433     TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
3434 
3435   return BuildUniqueStableName(OpLoc, TInfo);
3436 }
3437 
3438 ExprResult Sema::ActOnUniqueStableNameExpr(SourceLocation OpLoc,
3439                                            SourceLocation L, SourceLocation R,
3440                                            Expr *E) {
3441   return BuildUniqueStableName(OpLoc, E);
3442 }
3443 
3444 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3445   PredefinedExpr::IdentKind IK;
3446 
3447   switch (Kind) {
3448   default: llvm_unreachable("Unknown simple primary expr!");
3449   case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3450   case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break;
3451   case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS]
3452   case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS]
3453   case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS]
3454   case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS]
3455   case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break;
3456   }
3457 
3458   return BuildPredefinedExpr(Loc, IK);
3459 }
3460 
3461 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3462   SmallString<16> CharBuffer;
3463   bool Invalid = false;
3464   StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3465   if (Invalid)
3466     return ExprError();
3467 
3468   CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3469                             PP, Tok.getKind());
3470   if (Literal.hadError())
3471     return ExprError();
3472 
3473   QualType Ty;
3474   if (Literal.isWide())
3475     Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3476   else if (Literal.isUTF8() && getLangOpts().Char8)
3477     Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3478   else if (Literal.isUTF16())
3479     Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3480   else if (Literal.isUTF32())
3481     Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3482   else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3483     Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
3484   else
3485     Ty = Context.CharTy;  // 'x' -> char in C++
3486 
3487   CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3488   if (Literal.isWide())
3489     Kind = CharacterLiteral::Wide;
3490   else if (Literal.isUTF16())
3491     Kind = CharacterLiteral::UTF16;
3492   else if (Literal.isUTF32())
3493     Kind = CharacterLiteral::UTF32;
3494   else if (Literal.isUTF8())
3495     Kind = CharacterLiteral::UTF8;
3496 
3497   Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3498                                              Tok.getLocation());
3499 
3500   if (Literal.getUDSuffix().empty())
3501     return Lit;
3502 
3503   // We're building a user-defined literal.
3504   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3505   SourceLocation UDSuffixLoc =
3506     getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3507 
3508   // Make sure we're allowed user-defined literals here.
3509   if (!UDLScope)
3510     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3511 
3512   // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3513   //   operator "" X (ch)
3514   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3515                                         Lit, Tok.getLocation());
3516 }
3517 
3518 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3519   unsigned IntSize = Context.getTargetInfo().getIntWidth();
3520   return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3521                                 Context.IntTy, Loc);
3522 }
3523 
3524 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3525                                   QualType Ty, SourceLocation Loc) {
3526   const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3527 
3528   using llvm::APFloat;
3529   APFloat Val(Format);
3530 
3531   APFloat::opStatus result = Literal.GetFloatValue(Val);
3532 
3533   // Overflow is always an error, but underflow is only an error if
3534   // we underflowed to zero (APFloat reports denormals as underflow).
3535   if ((result & APFloat::opOverflow) ||
3536       ((result & APFloat::opUnderflow) && Val.isZero())) {
3537     unsigned diagnostic;
3538     SmallString<20> buffer;
3539     if (result & APFloat::opOverflow) {
3540       diagnostic = diag::warn_float_overflow;
3541       APFloat::getLargest(Format).toString(buffer);
3542     } else {
3543       diagnostic = diag::warn_float_underflow;
3544       APFloat::getSmallest(Format).toString(buffer);
3545     }
3546 
3547     S.Diag(Loc, diagnostic)
3548       << Ty
3549       << StringRef(buffer.data(), buffer.size());
3550   }
3551 
3552   bool isExact = (result == APFloat::opOK);
3553   return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3554 }
3555 
3556 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3557   assert(E && "Invalid expression");
3558 
3559   if (E->isValueDependent())
3560     return false;
3561 
3562   QualType QT = E->getType();
3563   if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3564     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3565     return true;
3566   }
3567 
3568   llvm::APSInt ValueAPS;
3569   ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3570 
3571   if (R.isInvalid())
3572     return true;
3573 
3574   bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3575   if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3576     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3577         << ValueAPS.toString(10) << ValueIsPositive;
3578     return true;
3579   }
3580 
3581   return false;
3582 }
3583 
3584 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3585   // Fast path for a single digit (which is quite common).  A single digit
3586   // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3587   if (Tok.getLength() == 1) {
3588     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3589     return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3590   }
3591 
3592   SmallString<128> SpellingBuffer;
3593   // NumericLiteralParser wants to overread by one character.  Add padding to
3594   // the buffer in case the token is copied to the buffer.  If getSpelling()
3595   // returns a StringRef to the memory buffer, it should have a null char at
3596   // the EOF, so it is also safe.
3597   SpellingBuffer.resize(Tok.getLength() + 1);
3598 
3599   // Get the spelling of the token, which eliminates trigraphs, etc.
3600   bool Invalid = false;
3601   StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3602   if (Invalid)
3603     return ExprError();
3604 
3605   NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
3606   if (Literal.hadError)
3607     return ExprError();
3608 
3609   if (Literal.hasUDSuffix()) {
3610     // We're building a user-defined literal.
3611     IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3612     SourceLocation UDSuffixLoc =
3613       getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3614 
3615     // Make sure we're allowed user-defined literals here.
3616     if (!UDLScope)
3617       return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3618 
3619     QualType CookedTy;
3620     if (Literal.isFloatingLiteral()) {
3621       // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3622       // long double, the literal is treated as a call of the form
3623       //   operator "" X (f L)
3624       CookedTy = Context.LongDoubleTy;
3625     } else {
3626       // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3627       // unsigned long long, the literal is treated as a call of the form
3628       //   operator "" X (n ULL)
3629       CookedTy = Context.UnsignedLongLongTy;
3630     }
3631 
3632     DeclarationName OpName =
3633       Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3634     DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3635     OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3636 
3637     SourceLocation TokLoc = Tok.getLocation();
3638 
3639     // Perform literal operator lookup to determine if we're building a raw
3640     // literal or a cooked one.
3641     LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3642     switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3643                                   /*AllowRaw*/ true, /*AllowTemplate*/ true,
3644                                   /*AllowStringTemplate*/ false,
3645                                   /*DiagnoseMissing*/ !Literal.isImaginary)) {
3646     case LOLR_ErrorNoDiagnostic:
3647       // Lookup failure for imaginary constants isn't fatal, there's still the
3648       // GNU extension producing _Complex types.
3649       break;
3650     case LOLR_Error:
3651       return ExprError();
3652     case LOLR_Cooked: {
3653       Expr *Lit;
3654       if (Literal.isFloatingLiteral()) {
3655         Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3656       } else {
3657         llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3658         if (Literal.GetIntegerValue(ResultVal))
3659           Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3660               << /* Unsigned */ 1;
3661         Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3662                                      Tok.getLocation());
3663       }
3664       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3665     }
3666 
3667     case LOLR_Raw: {
3668       // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3669       // literal is treated as a call of the form
3670       //   operator "" X ("n")
3671       unsigned Length = Literal.getUDSuffixOffset();
3672       QualType StrTy = Context.getConstantArrayType(
3673           Context.adjustStringLiteralBaseType(Context.CharTy.withConst()),
3674           llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0);
3675       Expr *Lit = StringLiteral::Create(
3676           Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3677           /*Pascal*/false, StrTy, &TokLoc, 1);
3678       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3679     }
3680 
3681     case LOLR_Template: {
3682       // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3683       // template), L is treated as a call fo the form
3684       //   operator "" X <'c1', 'c2', ... 'ck'>()
3685       // where n is the source character sequence c1 c2 ... ck.
3686       TemplateArgumentListInfo ExplicitArgs;
3687       unsigned CharBits = Context.getIntWidth(Context.CharTy);
3688       bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3689       llvm::APSInt Value(CharBits, CharIsUnsigned);
3690       for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3691         Value = TokSpelling[I];
3692         TemplateArgument Arg(Context, Value, Context.CharTy);
3693         TemplateArgumentLocInfo ArgInfo;
3694         ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3695       }
3696       return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3697                                       &ExplicitArgs);
3698     }
3699     case LOLR_StringTemplate:
3700       llvm_unreachable("unexpected literal operator lookup result");
3701     }
3702   }
3703 
3704   Expr *Res;
3705 
3706   if (Literal.isFixedPointLiteral()) {
3707     QualType Ty;
3708 
3709     if (Literal.isAccum) {
3710       if (Literal.isHalf) {
3711         Ty = Context.ShortAccumTy;
3712       } else if (Literal.isLong) {
3713         Ty = Context.LongAccumTy;
3714       } else {
3715         Ty = Context.AccumTy;
3716       }
3717     } else if (Literal.isFract) {
3718       if (Literal.isHalf) {
3719         Ty = Context.ShortFractTy;
3720       } else if (Literal.isLong) {
3721         Ty = Context.LongFractTy;
3722       } else {
3723         Ty = Context.FractTy;
3724       }
3725     }
3726 
3727     if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
3728 
3729     bool isSigned = !Literal.isUnsigned;
3730     unsigned scale = Context.getFixedPointScale(Ty);
3731     unsigned bit_width = Context.getTypeInfo(Ty).Width;
3732 
3733     llvm::APInt Val(bit_width, 0, isSigned);
3734     bool Overflowed = Literal.GetFixedPointValue(Val, scale);
3735     bool ValIsZero = Val.isNullValue() && !Overflowed;
3736 
3737     auto MaxVal = Context.getFixedPointMax(Ty).getValue();
3738     if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
3739       // Clause 6.4.4 - The value of a constant shall be in the range of
3740       // representable values for its type, with exception for constants of a
3741       // fract type with a value of exactly 1; such a constant shall denote
3742       // the maximal value for the type.
3743       --Val;
3744     else if (Val.ugt(MaxVal) || Overflowed)
3745       Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
3746 
3747     Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty,
3748                                               Tok.getLocation(), scale);
3749   } else if (Literal.isFloatingLiteral()) {
3750     QualType Ty;
3751     if (Literal.isHalf){
3752       if (getOpenCLOptions().isEnabled("cl_khr_fp16"))
3753         Ty = Context.HalfTy;
3754       else {
3755         Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3756         return ExprError();
3757       }
3758     } else if (Literal.isFloat)
3759       Ty = Context.FloatTy;
3760     else if (Literal.isLong)
3761       Ty = Context.LongDoubleTy;
3762     else if (Literal.isFloat16)
3763       Ty = Context.Float16Ty;
3764     else if (Literal.isFloat128)
3765       Ty = Context.Float128Ty;
3766     else
3767       Ty = Context.DoubleTy;
3768 
3769     Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3770 
3771     if (Ty == Context.DoubleTy) {
3772       if (getLangOpts().SinglePrecisionConstants) {
3773         const BuiltinType *BTy = Ty->getAs<BuiltinType>();
3774         if (BTy->getKind() != BuiltinType::Float) {
3775           Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3776         }
3777       } else if (getLangOpts().OpenCL &&
3778                  !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
3779         // Impose single-precision float type when cl_khr_fp64 is not enabled.
3780         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
3781         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3782       }
3783     }
3784   } else if (!Literal.isIntegerLiteral()) {
3785     return ExprError();
3786   } else {
3787     QualType Ty;
3788 
3789     // 'long long' is a C99 or C++11 feature.
3790     if (!getLangOpts().C99 && Literal.isLongLong) {
3791       if (getLangOpts().CPlusPlus)
3792         Diag(Tok.getLocation(),
3793              getLangOpts().CPlusPlus11 ?
3794              diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3795       else
3796         Diag(Tok.getLocation(), diag::ext_c99_longlong);
3797     }
3798 
3799     // Get the value in the widest-possible width.
3800     unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3801     llvm::APInt ResultVal(MaxWidth, 0);
3802 
3803     if (Literal.GetIntegerValue(ResultVal)) {
3804       // If this value didn't fit into uintmax_t, error and force to ull.
3805       Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3806           << /* Unsigned */ 1;
3807       Ty = Context.UnsignedLongLongTy;
3808       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3809              "long long is not intmax_t?");
3810     } else {
3811       // If this value fits into a ULL, try to figure out what else it fits into
3812       // according to the rules of C99 6.4.4.1p5.
3813 
3814       // Octal, Hexadecimal, and integers with a U suffix are allowed to
3815       // be an unsigned int.
3816       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3817 
3818       // Check from smallest to largest, picking the smallest type we can.
3819       unsigned Width = 0;
3820 
3821       // Microsoft specific integer suffixes are explicitly sized.
3822       if (Literal.MicrosoftInteger) {
3823         if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3824           Width = 8;
3825           Ty = Context.CharTy;
3826         } else {
3827           Width = Literal.MicrosoftInteger;
3828           Ty = Context.getIntTypeForBitwidth(Width,
3829                                              /*Signed=*/!Literal.isUnsigned);
3830         }
3831       }
3832 
3833       if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
3834         // Are int/unsigned possibilities?
3835         unsigned IntSize = Context.getTargetInfo().getIntWidth();
3836 
3837         // Does it fit in a unsigned int?
3838         if (ResultVal.isIntN(IntSize)) {
3839           // Does it fit in a signed int?
3840           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3841             Ty = Context.IntTy;
3842           else if (AllowUnsigned)
3843             Ty = Context.UnsignedIntTy;
3844           Width = IntSize;
3845         }
3846       }
3847 
3848       // Are long/unsigned long possibilities?
3849       if (Ty.isNull() && !Literal.isLongLong) {
3850         unsigned LongSize = Context.getTargetInfo().getLongWidth();
3851 
3852         // Does it fit in a unsigned long?
3853         if (ResultVal.isIntN(LongSize)) {
3854           // Does it fit in a signed long?
3855           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3856             Ty = Context.LongTy;
3857           else if (AllowUnsigned)
3858             Ty = Context.UnsignedLongTy;
3859           // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
3860           // is compatible.
3861           else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
3862             const unsigned LongLongSize =
3863                 Context.getTargetInfo().getLongLongWidth();
3864             Diag(Tok.getLocation(),
3865                  getLangOpts().CPlusPlus
3866                      ? Literal.isLong
3867                            ? diag::warn_old_implicitly_unsigned_long_cxx
3868                            : /*C++98 UB*/ diag::
3869                                  ext_old_implicitly_unsigned_long_cxx
3870                      : diag::warn_old_implicitly_unsigned_long)
3871                 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
3872                                             : /*will be ill-formed*/ 1);
3873             Ty = Context.UnsignedLongTy;
3874           }
3875           Width = LongSize;
3876         }
3877       }
3878 
3879       // Check long long if needed.
3880       if (Ty.isNull()) {
3881         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3882 
3883         // Does it fit in a unsigned long long?
3884         if (ResultVal.isIntN(LongLongSize)) {
3885           // Does it fit in a signed long long?
3886           // To be compatible with MSVC, hex integer literals ending with the
3887           // LL or i64 suffix are always signed in Microsoft mode.
3888           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3889               (getLangOpts().MSVCCompat && Literal.isLongLong)))
3890             Ty = Context.LongLongTy;
3891           else if (AllowUnsigned)
3892             Ty = Context.UnsignedLongLongTy;
3893           Width = LongLongSize;
3894         }
3895       }
3896 
3897       // If we still couldn't decide a type, we probably have something that
3898       // does not fit in a signed long long, but has no U suffix.
3899       if (Ty.isNull()) {
3900         Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
3901         Ty = Context.UnsignedLongLongTy;
3902         Width = Context.getTargetInfo().getLongLongWidth();
3903       }
3904 
3905       if (ResultVal.getBitWidth() != Width)
3906         ResultVal = ResultVal.trunc(Width);
3907     }
3908     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3909   }
3910 
3911   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3912   if (Literal.isImaginary) {
3913     Res = new (Context) ImaginaryLiteral(Res,
3914                                         Context.getComplexType(Res->getType()));
3915 
3916     Diag(Tok.getLocation(), diag::ext_imaginary_constant);
3917   }
3918   return Res;
3919 }
3920 
3921 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
3922   assert(E && "ActOnParenExpr() missing expr");
3923   return new (Context) ParenExpr(L, R, E);
3924 }
3925 
3926 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3927                                          SourceLocation Loc,
3928                                          SourceRange ArgRange) {
3929   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3930   // scalar or vector data type argument..."
3931   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3932   // type (C99 6.2.5p18) or void.
3933   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3934     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3935       << T << ArgRange;
3936     return true;
3937   }
3938 
3939   assert((T->isVoidType() || !T->isIncompleteType()) &&
3940          "Scalar types should always be complete");
3941   return false;
3942 }
3943 
3944 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3945                                            SourceLocation Loc,
3946                                            SourceRange ArgRange,
3947                                            UnaryExprOrTypeTrait TraitKind) {
3948   // Invalid types must be hard errors for SFINAE in C++.
3949   if (S.LangOpts.CPlusPlus)
3950     return true;
3951 
3952   // C99 6.5.3.4p1:
3953   if (T->isFunctionType() &&
3954       (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
3955        TraitKind == UETT_PreferredAlignOf)) {
3956     // sizeof(function)/alignof(function) is allowed as an extension.
3957     S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3958       << TraitKind << ArgRange;
3959     return false;
3960   }
3961 
3962   // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
3963   // this is an error (OpenCL v1.1 s6.3.k)
3964   if (T->isVoidType()) {
3965     unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
3966                                         : diag::ext_sizeof_alignof_void_type;
3967     S.Diag(Loc, DiagID) << TraitKind << ArgRange;
3968     return false;
3969   }
3970 
3971   return true;
3972 }
3973 
3974 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
3975                                              SourceLocation Loc,
3976                                              SourceRange ArgRange,
3977                                              UnaryExprOrTypeTrait TraitKind) {
3978   // Reject sizeof(interface) and sizeof(interface<proto>) if the
3979   // runtime doesn't allow it.
3980   if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
3981     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3982       << T << (TraitKind == UETT_SizeOf)
3983       << ArgRange;
3984     return true;
3985   }
3986 
3987   return false;
3988 }
3989 
3990 /// Check whether E is a pointer from a decayed array type (the decayed
3991 /// pointer type is equal to T) and emit a warning if it is.
3992 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
3993                                      Expr *E) {
3994   // Don't warn if the operation changed the type.
3995   if (T != E->getType())
3996     return;
3997 
3998   // Now look for array decays.
3999   ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
4000   if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
4001     return;
4002 
4003   S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
4004                                              << ICE->getType()
4005                                              << ICE->getSubExpr()->getType();
4006 }
4007 
4008 /// Check the constraints on expression operands to unary type expression
4009 /// and type traits.
4010 ///
4011 /// Completes any types necessary and validates the constraints on the operand
4012 /// expression. The logic mostly mirrors the type-based overload, but may modify
4013 /// the expression as it completes the type for that expression through template
4014 /// instantiation, etc.
4015 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
4016                                             UnaryExprOrTypeTrait ExprKind) {
4017   QualType ExprTy = E->getType();
4018   assert(!ExprTy->isReferenceType());
4019 
4020   bool IsUnevaluatedOperand =
4021       (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf ||
4022        ExprKind == UETT_PreferredAlignOf);
4023   if (IsUnevaluatedOperand) {
4024     ExprResult Result = CheckUnevaluatedOperand(E);
4025     if (Result.isInvalid())
4026       return true;
4027     E = Result.get();
4028   }
4029 
4030   if (ExprKind == UETT_VecStep)
4031     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
4032                                         E->getSourceRange());
4033 
4034   // Whitelist some types as extensions
4035   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
4036                                       E->getSourceRange(), ExprKind))
4037     return false;
4038 
4039   // 'alignof' applied to an expression only requires the base element type of
4040   // the expression to be complete. 'sizeof' requires the expression's type to
4041   // be complete (and will attempt to complete it if it's an array of unknown
4042   // bound).
4043   if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4044     if (RequireCompleteSizedType(
4045             E->getExprLoc(), Context.getBaseElementType(E->getType()),
4046             diag::err_sizeof_alignof_incomplete_or_sizeless_type, ExprKind,
4047             E->getSourceRange()))
4048       return true;
4049   } else {
4050     if (RequireCompleteSizedExprType(
4051             E, diag::err_sizeof_alignof_incomplete_or_sizeless_type, ExprKind,
4052             E->getSourceRange()))
4053       return true;
4054   }
4055 
4056   // Completing the expression's type may have changed it.
4057   ExprTy = E->getType();
4058   assert(!ExprTy->isReferenceType());
4059 
4060   if (ExprTy->isFunctionType()) {
4061     Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
4062       << ExprKind << E->getSourceRange();
4063     return true;
4064   }
4065 
4066   // The operand for sizeof and alignof is in an unevaluated expression context,
4067   // so side effects could result in unintended consequences.
4068   if (IsUnevaluatedOperand && !inTemplateInstantiation() &&
4069       E->HasSideEffects(Context, false))
4070     Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
4071 
4072   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
4073                                        E->getSourceRange(), ExprKind))
4074     return true;
4075 
4076   if (ExprKind == UETT_SizeOf) {
4077     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
4078       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
4079         QualType OType = PVD->getOriginalType();
4080         QualType Type = PVD->getType();
4081         if (Type->isPointerType() && OType->isArrayType()) {
4082           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
4083             << Type << OType;
4084           Diag(PVD->getLocation(), diag::note_declared_at);
4085         }
4086       }
4087     }
4088 
4089     // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
4090     // decays into a pointer and returns an unintended result. This is most
4091     // likely a typo for "sizeof(array) op x".
4092     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
4093       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4094                                BO->getLHS());
4095       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4096                                BO->getRHS());
4097     }
4098   }
4099 
4100   return false;
4101 }
4102 
4103 /// Check the constraints on operands to unary expression and type
4104 /// traits.
4105 ///
4106 /// This will complete any types necessary, and validate the various constraints
4107 /// on those operands.
4108 ///
4109 /// The UsualUnaryConversions() function is *not* called by this routine.
4110 /// C99 6.3.2.1p[2-4] all state:
4111 ///   Except when it is the operand of the sizeof operator ...
4112 ///
4113 /// C++ [expr.sizeof]p4
4114 ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
4115 ///   standard conversions are not applied to the operand of sizeof.
4116 ///
4117 /// This policy is followed for all of the unary trait expressions.
4118 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
4119                                             SourceLocation OpLoc,
4120                                             SourceRange ExprRange,
4121                                             UnaryExprOrTypeTrait ExprKind) {
4122   if (ExprType->isDependentType())
4123     return false;
4124 
4125   // C++ [expr.sizeof]p2:
4126   //     When applied to a reference or a reference type, the result
4127   //     is the size of the referenced type.
4128   // C++11 [expr.alignof]p3:
4129   //     When alignof is applied to a reference type, the result
4130   //     shall be the alignment of the referenced type.
4131   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
4132     ExprType = Ref->getPointeeType();
4133 
4134   // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
4135   //   When alignof or _Alignof is applied to an array type, the result
4136   //   is the alignment of the element type.
4137   if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4138       ExprKind == UETT_OpenMPRequiredSimdAlign)
4139     ExprType = Context.getBaseElementType(ExprType);
4140 
4141   if (ExprKind == UETT_VecStep)
4142     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
4143 
4144   // Whitelist some types as extensions
4145   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
4146                                       ExprKind))
4147     return false;
4148 
4149   if (RequireCompleteSizedType(
4150           OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4151           ExprKind, ExprRange))
4152     return true;
4153 
4154   if (ExprType->isFunctionType()) {
4155     Diag(OpLoc, diag::err_sizeof_alignof_function_type)
4156       << ExprKind << ExprRange;
4157     return true;
4158   }
4159 
4160   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
4161                                        ExprKind))
4162     return true;
4163 
4164   return false;
4165 }
4166 
4167 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
4168   // Cannot know anything else if the expression is dependent.
4169   if (E->isTypeDependent())
4170     return false;
4171 
4172   if (E->getObjectKind() == OK_BitField) {
4173     S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
4174        << 1 << E->getSourceRange();
4175     return true;
4176   }
4177 
4178   ValueDecl *D = nullptr;
4179   Expr *Inner = E->IgnoreParens();
4180   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) {
4181     D = DRE->getDecl();
4182   } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) {
4183     D = ME->getMemberDecl();
4184   }
4185 
4186   // If it's a field, require the containing struct to have a
4187   // complete definition so that we can compute the layout.
4188   //
4189   // This can happen in C++11 onwards, either by naming the member
4190   // in a way that is not transformed into a member access expression
4191   // (in an unevaluated operand, for instance), or by naming the member
4192   // in a trailing-return-type.
4193   //
4194   // For the record, since __alignof__ on expressions is a GCC
4195   // extension, GCC seems to permit this but always gives the
4196   // nonsensical answer 0.
4197   //
4198   // We don't really need the layout here --- we could instead just
4199   // directly check for all the appropriate alignment-lowing
4200   // attributes --- but that would require duplicating a lot of
4201   // logic that just isn't worth duplicating for such a marginal
4202   // use-case.
4203   if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
4204     // Fast path this check, since we at least know the record has a
4205     // definition if we can find a member of it.
4206     if (!FD->getParent()->isCompleteDefinition()) {
4207       S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
4208         << E->getSourceRange();
4209       return true;
4210     }
4211 
4212     // Otherwise, if it's a field, and the field doesn't have
4213     // reference type, then it must have a complete type (or be a
4214     // flexible array member, which we explicitly want to
4215     // white-list anyway), which makes the following checks trivial.
4216     if (!FD->getType()->isReferenceType())
4217       return false;
4218   }
4219 
4220   return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4221 }
4222 
4223 bool Sema::CheckVecStepExpr(Expr *E) {
4224   E = E->IgnoreParens();
4225 
4226   // Cannot know anything else if the expression is dependent.
4227   if (E->isTypeDependent())
4228     return false;
4229 
4230   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
4231 }
4232 
4233 static void captureVariablyModifiedType(ASTContext &Context, QualType T,
4234                                         CapturingScopeInfo *CSI) {
4235   assert(T->isVariablyModifiedType());
4236   assert(CSI != nullptr);
4237 
4238   // We're going to walk down into the type and look for VLA expressions.
4239   do {
4240     const Type *Ty = T.getTypePtr();
4241     switch (Ty->getTypeClass()) {
4242 #define TYPE(Class, Base)
4243 #define ABSTRACT_TYPE(Class, Base)
4244 #define NON_CANONICAL_TYPE(Class, Base)
4245 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
4246 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4247 #include "clang/AST/TypeNodes.inc"
4248       T = QualType();
4249       break;
4250     // These types are never variably-modified.
4251     case Type::Builtin:
4252     case Type::Complex:
4253     case Type::Vector:
4254     case Type::ExtVector:
4255     case Type::Record:
4256     case Type::Enum:
4257     case Type::Elaborated:
4258     case Type::TemplateSpecialization:
4259     case Type::ObjCObject:
4260     case Type::ObjCInterface:
4261     case Type::ObjCObjectPointer:
4262     case Type::ObjCTypeParam:
4263     case Type::Pipe:
4264       llvm_unreachable("type class is never variably-modified!");
4265     case Type::Adjusted:
4266       T = cast<AdjustedType>(Ty)->getOriginalType();
4267       break;
4268     case Type::Decayed:
4269       T = cast<DecayedType>(Ty)->getPointeeType();
4270       break;
4271     case Type::Pointer:
4272       T = cast<PointerType>(Ty)->getPointeeType();
4273       break;
4274     case Type::BlockPointer:
4275       T = cast<BlockPointerType>(Ty)->getPointeeType();
4276       break;
4277     case Type::LValueReference:
4278     case Type::RValueReference:
4279       T = cast<ReferenceType>(Ty)->getPointeeType();
4280       break;
4281     case Type::MemberPointer:
4282       T = cast<MemberPointerType>(Ty)->getPointeeType();
4283       break;
4284     case Type::ConstantArray:
4285     case Type::IncompleteArray:
4286       // Losing element qualification here is fine.
4287       T = cast<ArrayType>(Ty)->getElementType();
4288       break;
4289     case Type::VariableArray: {
4290       // Losing element qualification here is fine.
4291       const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
4292 
4293       // Unknown size indication requires no size computation.
4294       // Otherwise, evaluate and record it.
4295       auto Size = VAT->getSizeExpr();
4296       if (Size && !CSI->isVLATypeCaptured(VAT) &&
4297           (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI)))
4298         CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType());
4299 
4300       T = VAT->getElementType();
4301       break;
4302     }
4303     case Type::FunctionProto:
4304     case Type::FunctionNoProto:
4305       T = cast<FunctionType>(Ty)->getReturnType();
4306       break;
4307     case Type::Paren:
4308     case Type::TypeOf:
4309     case Type::UnaryTransform:
4310     case Type::Attributed:
4311     case Type::SubstTemplateTypeParm:
4312     case Type::PackExpansion:
4313     case Type::MacroQualified:
4314       // Keep walking after single level desugaring.
4315       T = T.getSingleStepDesugaredType(Context);
4316       break;
4317     case Type::Typedef:
4318       T = cast<TypedefType>(Ty)->desugar();
4319       break;
4320     case Type::Decltype:
4321       T = cast<DecltypeType>(Ty)->desugar();
4322       break;
4323     case Type::Auto:
4324     case Type::DeducedTemplateSpecialization:
4325       T = cast<DeducedType>(Ty)->getDeducedType();
4326       break;
4327     case Type::TypeOfExpr:
4328       T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
4329       break;
4330     case Type::Atomic:
4331       T = cast<AtomicType>(Ty)->getValueType();
4332       break;
4333     }
4334   } while (!T.isNull() && T->isVariablyModifiedType());
4335 }
4336 
4337 /// Build a sizeof or alignof expression given a type operand.
4338 ExprResult
4339 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4340                                      SourceLocation OpLoc,
4341                                      UnaryExprOrTypeTrait ExprKind,
4342                                      SourceRange R) {
4343   if (!TInfo)
4344     return ExprError();
4345 
4346   QualType T = TInfo->getType();
4347 
4348   if (!T->isDependentType() &&
4349       CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
4350     return ExprError();
4351 
4352   if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4353     if (auto *TT = T->getAs<TypedefType>()) {
4354       for (auto I = FunctionScopes.rbegin(),
4355                 E = std::prev(FunctionScopes.rend());
4356            I != E; ++I) {
4357         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4358         if (CSI == nullptr)
4359           break;
4360         DeclContext *DC = nullptr;
4361         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4362           DC = LSI->CallOperator;
4363         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4364           DC = CRSI->TheCapturedDecl;
4365         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4366           DC = BSI->TheDecl;
4367         if (DC) {
4368           if (DC->containsDecl(TT->getDecl()))
4369             break;
4370           captureVariablyModifiedType(Context, T, CSI);
4371         }
4372       }
4373     }
4374   }
4375 
4376   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4377   return new (Context) UnaryExprOrTypeTraitExpr(
4378       ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4379 }
4380 
4381 /// Build a sizeof or alignof expression given an expression
4382 /// operand.
4383 ExprResult
4384 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4385                                      UnaryExprOrTypeTrait ExprKind) {
4386   ExprResult PE = CheckPlaceholderExpr(E);
4387   if (PE.isInvalid())
4388     return ExprError();
4389 
4390   E = PE.get();
4391 
4392   // Verify that the operand is valid.
4393   bool isInvalid = false;
4394   if (E->isTypeDependent()) {
4395     // Delay type-checking for type-dependent expressions.
4396   } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4397     isInvalid = CheckAlignOfExpr(*this, E, ExprKind);
4398   } else if (ExprKind == UETT_VecStep) {
4399     isInvalid = CheckVecStepExpr(E);
4400   } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4401       Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4402       isInvalid = true;
4403   } else if (E->refersToBitField()) {  // C99 6.5.3.4p1.
4404     Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4405     isInvalid = true;
4406   } else {
4407     isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
4408   }
4409 
4410   if (isInvalid)
4411     return ExprError();
4412 
4413   if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4414     PE = TransformToPotentiallyEvaluated(E);
4415     if (PE.isInvalid()) return ExprError();
4416     E = PE.get();
4417   }
4418 
4419   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4420   return new (Context) UnaryExprOrTypeTraitExpr(
4421       ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4422 }
4423 
4424 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4425 /// expr and the same for @c alignof and @c __alignof
4426 /// Note that the ArgRange is invalid if isType is false.
4427 ExprResult
4428 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4429                                     UnaryExprOrTypeTrait ExprKind, bool IsType,
4430                                     void *TyOrEx, SourceRange ArgRange) {
4431   // If error parsing type, ignore.
4432   if (!TyOrEx) return ExprError();
4433 
4434   if (IsType) {
4435     TypeSourceInfo *TInfo;
4436     (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4437     return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4438   }
4439 
4440   Expr *ArgEx = (Expr *)TyOrEx;
4441   ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4442   return Result;
4443 }
4444 
4445 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4446                                      bool IsReal) {
4447   if (V.get()->isTypeDependent())
4448     return S.Context.DependentTy;
4449 
4450   // _Real and _Imag are only l-values for normal l-values.
4451   if (V.get()->getObjectKind() != OK_Ordinary) {
4452     V = S.DefaultLvalueConversion(V.get());
4453     if (V.isInvalid())
4454       return QualType();
4455   }
4456 
4457   // These operators return the element type of a complex type.
4458   if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4459     return CT->getElementType();
4460 
4461   // Otherwise they pass through real integer and floating point types here.
4462   if (V.get()->getType()->isArithmeticType())
4463     return V.get()->getType();
4464 
4465   // Test for placeholders.
4466   ExprResult PR = S.CheckPlaceholderExpr(V.get());
4467   if (PR.isInvalid()) return QualType();
4468   if (PR.get() != V.get()) {
4469     V = PR;
4470     return CheckRealImagOperand(S, V, Loc, IsReal);
4471   }
4472 
4473   // Reject anything else.
4474   S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4475     << (IsReal ? "__real" : "__imag");
4476   return QualType();
4477 }
4478 
4479 
4480 
4481 ExprResult
4482 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4483                           tok::TokenKind Kind, Expr *Input) {
4484   UnaryOperatorKind Opc;
4485   switch (Kind) {
4486   default: llvm_unreachable("Unknown unary op!");
4487   case tok::plusplus:   Opc = UO_PostInc; break;
4488   case tok::minusminus: Opc = UO_PostDec; break;
4489   }
4490 
4491   // Since this might is a postfix expression, get rid of ParenListExprs.
4492   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4493   if (Result.isInvalid()) return ExprError();
4494   Input = Result.get();
4495 
4496   return BuildUnaryOp(S, OpLoc, Opc, Input);
4497 }
4498 
4499 /// Diagnose if arithmetic on the given ObjC pointer is illegal.
4500 ///
4501 /// \return true on error
4502 static bool checkArithmeticOnObjCPointer(Sema &S,
4503                                          SourceLocation opLoc,
4504                                          Expr *op) {
4505   assert(op->getType()->isObjCObjectPointerType());
4506   if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4507       !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4508     return false;
4509 
4510   S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4511     << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4512     << op->getSourceRange();
4513   return true;
4514 }
4515 
4516 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4517   auto *BaseNoParens = Base->IgnoreParens();
4518   if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4519     return MSProp->getPropertyDecl()->getType()->isArrayType();
4520   return isa<MSPropertySubscriptExpr>(BaseNoParens);
4521 }
4522 
4523 ExprResult
4524 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
4525                               Expr *idx, SourceLocation rbLoc) {
4526   if (base && !base->getType().isNull() &&
4527       base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection))
4528     return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
4529                                     /*Length=*/nullptr, rbLoc);
4530 
4531   // Since this might be a postfix expression, get rid of ParenListExprs.
4532   if (isa<ParenListExpr>(base)) {
4533     ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4534     if (result.isInvalid()) return ExprError();
4535     base = result.get();
4536   }
4537 
4538   // A comma-expression as the index is deprecated in C++2a onwards.
4539   if (getLangOpts().CPlusPlus2a &&
4540       ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) ||
4541        (isa<CXXOperatorCallExpr>(idx) &&
4542         cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma))) {
4543     Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript)
4544       << SourceRange(base->getBeginLoc(), rbLoc);
4545   }
4546 
4547   // Handle any non-overload placeholder types in the base and index
4548   // expressions.  We can't handle overloads here because the other
4549   // operand might be an overloadable type, in which case the overload
4550   // resolution for the operator overload should get the first crack
4551   // at the overload.
4552   bool IsMSPropertySubscript = false;
4553   if (base->getType()->isNonOverloadPlaceholderType()) {
4554     IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4555     if (!IsMSPropertySubscript) {
4556       ExprResult result = CheckPlaceholderExpr(base);
4557       if (result.isInvalid())
4558         return ExprError();
4559       base = result.get();
4560     }
4561   }
4562   if (idx->getType()->isNonOverloadPlaceholderType()) {
4563     ExprResult result = CheckPlaceholderExpr(idx);
4564     if (result.isInvalid()) return ExprError();
4565     idx = result.get();
4566   }
4567 
4568   // Build an unanalyzed expression if either operand is type-dependent.
4569   if (getLangOpts().CPlusPlus &&
4570       (base->isTypeDependent() || idx->isTypeDependent())) {
4571     return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
4572                                             VK_LValue, OK_Ordinary, rbLoc);
4573   }
4574 
4575   // MSDN, property (C++)
4576   // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4577   // This attribute can also be used in the declaration of an empty array in a
4578   // class or structure definition. For example:
4579   // __declspec(property(get=GetX, put=PutX)) int x[];
4580   // The above statement indicates that x[] can be used with one or more array
4581   // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4582   // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4583   if (IsMSPropertySubscript) {
4584     // Build MS property subscript expression if base is MS property reference
4585     // or MS property subscript.
4586     return new (Context) MSPropertySubscriptExpr(
4587         base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
4588   }
4589 
4590   // Use C++ overloaded-operator rules if either operand has record
4591   // type.  The spec says to do this if either type is *overloadable*,
4592   // but enum types can't declare subscript operators or conversion
4593   // operators, so there's nothing interesting for overload resolution
4594   // to do if there aren't any record types involved.
4595   //
4596   // ObjC pointers have their own subscripting logic that is not tied
4597   // to overload resolution and so should not take this path.
4598   if (getLangOpts().CPlusPlus &&
4599       (base->getType()->isRecordType() ||
4600        (!base->getType()->isObjCObjectPointerType() &&
4601         idx->getType()->isRecordType()))) {
4602     return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
4603   }
4604 
4605   ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
4606 
4607   if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get()))
4608     CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get()));
4609 
4610   return Res;
4611 }
4612 
4613 void Sema::CheckAddressOfNoDeref(const Expr *E) {
4614   ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4615   const Expr *StrippedExpr = E->IgnoreParenImpCasts();
4616 
4617   // For expressions like `&(*s).b`, the base is recorded and what should be
4618   // checked.
4619   const MemberExpr *Member = nullptr;
4620   while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow())
4621     StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
4622 
4623   LastRecord.PossibleDerefs.erase(StrippedExpr);
4624 }
4625 
4626 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
4627   QualType ResultTy = E->getType();
4628   ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4629 
4630   // Bail if the element is an array since it is not memory access.
4631   if (isa<ArrayType>(ResultTy))
4632     return;
4633 
4634   if (ResultTy->hasAttr(attr::NoDeref)) {
4635     LastRecord.PossibleDerefs.insert(E);
4636     return;
4637   }
4638 
4639   // Check if the base type is a pointer to a member access of a struct
4640   // marked with noderef.
4641   const Expr *Base = E->getBase();
4642   QualType BaseTy = Base->getType();
4643   if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy)))
4644     // Not a pointer access
4645     return;
4646 
4647   const MemberExpr *Member = nullptr;
4648   while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) &&
4649          Member->isArrow())
4650     Base = Member->getBase();
4651 
4652   if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) {
4653     if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))
4654       LastRecord.PossibleDerefs.insert(E);
4655   }
4656 }
4657 
4658 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4659                                           Expr *LowerBound,
4660                                           SourceLocation ColonLoc, Expr *Length,
4661                                           SourceLocation RBLoc) {
4662   if (Base->getType()->isPlaceholderType() &&
4663       !Base->getType()->isSpecificPlaceholderType(
4664           BuiltinType::OMPArraySection)) {
4665     ExprResult Result = CheckPlaceholderExpr(Base);
4666     if (Result.isInvalid())
4667       return ExprError();
4668     Base = Result.get();
4669   }
4670   if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
4671     ExprResult Result = CheckPlaceholderExpr(LowerBound);
4672     if (Result.isInvalid())
4673       return ExprError();
4674     Result = DefaultLvalueConversion(Result.get());
4675     if (Result.isInvalid())
4676       return ExprError();
4677     LowerBound = Result.get();
4678   }
4679   if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
4680     ExprResult Result = CheckPlaceholderExpr(Length);
4681     if (Result.isInvalid())
4682       return ExprError();
4683     Result = DefaultLvalueConversion(Result.get());
4684     if (Result.isInvalid())
4685       return ExprError();
4686     Length = Result.get();
4687   }
4688 
4689   // Build an unanalyzed expression if either operand is type-dependent.
4690   if (Base->isTypeDependent() ||
4691       (LowerBound &&
4692        (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
4693       (Length && (Length->isTypeDependent() || Length->isValueDependent()))) {
4694     return new (Context)
4695         OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy,
4696                             VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4697   }
4698 
4699   // Perform default conversions.
4700   QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
4701   QualType ResultTy;
4702   if (OriginalTy->isAnyPointerType()) {
4703     ResultTy = OriginalTy->getPointeeType();
4704   } else if (OriginalTy->isArrayType()) {
4705     ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
4706   } else {
4707     return ExprError(
4708         Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
4709         << Base->getSourceRange());
4710   }
4711   // C99 6.5.2.1p1
4712   if (LowerBound) {
4713     auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
4714                                                       LowerBound);
4715     if (Res.isInvalid())
4716       return ExprError(Diag(LowerBound->getExprLoc(),
4717                             diag::err_omp_typecheck_section_not_integer)
4718                        << 0 << LowerBound->getSourceRange());
4719     LowerBound = Res.get();
4720 
4721     if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4722         LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4723       Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
4724           << 0 << LowerBound->getSourceRange();
4725   }
4726   if (Length) {
4727     auto Res =
4728         PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
4729     if (Res.isInvalid())
4730       return ExprError(Diag(Length->getExprLoc(),
4731                             diag::err_omp_typecheck_section_not_integer)
4732                        << 1 << Length->getSourceRange());
4733     Length = Res.get();
4734 
4735     if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4736         Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4737       Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
4738           << 1 << Length->getSourceRange();
4739   }
4740 
4741   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4742   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4743   // type. Note that functions are not objects, and that (in C99 parlance)
4744   // incomplete types are not object types.
4745   if (ResultTy->isFunctionType()) {
4746     Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
4747         << ResultTy << Base->getSourceRange();
4748     return ExprError();
4749   }
4750 
4751   if (RequireCompleteType(Base->getExprLoc(), ResultTy,
4752                           diag::err_omp_section_incomplete_type, Base))
4753     return ExprError();
4754 
4755   if (LowerBound && !OriginalTy->isAnyPointerType()) {
4756     Expr::EvalResult Result;
4757     if (LowerBound->EvaluateAsInt(Result, Context)) {
4758       // OpenMP 4.5, [2.4 Array Sections]
4759       // The array section must be a subset of the original array.
4760       llvm::APSInt LowerBoundValue = Result.Val.getInt();
4761       if (LowerBoundValue.isNegative()) {
4762         Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
4763             << LowerBound->getSourceRange();
4764         return ExprError();
4765       }
4766     }
4767   }
4768 
4769   if (Length) {
4770     Expr::EvalResult Result;
4771     if (Length->EvaluateAsInt(Result, Context)) {
4772       // OpenMP 4.5, [2.4 Array Sections]
4773       // The length must evaluate to non-negative integers.
4774       llvm::APSInt LengthValue = Result.Val.getInt();
4775       if (LengthValue.isNegative()) {
4776         Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
4777             << LengthValue.toString(/*Radix=*/10, /*Signed=*/true)
4778             << Length->getSourceRange();
4779         return ExprError();
4780       }
4781     }
4782   } else if (ColonLoc.isValid() &&
4783              (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
4784                                       !OriginalTy->isVariableArrayType()))) {
4785     // OpenMP 4.5, [2.4 Array Sections]
4786     // When the size of the array dimension is not known, the length must be
4787     // specified explicitly.
4788     Diag(ColonLoc, diag::err_omp_section_length_undefined)
4789         << (!OriginalTy.isNull() && OriginalTy->isArrayType());
4790     return ExprError();
4791   }
4792 
4793   if (!Base->getType()->isSpecificPlaceholderType(
4794           BuiltinType::OMPArraySection)) {
4795     ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
4796     if (Result.isInvalid())
4797       return ExprError();
4798     Base = Result.get();
4799   }
4800   return new (Context)
4801       OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy,
4802                           VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4803 }
4804 
4805 ExprResult Sema::ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc,
4806                                           SourceLocation RParenLoc,
4807                                           ArrayRef<Expr *> Dims,
4808                                           ArrayRef<SourceRange> Brackets) {
4809   if (Base->getType()->isPlaceholderType()) {
4810     ExprResult Result = CheckPlaceholderExpr(Base);
4811     if (Result.isInvalid())
4812       return ExprError();
4813     Result = DefaultLvalueConversion(Result.get());
4814     if (Result.isInvalid())
4815       return ExprError();
4816     Base = Result.get();
4817   }
4818   QualType BaseTy = Base->getType();
4819   // Delay analysis of the types/expressions if instantiation/specialization is
4820   // required.
4821   if (!BaseTy->isPointerType() && Base->isTypeDependent())
4822     return OMPArrayShapingExpr::Create(Context, Context.DependentTy, Base,
4823                                        LParenLoc, RParenLoc, Dims, Brackets);
4824   if (!BaseTy->isPointerType() ||
4825       (!Base->isTypeDependent() &&
4826        BaseTy->getPointeeType()->isIncompleteType()))
4827     return ExprError(Diag(Base->getExprLoc(),
4828                           diag::err_omp_non_pointer_type_array_shaping_base)
4829                      << Base->getSourceRange());
4830 
4831   SmallVector<Expr *, 4> NewDims;
4832   bool ErrorFound = false;
4833   for (Expr *Dim : Dims) {
4834     if (Dim->getType()->isPlaceholderType()) {
4835       ExprResult Result = CheckPlaceholderExpr(Dim);
4836       if (Result.isInvalid()) {
4837         ErrorFound = true;
4838         continue;
4839       }
4840       Result = DefaultLvalueConversion(Result.get());
4841       if (Result.isInvalid()) {
4842         ErrorFound = true;
4843         continue;
4844       }
4845       Dim = Result.get();
4846     }
4847     if (!Dim->isTypeDependent()) {
4848       ExprResult Result =
4849           PerformOpenMPImplicitIntegerConversion(Dim->getExprLoc(), Dim);
4850       if (Result.isInvalid()) {
4851         ErrorFound = true;
4852         Diag(Dim->getExprLoc(), diag::err_omp_typecheck_shaping_not_integer)
4853             << Dim->getSourceRange();
4854         continue;
4855       }
4856       Dim = Result.get();
4857       Expr::EvalResult EvResult;
4858       if (!Dim->isValueDependent() && Dim->EvaluateAsInt(EvResult, Context)) {
4859         // OpenMP 5.0, [2.1.4 Array Shaping]
4860         // Each si is an integral type expression that must evaluate to a
4861         // positive integer.
4862         llvm::APSInt Value = EvResult.Val.getInt();
4863         if (!Value.isStrictlyPositive()) {
4864           Diag(Dim->getExprLoc(), diag::err_omp_shaping_dimension_not_positive)
4865               << Value.toString(/*Radix=*/10, /*Signed=*/true)
4866               << Dim->getSourceRange();
4867           ErrorFound = true;
4868           continue;
4869         }
4870       }
4871     }
4872     NewDims.push_back(Dim);
4873   }
4874   if (ErrorFound)
4875     return ExprError();
4876   return OMPArrayShapingExpr::Create(Context, Context.OMPArrayShapingTy, Base,
4877                                      LParenLoc, RParenLoc, NewDims, Brackets);
4878 }
4879 
4880 ExprResult Sema::ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc,
4881                                       SourceLocation LLoc, SourceLocation RLoc,
4882                                       ArrayRef<OMPIteratorData> Data) {
4883   SmallVector<OMPIteratorExpr::IteratorDefinition, 4> ID;
4884   bool IsCorrect = true;
4885   for (const OMPIteratorData &D : Data) {
4886     TypeSourceInfo *TInfo = nullptr;
4887     SourceLocation StartLoc;
4888     QualType DeclTy;
4889     if (!D.Type.getAsOpaquePtr()) {
4890       // OpenMP 5.0, 2.1.6 Iterators
4891       // In an iterator-specifier, if the iterator-type is not specified then
4892       // the type of that iterator is of int type.
4893       DeclTy = Context.IntTy;
4894       StartLoc = D.DeclIdentLoc;
4895     } else {
4896       DeclTy = GetTypeFromParser(D.Type, &TInfo);
4897       StartLoc = TInfo->getTypeLoc().getBeginLoc();
4898     }
4899 
4900     bool IsDeclTyDependent = DeclTy->isDependentType() ||
4901                              DeclTy->containsUnexpandedParameterPack() ||
4902                              DeclTy->isInstantiationDependentType();
4903     if (!IsDeclTyDependent) {
4904       if (!DeclTy->isIntegralType(Context) && !DeclTy->isAnyPointerType()) {
4905         // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++
4906         // The iterator-type must be an integral or pointer type.
4907         Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer)
4908             << DeclTy;
4909         IsCorrect = false;
4910         continue;
4911       }
4912       if (DeclTy.isConstant(Context)) {
4913         // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++
4914         // The iterator-type must not be const qualified.
4915         Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer)
4916             << DeclTy;
4917         IsCorrect = false;
4918         continue;
4919       }
4920     }
4921 
4922     // Iterator declaration.
4923     assert(D.DeclIdent && "Identifier expected.");
4924     // Always try to create iterator declarator to avoid extra error messages
4925     // about unknown declarations use.
4926     auto *VD = VarDecl::Create(Context, CurContext, StartLoc, D.DeclIdentLoc,
4927                                D.DeclIdent, DeclTy, TInfo, SC_None);
4928     VD->setImplicit();
4929     if (S) {
4930       // Check for conflicting previous declaration.
4931       DeclarationNameInfo NameInfo(VD->getDeclName(), D.DeclIdentLoc);
4932       LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
4933                             ForVisibleRedeclaration);
4934       Previous.suppressDiagnostics();
4935       LookupName(Previous, S);
4936 
4937       FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false,
4938                            /*AllowInlineNamespace=*/false);
4939       if (!Previous.empty()) {
4940         NamedDecl *Old = Previous.getRepresentativeDecl();
4941         Diag(D.DeclIdentLoc, diag::err_redefinition) << VD->getDeclName();
4942         Diag(Old->getLocation(), diag::note_previous_definition);
4943       } else {
4944         PushOnScopeChains(VD, S);
4945       }
4946     } else {
4947       CurContext->addDecl(VD);
4948     }
4949     Expr *Begin = D.Range.Begin;
4950     if (!IsDeclTyDependent && Begin && !Begin->isTypeDependent()) {
4951       ExprResult BeginRes =
4952           PerformImplicitConversion(Begin, DeclTy, AA_Converting);
4953       Begin = BeginRes.get();
4954     }
4955     Expr *End = D.Range.End;
4956     if (!IsDeclTyDependent && End && !End->isTypeDependent()) {
4957       ExprResult EndRes = PerformImplicitConversion(End, DeclTy, AA_Converting);
4958       End = EndRes.get();
4959     }
4960     Expr *Step = D.Range.Step;
4961     if (!IsDeclTyDependent && Step && !Step->isTypeDependent()) {
4962       if (!Step->getType()->isIntegralType(Context)) {
4963         Diag(Step->getExprLoc(), diag::err_omp_iterator_step_not_integral)
4964             << Step << Step->getSourceRange();
4965         IsCorrect = false;
4966         continue;
4967       }
4968       llvm::APSInt Result;
4969       bool IsConstant = Step->isIntegerConstantExpr(Result, Context);
4970       // OpenMP 5.0, 2.1.6 Iterators, Restrictions
4971       // If the step expression of a range-specification equals zero, the
4972       // behavior is unspecified.
4973       if (IsConstant && Result.isNullValue()) {
4974         Diag(Step->getExprLoc(), diag::err_omp_iterator_step_constant_zero)
4975             << Step << Step->getSourceRange();
4976         IsCorrect = false;
4977         continue;
4978       }
4979     }
4980     if (!Begin || !End || !IsCorrect) {
4981       IsCorrect = false;
4982       continue;
4983     }
4984     OMPIteratorExpr::IteratorDefinition &IDElem = ID.emplace_back();
4985     IDElem.IteratorDecl = VD;
4986     IDElem.AssignmentLoc = D.AssignLoc;
4987     IDElem.Range.Begin = Begin;
4988     IDElem.Range.End = End;
4989     IDElem.Range.Step = Step;
4990     IDElem.ColonLoc = D.ColonLoc;
4991     IDElem.SecondColonLoc = D.SecColonLoc;
4992   }
4993   if (!IsCorrect) {
4994     // Invalidate all created iterator declarations if error is found.
4995     for (const OMPIteratorExpr::IteratorDefinition &D : ID) {
4996       if (Decl *ID = D.IteratorDecl)
4997         ID->setInvalidDecl();
4998     }
4999     return ExprError();
5000   }
5001   SmallVector<OMPIteratorHelperData, 4> Helpers;
5002   if (!CurContext->isDependentContext()) {
5003     // Build number of ityeration for each iteration range.
5004     // Ni = ((Stepi > 0) ? ((Endi + Stepi -1 - Begini)/Stepi) :
5005     // ((Begini-Stepi-1-Endi) / -Stepi);
5006     for (OMPIteratorExpr::IteratorDefinition &D : ID) {
5007       // (Endi - Begini)
5008       ExprResult Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, D.Range.End,
5009                                           D.Range.Begin);
5010       if(!Res.isUsable()) {
5011         IsCorrect = false;
5012         continue;
5013       }
5014       ExprResult St, St1;
5015       if (D.Range.Step) {
5016         St = D.Range.Step;
5017         // (Endi - Begini) + Stepi
5018         Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res.get(), St.get());
5019         if (!Res.isUsable()) {
5020           IsCorrect = false;
5021           continue;
5022         }
5023         // (Endi - Begini) + Stepi - 1
5024         Res =
5025             CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res.get(),
5026                                ActOnIntegerConstant(D.AssignmentLoc, 1).get());
5027         if (!Res.isUsable()) {
5028           IsCorrect = false;
5029           continue;
5030         }
5031         // ((Endi - Begini) + Stepi - 1) / Stepi
5032         Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res.get(), St.get());
5033         if (!Res.isUsable()) {
5034           IsCorrect = false;
5035           continue;
5036         }
5037         St1 = CreateBuiltinUnaryOp(D.AssignmentLoc, UO_Minus, D.Range.Step);
5038         // (Begini - Endi)
5039         ExprResult Res1 = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub,
5040                                              D.Range.Begin, D.Range.End);
5041         if (!Res1.isUsable()) {
5042           IsCorrect = false;
5043           continue;
5044         }
5045         // (Begini - Endi) - Stepi
5046         Res1 =
5047             CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res1.get(), St1.get());
5048         if (!Res1.isUsable()) {
5049           IsCorrect = false;
5050           continue;
5051         }
5052         // (Begini - Endi) - Stepi - 1
5053         Res1 =
5054             CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res1.get(),
5055                                ActOnIntegerConstant(D.AssignmentLoc, 1).get());
5056         if (!Res1.isUsable()) {
5057           IsCorrect = false;
5058           continue;
5059         }
5060         // ((Begini - Endi) - Stepi - 1) / (-Stepi)
5061         Res1 =
5062             CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res1.get(), St1.get());
5063         if (!Res1.isUsable()) {
5064           IsCorrect = false;
5065           continue;
5066         }
5067         // Stepi > 0.
5068         ExprResult CmpRes =
5069             CreateBuiltinBinOp(D.AssignmentLoc, BO_GT, D.Range.Step,
5070                                ActOnIntegerConstant(D.AssignmentLoc, 0).get());
5071         if (!CmpRes.isUsable()) {
5072           IsCorrect = false;
5073           continue;
5074         }
5075         Res = ActOnConditionalOp(D.AssignmentLoc, D.AssignmentLoc, CmpRes.get(),
5076                                  Res.get(), Res1.get());
5077         if (!Res.isUsable()) {
5078           IsCorrect = false;
5079           continue;
5080         }
5081       }
5082       Res = ActOnFinishFullExpr(Res.get(), /*DiscardedValue=*/false);
5083       if (!Res.isUsable()) {
5084         IsCorrect = false;
5085         continue;
5086       }
5087 
5088       // Build counter update.
5089       // Build counter.
5090       auto *CounterVD =
5091           VarDecl::Create(Context, CurContext, D.IteratorDecl->getBeginLoc(),
5092                           D.IteratorDecl->getBeginLoc(), nullptr,
5093                           Res.get()->getType(), nullptr, SC_None);
5094       CounterVD->setImplicit();
5095       ExprResult RefRes =
5096           BuildDeclRefExpr(CounterVD, CounterVD->getType(), VK_LValue,
5097                            D.IteratorDecl->getBeginLoc());
5098       // Build counter update.
5099       // I = Begini + counter * Stepi;
5100       ExprResult UpdateRes;
5101       if (D.Range.Step) {
5102         UpdateRes = CreateBuiltinBinOp(
5103             D.AssignmentLoc, BO_Mul,
5104             DefaultLvalueConversion(RefRes.get()).get(), St.get());
5105       } else {
5106         UpdateRes = DefaultLvalueConversion(RefRes.get());
5107       }
5108       if (!UpdateRes.isUsable()) {
5109         IsCorrect = false;
5110         continue;
5111       }
5112       UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, D.Range.Begin,
5113                                      UpdateRes.get());
5114       if (!UpdateRes.isUsable()) {
5115         IsCorrect = false;
5116         continue;
5117       }
5118       ExprResult VDRes =
5119           BuildDeclRefExpr(cast<VarDecl>(D.IteratorDecl),
5120                            cast<VarDecl>(D.IteratorDecl)->getType(), VK_LValue,
5121                            D.IteratorDecl->getBeginLoc());
5122       UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Assign, VDRes.get(),
5123                                      UpdateRes.get());
5124       if (!UpdateRes.isUsable()) {
5125         IsCorrect = false;
5126         continue;
5127       }
5128       UpdateRes =
5129           ActOnFinishFullExpr(UpdateRes.get(), /*DiscardedValue=*/true);
5130       if (!UpdateRes.isUsable()) {
5131         IsCorrect = false;
5132         continue;
5133       }
5134       ExprResult CounterUpdateRes =
5135           CreateBuiltinUnaryOp(D.AssignmentLoc, UO_PreInc, RefRes.get());
5136       if (!CounterUpdateRes.isUsable()) {
5137         IsCorrect = false;
5138         continue;
5139       }
5140       CounterUpdateRes =
5141           ActOnFinishFullExpr(CounterUpdateRes.get(), /*DiscardedValue=*/true);
5142       if (!CounterUpdateRes.isUsable()) {
5143         IsCorrect = false;
5144         continue;
5145       }
5146       OMPIteratorHelperData &HD = Helpers.emplace_back();
5147       HD.CounterVD = CounterVD;
5148       HD.Upper = Res.get();
5149       HD.Update = UpdateRes.get();
5150       HD.CounterUpdate = CounterUpdateRes.get();
5151     }
5152   } else {
5153     Helpers.assign(ID.size(), {});
5154   }
5155   if (!IsCorrect) {
5156     // Invalidate all created iterator declarations if error is found.
5157     for (const OMPIteratorExpr::IteratorDefinition &D : ID) {
5158       if (Decl *ID = D.IteratorDecl)
5159         ID->setInvalidDecl();
5160     }
5161     return ExprError();
5162   }
5163   return OMPIteratorExpr::Create(Context, Context.OMPIteratorTy, IteratorKwLoc,
5164                                  LLoc, RLoc, ID, Helpers);
5165 }
5166 
5167 ExprResult
5168 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
5169                                       Expr *Idx, SourceLocation RLoc) {
5170   Expr *LHSExp = Base;
5171   Expr *RHSExp = Idx;
5172 
5173   ExprValueKind VK = VK_LValue;
5174   ExprObjectKind OK = OK_Ordinary;
5175 
5176   // Per C++ core issue 1213, the result is an xvalue if either operand is
5177   // a non-lvalue array, and an lvalue otherwise.
5178   if (getLangOpts().CPlusPlus11) {
5179     for (auto *Op : {LHSExp, RHSExp}) {
5180       Op = Op->IgnoreImplicit();
5181       if (Op->getType()->isArrayType() && !Op->isLValue())
5182         VK = VK_XValue;
5183     }
5184   }
5185 
5186   // Perform default conversions.
5187   if (!LHSExp->getType()->getAs<VectorType>()) {
5188     ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
5189     if (Result.isInvalid())
5190       return ExprError();
5191     LHSExp = Result.get();
5192   }
5193   ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
5194   if (Result.isInvalid())
5195     return ExprError();
5196   RHSExp = Result.get();
5197 
5198   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
5199 
5200   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
5201   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
5202   // in the subscript position. As a result, we need to derive the array base
5203   // and index from the expression types.
5204   Expr *BaseExpr, *IndexExpr;
5205   QualType ResultType;
5206   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
5207     BaseExpr = LHSExp;
5208     IndexExpr = RHSExp;
5209     ResultType = Context.DependentTy;
5210   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
5211     BaseExpr = LHSExp;
5212     IndexExpr = RHSExp;
5213     ResultType = PTy->getPointeeType();
5214   } else if (const ObjCObjectPointerType *PTy =
5215                LHSTy->getAs<ObjCObjectPointerType>()) {
5216     BaseExpr = LHSExp;
5217     IndexExpr = RHSExp;
5218 
5219     // Use custom logic if this should be the pseudo-object subscript
5220     // expression.
5221     if (!LangOpts.isSubscriptPointerArithmetic())
5222       return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
5223                                           nullptr);
5224 
5225     ResultType = PTy->getPointeeType();
5226   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
5227      // Handle the uncommon case of "123[Ptr]".
5228     BaseExpr = RHSExp;
5229     IndexExpr = LHSExp;
5230     ResultType = PTy->getPointeeType();
5231   } else if (const ObjCObjectPointerType *PTy =
5232                RHSTy->getAs<ObjCObjectPointerType>()) {
5233      // Handle the uncommon case of "123[Ptr]".
5234     BaseExpr = RHSExp;
5235     IndexExpr = LHSExp;
5236     ResultType = PTy->getPointeeType();
5237     if (!LangOpts.isSubscriptPointerArithmetic()) {
5238       Diag(LLoc, diag::err_subscript_nonfragile_interface)
5239         << ResultType << BaseExpr->getSourceRange();
5240       return ExprError();
5241     }
5242   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
5243     BaseExpr = LHSExp;    // vectors: V[123]
5244     IndexExpr = RHSExp;
5245     // We apply C++ DR1213 to vector subscripting too.
5246     if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_RValue) {
5247       ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
5248       if (Materialized.isInvalid())
5249         return ExprError();
5250       LHSExp = Materialized.get();
5251     }
5252     VK = LHSExp->getValueKind();
5253     if (VK != VK_RValue)
5254       OK = OK_VectorComponent;
5255 
5256     ResultType = VTy->getElementType();
5257     QualType BaseType = BaseExpr->getType();
5258     Qualifiers BaseQuals = BaseType.getQualifiers();
5259     Qualifiers MemberQuals = ResultType.getQualifiers();
5260     Qualifiers Combined = BaseQuals + MemberQuals;
5261     if (Combined != MemberQuals)
5262       ResultType = Context.getQualifiedType(ResultType, Combined);
5263   } else if (LHSTy->isArrayType()) {
5264     // If we see an array that wasn't promoted by
5265     // DefaultFunctionArrayLvalueConversion, it must be an array that
5266     // wasn't promoted because of the C90 rule that doesn't
5267     // allow promoting non-lvalue arrays.  Warn, then
5268     // force the promotion here.
5269     Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5270         << LHSExp->getSourceRange();
5271     LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
5272                                CK_ArrayToPointerDecay).get();
5273     LHSTy = LHSExp->getType();
5274 
5275     BaseExpr = LHSExp;
5276     IndexExpr = RHSExp;
5277     ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
5278   } else if (RHSTy->isArrayType()) {
5279     // Same as previous, except for 123[f().a] case
5280     Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5281         << RHSExp->getSourceRange();
5282     RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
5283                                CK_ArrayToPointerDecay).get();
5284     RHSTy = RHSExp->getType();
5285 
5286     BaseExpr = RHSExp;
5287     IndexExpr = LHSExp;
5288     ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
5289   } else {
5290     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
5291        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
5292   }
5293   // C99 6.5.2.1p1
5294   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
5295     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
5296                      << IndexExpr->getSourceRange());
5297 
5298   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5299        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5300          && !IndexExpr->isTypeDependent())
5301     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
5302 
5303   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5304   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5305   // type. Note that Functions are not objects, and that (in C99 parlance)
5306   // incomplete types are not object types.
5307   if (ResultType->isFunctionType()) {
5308     Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type)
5309         << ResultType << BaseExpr->getSourceRange();
5310     return ExprError();
5311   }
5312 
5313   if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
5314     // GNU extension: subscripting on pointer to void
5315     Diag(LLoc, diag::ext_gnu_subscript_void_type)
5316       << BaseExpr->getSourceRange();
5317 
5318     // C forbids expressions of unqualified void type from being l-values.
5319     // See IsCForbiddenLValueType.
5320     if (!ResultType.hasQualifiers()) VK = VK_RValue;
5321   } else if (!ResultType->isDependentType() &&
5322              RequireCompleteSizedType(
5323                  LLoc, ResultType,
5324                  diag::err_subscript_incomplete_or_sizeless_type, BaseExpr))
5325     return ExprError();
5326 
5327   assert(VK == VK_RValue || LangOpts.CPlusPlus ||
5328          !ResultType.isCForbiddenLValueType());
5329 
5330   if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() &&
5331       FunctionScopes.size() > 1) {
5332     if (auto *TT =
5333             LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) {
5334       for (auto I = FunctionScopes.rbegin(),
5335                 E = std::prev(FunctionScopes.rend());
5336            I != E; ++I) {
5337         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
5338         if (CSI == nullptr)
5339           break;
5340         DeclContext *DC = nullptr;
5341         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
5342           DC = LSI->CallOperator;
5343         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
5344           DC = CRSI->TheCapturedDecl;
5345         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
5346           DC = BSI->TheDecl;
5347         if (DC) {
5348           if (DC->containsDecl(TT->getDecl()))
5349             break;
5350           captureVariablyModifiedType(
5351               Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI);
5352         }
5353       }
5354     }
5355   }
5356 
5357   return new (Context)
5358       ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
5359 }
5360 
5361 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
5362                                   ParmVarDecl *Param) {
5363   if (Param->hasUnparsedDefaultArg()) {
5364     Diag(CallLoc,
5365          diag::err_use_of_default_argument_to_function_declared_later) <<
5366       FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
5367     Diag(UnparsedDefaultArgLocs[Param],
5368          diag::note_default_argument_declared_here);
5369     return true;
5370   }
5371 
5372   if (Param->hasUninstantiatedDefaultArg()) {
5373     Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
5374 
5375     EnterExpressionEvaluationContext EvalContext(
5376         *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
5377 
5378     // Instantiate the expression.
5379     //
5380     // FIXME: Pass in a correct Pattern argument, otherwise
5381     // getTemplateInstantiationArgs uses the lexical context of FD, e.g.
5382     //
5383     // template<typename T>
5384     // struct A {
5385     //   static int FooImpl();
5386     //
5387     //   template<typename Tp>
5388     //   // bug: default argument A<T>::FooImpl() is evaluated with 2-level
5389     //   // template argument list [[T], [Tp]], should be [[Tp]].
5390     //   friend A<Tp> Foo(int a);
5391     // };
5392     //
5393     // template<typename T>
5394     // A<T> Foo(int a = A<T>::FooImpl());
5395     MultiLevelTemplateArgumentList MutiLevelArgList
5396       = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true);
5397 
5398     InstantiatingTemplate Inst(*this, CallLoc, Param,
5399                                MutiLevelArgList.getInnermost());
5400     if (Inst.isInvalid())
5401       return true;
5402     if (Inst.isAlreadyInstantiating()) {
5403       Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
5404       Param->setInvalidDecl();
5405       return true;
5406     }
5407 
5408     ExprResult Result;
5409     {
5410       // C++ [dcl.fct.default]p5:
5411       //   The names in the [default argument] expression are bound, and
5412       //   the semantic constraints are checked, at the point where the
5413       //   default argument expression appears.
5414       ContextRAII SavedContext(*this, FD);
5415       LocalInstantiationScope Local(*this);
5416       runWithSufficientStackSpace(CallLoc, [&] {
5417         Result = SubstInitializer(UninstExpr, MutiLevelArgList,
5418                                   /*DirectInit*/false);
5419       });
5420     }
5421     if (Result.isInvalid())
5422       return true;
5423 
5424     // Check the expression as an initializer for the parameter.
5425     InitializedEntity Entity
5426       = InitializedEntity::InitializeParameter(Context, Param);
5427     InitializationKind Kind = InitializationKind::CreateCopy(
5428         Param->getLocation(),
5429         /*FIXME:EqualLoc*/ UninstExpr->getBeginLoc());
5430     Expr *ResultE = Result.getAs<Expr>();
5431 
5432     InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
5433     Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
5434     if (Result.isInvalid())
5435       return true;
5436 
5437     Result =
5438         ActOnFinishFullExpr(Result.getAs<Expr>(), Param->getOuterLocStart(),
5439                             /*DiscardedValue*/ false);
5440     if (Result.isInvalid())
5441       return true;
5442 
5443     // Remember the instantiated default argument.
5444     Param->setDefaultArg(Result.getAs<Expr>());
5445     if (ASTMutationListener *L = getASTMutationListener()) {
5446       L->DefaultArgumentInstantiated(Param);
5447     }
5448   }
5449 
5450   // If the default argument expression is not set yet, we are building it now.
5451   if (!Param->hasInit()) {
5452     Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
5453     Diag(CallLoc, diag::note_recursive_default_argument_used_here);
5454     Param->setInvalidDecl();
5455     return true;
5456   }
5457 
5458   // If the default expression creates temporaries, we need to
5459   // push them to the current stack of expression temporaries so they'll
5460   // be properly destroyed.
5461   // FIXME: We should really be rebuilding the default argument with new
5462   // bound temporaries; see the comment in PR5810.
5463   // We don't need to do that with block decls, though, because
5464   // blocks in default argument expression can never capture anything.
5465   if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
5466     // Set the "needs cleanups" bit regardless of whether there are
5467     // any explicit objects.
5468     Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
5469 
5470     // Append all the objects to the cleanup list.  Right now, this
5471     // should always be a no-op, because blocks in default argument
5472     // expressions should never be able to capture anything.
5473     assert(!Init->getNumObjects() &&
5474            "default argument expression has capturing blocks?");
5475   }
5476 
5477   // We already type-checked the argument, so we know it works.
5478   // Just mark all of the declarations in this potentially-evaluated expression
5479   // as being "referenced".
5480   EnterExpressionEvaluationContext EvalContext(
5481       *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
5482   MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
5483                                    /*SkipLocalVariables=*/true);
5484   return false;
5485 }
5486 
5487 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
5488                                         FunctionDecl *FD, ParmVarDecl *Param) {
5489   if (CheckCXXDefaultArgExpr(CallLoc, FD, Param))
5490     return ExprError();
5491   return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext);
5492 }
5493 
5494 Sema::VariadicCallType
5495 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
5496                           Expr *Fn) {
5497   if (Proto && Proto->isVariadic()) {
5498     if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
5499       return VariadicConstructor;
5500     else if (Fn && Fn->getType()->isBlockPointerType())
5501       return VariadicBlock;
5502     else if (FDecl) {
5503       if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5504         if (Method->isInstance())
5505           return VariadicMethod;
5506     } else if (Fn && Fn->getType() == Context.BoundMemberTy)
5507       return VariadicMethod;
5508     return VariadicFunction;
5509   }
5510   return VariadicDoesNotApply;
5511 }
5512 
5513 namespace {
5514 class FunctionCallCCC final : public FunctionCallFilterCCC {
5515 public:
5516   FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
5517                   unsigned NumArgs, MemberExpr *ME)
5518       : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
5519         FunctionName(FuncName) {}
5520 
5521   bool ValidateCandidate(const TypoCorrection &candidate) override {
5522     if (!candidate.getCorrectionSpecifier() ||
5523         candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
5524       return false;
5525     }
5526 
5527     return FunctionCallFilterCCC::ValidateCandidate(candidate);
5528   }
5529 
5530   std::unique_ptr<CorrectionCandidateCallback> clone() override {
5531     return std::make_unique<FunctionCallCCC>(*this);
5532   }
5533 
5534 private:
5535   const IdentifierInfo *const FunctionName;
5536 };
5537 }
5538 
5539 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
5540                                                FunctionDecl *FDecl,
5541                                                ArrayRef<Expr *> Args) {
5542   MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
5543   DeclarationName FuncName = FDecl->getDeclName();
5544   SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
5545 
5546   FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
5547   if (TypoCorrection Corrected = S.CorrectTypo(
5548           DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
5549           S.getScopeForContext(S.CurContext), nullptr, CCC,
5550           Sema::CTK_ErrorRecovery)) {
5551     if (NamedDecl *ND = Corrected.getFoundDecl()) {
5552       if (Corrected.isOverloaded()) {
5553         OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
5554         OverloadCandidateSet::iterator Best;
5555         for (NamedDecl *CD : Corrected) {
5556           if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
5557             S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
5558                                    OCS);
5559         }
5560         switch (OCS.BestViableFunction(S, NameLoc, Best)) {
5561         case OR_Success:
5562           ND = Best->FoundDecl;
5563           Corrected.setCorrectionDecl(ND);
5564           break;
5565         default:
5566           break;
5567         }
5568       }
5569       ND = ND->getUnderlyingDecl();
5570       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
5571         return Corrected;
5572     }
5573   }
5574   return TypoCorrection();
5575 }
5576 
5577 /// ConvertArgumentsForCall - Converts the arguments specified in
5578 /// Args/NumArgs to the parameter types of the function FDecl with
5579 /// function prototype Proto. Call is the call expression itself, and
5580 /// Fn is the function expression. For a C++ member function, this
5581 /// routine does not attempt to convert the object argument. Returns
5582 /// true if the call is ill-formed.
5583 bool
5584 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
5585                               FunctionDecl *FDecl,
5586                               const FunctionProtoType *Proto,
5587                               ArrayRef<Expr *> Args,
5588                               SourceLocation RParenLoc,
5589                               bool IsExecConfig) {
5590   // Bail out early if calling a builtin with custom typechecking.
5591   if (FDecl)
5592     if (unsigned ID = FDecl->getBuiltinID())
5593       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
5594         return false;
5595 
5596   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
5597   // assignment, to the types of the corresponding parameter, ...
5598   unsigned NumParams = Proto->getNumParams();
5599   bool Invalid = false;
5600   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
5601   unsigned FnKind = Fn->getType()->isBlockPointerType()
5602                        ? 1 /* block */
5603                        : (IsExecConfig ? 3 /* kernel function (exec config) */
5604                                        : 0 /* function */);
5605 
5606   // If too few arguments are available (and we don't have default
5607   // arguments for the remaining parameters), don't make the call.
5608   if (Args.size() < NumParams) {
5609     if (Args.size() < MinArgs) {
5610       TypoCorrection TC;
5611       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5612         unsigned diag_id =
5613             MinArgs == NumParams && !Proto->isVariadic()
5614                 ? diag::err_typecheck_call_too_few_args_suggest
5615                 : diag::err_typecheck_call_too_few_args_at_least_suggest;
5616         diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
5617                                         << static_cast<unsigned>(Args.size())
5618                                         << TC.getCorrectionRange());
5619       } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
5620         Diag(RParenLoc,
5621              MinArgs == NumParams && !Proto->isVariadic()
5622                  ? diag::err_typecheck_call_too_few_args_one
5623                  : diag::err_typecheck_call_too_few_args_at_least_one)
5624             << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
5625       else
5626         Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
5627                             ? diag::err_typecheck_call_too_few_args
5628                             : diag::err_typecheck_call_too_few_args_at_least)
5629             << FnKind << MinArgs << static_cast<unsigned>(Args.size())
5630             << Fn->getSourceRange();
5631 
5632       // Emit the location of the prototype.
5633       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5634         Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
5635 
5636       return true;
5637     }
5638     // We reserve space for the default arguments when we create
5639     // the call expression, before calling ConvertArgumentsForCall.
5640     assert((Call->getNumArgs() == NumParams) &&
5641            "We should have reserved space for the default arguments before!");
5642   }
5643 
5644   // If too many are passed and not variadic, error on the extras and drop
5645   // them.
5646   if (Args.size() > NumParams) {
5647     if (!Proto->isVariadic()) {
5648       TypoCorrection TC;
5649       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5650         unsigned diag_id =
5651             MinArgs == NumParams && !Proto->isVariadic()
5652                 ? diag::err_typecheck_call_too_many_args_suggest
5653                 : diag::err_typecheck_call_too_many_args_at_most_suggest;
5654         diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
5655                                         << static_cast<unsigned>(Args.size())
5656                                         << TC.getCorrectionRange());
5657       } else if (NumParams == 1 && FDecl &&
5658                  FDecl->getParamDecl(0)->getDeclName())
5659         Diag(Args[NumParams]->getBeginLoc(),
5660              MinArgs == NumParams
5661                  ? diag::err_typecheck_call_too_many_args_one
5662                  : diag::err_typecheck_call_too_many_args_at_most_one)
5663             << FnKind << FDecl->getParamDecl(0)
5664             << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
5665             << SourceRange(Args[NumParams]->getBeginLoc(),
5666                            Args.back()->getEndLoc());
5667       else
5668         Diag(Args[NumParams]->getBeginLoc(),
5669              MinArgs == NumParams
5670                  ? diag::err_typecheck_call_too_many_args
5671                  : diag::err_typecheck_call_too_many_args_at_most)
5672             << FnKind << NumParams << static_cast<unsigned>(Args.size())
5673             << Fn->getSourceRange()
5674             << SourceRange(Args[NumParams]->getBeginLoc(),
5675                            Args.back()->getEndLoc());
5676 
5677       // Emit the location of the prototype.
5678       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5679         Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
5680 
5681       // This deletes the extra arguments.
5682       Call->shrinkNumArgs(NumParams);
5683       return true;
5684     }
5685   }
5686   SmallVector<Expr *, 8> AllArgs;
5687   VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
5688 
5689   Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args,
5690                                    AllArgs, CallType);
5691   if (Invalid)
5692     return true;
5693   unsigned TotalNumArgs = AllArgs.size();
5694   for (unsigned i = 0; i < TotalNumArgs; ++i)
5695     Call->setArg(i, AllArgs[i]);
5696 
5697   return false;
5698 }
5699 
5700 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
5701                                   const FunctionProtoType *Proto,
5702                                   unsigned FirstParam, ArrayRef<Expr *> Args,
5703                                   SmallVectorImpl<Expr *> &AllArgs,
5704                                   VariadicCallType CallType, bool AllowExplicit,
5705                                   bool IsListInitialization) {
5706   unsigned NumParams = Proto->getNumParams();
5707   bool Invalid = false;
5708   size_t ArgIx = 0;
5709   // Continue to check argument types (even if we have too few/many args).
5710   for (unsigned i = FirstParam; i < NumParams; i++) {
5711     QualType ProtoArgType = Proto->getParamType(i);
5712 
5713     Expr *Arg;
5714     ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
5715     if (ArgIx < Args.size()) {
5716       Arg = Args[ArgIx++];
5717 
5718       if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType,
5719                               diag::err_call_incomplete_argument, Arg))
5720         return true;
5721 
5722       // Strip the unbridged-cast placeholder expression off, if applicable.
5723       bool CFAudited = false;
5724       if (Arg->getType() == Context.ARCUnbridgedCastTy &&
5725           FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5726           (!Param || !Param->hasAttr<CFConsumedAttr>()))
5727         Arg = stripARCUnbridgedCast(Arg);
5728       else if (getLangOpts().ObjCAutoRefCount &&
5729                FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5730                (!Param || !Param->hasAttr<CFConsumedAttr>()))
5731         CFAudited = true;
5732 
5733       if (Proto->getExtParameterInfo(i).isNoEscape())
5734         if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
5735           BE->getBlockDecl()->setDoesNotEscape();
5736 
5737       InitializedEntity Entity =
5738           Param ? InitializedEntity::InitializeParameter(Context, Param,
5739                                                          ProtoArgType)
5740                 : InitializedEntity::InitializeParameter(
5741                       Context, ProtoArgType, Proto->isParamConsumed(i));
5742 
5743       // Remember that parameter belongs to a CF audited API.
5744       if (CFAudited)
5745         Entity.setParameterCFAudited();
5746 
5747       ExprResult ArgE = PerformCopyInitialization(
5748           Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
5749       if (ArgE.isInvalid())
5750         return true;
5751 
5752       Arg = ArgE.getAs<Expr>();
5753     } else {
5754       assert(Param && "can't use default arguments without a known callee");
5755 
5756       ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
5757       if (ArgExpr.isInvalid())
5758         return true;
5759 
5760       Arg = ArgExpr.getAs<Expr>();
5761     }
5762 
5763     // Check for array bounds violations for each argument to the call. This
5764     // check only triggers warnings when the argument isn't a more complex Expr
5765     // with its own checking, such as a BinaryOperator.
5766     CheckArrayAccess(Arg);
5767 
5768     // Check for violations of C99 static array rules (C99 6.7.5.3p7).
5769     CheckStaticArrayArgument(CallLoc, Param, Arg);
5770 
5771     AllArgs.push_back(Arg);
5772   }
5773 
5774   // If this is a variadic call, handle args passed through "...".
5775   if (CallType != VariadicDoesNotApply) {
5776     // Assume that extern "C" functions with variadic arguments that
5777     // return __unknown_anytype aren't *really* variadic.
5778     if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
5779         FDecl->isExternC()) {
5780       for (Expr *A : Args.slice(ArgIx)) {
5781         QualType paramType; // ignored
5782         ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
5783         Invalid |= arg.isInvalid();
5784         AllArgs.push_back(arg.get());
5785       }
5786 
5787     // Otherwise do argument promotion, (C99 6.5.2.2p7).
5788     } else {
5789       for (Expr *A : Args.slice(ArgIx)) {
5790         ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
5791         Invalid |= Arg.isInvalid();
5792         // Copy blocks to the heap.
5793         if (A->getType()->isBlockPointerType())
5794           maybeExtendBlockObject(Arg);
5795         AllArgs.push_back(Arg.get());
5796       }
5797     }
5798 
5799     // Check for array bounds violations.
5800     for (Expr *A : Args.slice(ArgIx))
5801       CheckArrayAccess(A);
5802   }
5803   return Invalid;
5804 }
5805 
5806 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
5807   TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
5808   if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
5809     TL = DTL.getOriginalLoc();
5810   if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
5811     S.Diag(PVD->getLocation(), diag::note_callee_static_array)
5812       << ATL.getLocalSourceRange();
5813 }
5814 
5815 /// CheckStaticArrayArgument - If the given argument corresponds to a static
5816 /// array parameter, check that it is non-null, and that if it is formed by
5817 /// array-to-pointer decay, the underlying array is sufficiently large.
5818 ///
5819 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
5820 /// array type derivation, then for each call to the function, the value of the
5821 /// corresponding actual argument shall provide access to the first element of
5822 /// an array with at least as many elements as specified by the size expression.
5823 void
5824 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
5825                                ParmVarDecl *Param,
5826                                const Expr *ArgExpr) {
5827   // Static array parameters are not supported in C++.
5828   if (!Param || getLangOpts().CPlusPlus)
5829     return;
5830 
5831   QualType OrigTy = Param->getOriginalType();
5832 
5833   const ArrayType *AT = Context.getAsArrayType(OrigTy);
5834   if (!AT || AT->getSizeModifier() != ArrayType::Static)
5835     return;
5836 
5837   if (ArgExpr->isNullPointerConstant(Context,
5838                                      Expr::NPC_NeverValueDependent)) {
5839     Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
5840     DiagnoseCalleeStaticArrayParam(*this, Param);
5841     return;
5842   }
5843 
5844   const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
5845   if (!CAT)
5846     return;
5847 
5848   const ConstantArrayType *ArgCAT =
5849     Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType());
5850   if (!ArgCAT)
5851     return;
5852 
5853   if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(),
5854                                              ArgCAT->getElementType())) {
5855     if (ArgCAT->getSize().ult(CAT->getSize())) {
5856       Diag(CallLoc, diag::warn_static_array_too_small)
5857           << ArgExpr->getSourceRange()
5858           << (unsigned)ArgCAT->getSize().getZExtValue()
5859           << (unsigned)CAT->getSize().getZExtValue() << 0;
5860       DiagnoseCalleeStaticArrayParam(*this, Param);
5861     }
5862     return;
5863   }
5864 
5865   Optional<CharUnits> ArgSize =
5866       getASTContext().getTypeSizeInCharsIfKnown(ArgCAT);
5867   Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT);
5868   if (ArgSize && ParmSize && *ArgSize < *ParmSize) {
5869     Diag(CallLoc, diag::warn_static_array_too_small)
5870         << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()
5871         << (unsigned)ParmSize->getQuantity() << 1;
5872     DiagnoseCalleeStaticArrayParam(*this, Param);
5873   }
5874 }
5875 
5876 /// Given a function expression of unknown-any type, try to rebuild it
5877 /// to have a function type.
5878 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
5879 
5880 /// Is the given type a placeholder that we need to lower out
5881 /// immediately during argument processing?
5882 static bool isPlaceholderToRemoveAsArg(QualType type) {
5883   // Placeholders are never sugared.
5884   const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
5885   if (!placeholder) return false;
5886 
5887   switch (placeholder->getKind()) {
5888   // Ignore all the non-placeholder types.
5889 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
5890   case BuiltinType::Id:
5891 #include "clang/Basic/OpenCLImageTypes.def"
5892 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
5893   case BuiltinType::Id:
5894 #include "clang/Basic/OpenCLExtensionTypes.def"
5895   // In practice we'll never use this, since all SVE types are sugared
5896   // via TypedefTypes rather than exposed directly as BuiltinTypes.
5897 #define SVE_TYPE(Name, Id, SingletonId) \
5898   case BuiltinType::Id:
5899 #include "clang/Basic/AArch64SVEACLETypes.def"
5900 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
5901 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
5902 #include "clang/AST/BuiltinTypes.def"
5903     return false;
5904 
5905   // We cannot lower out overload sets; they might validly be resolved
5906   // by the call machinery.
5907   case BuiltinType::Overload:
5908     return false;
5909 
5910   // Unbridged casts in ARC can be handled in some call positions and
5911   // should be left in place.
5912   case BuiltinType::ARCUnbridgedCast:
5913     return false;
5914 
5915   // Pseudo-objects should be converted as soon as possible.
5916   case BuiltinType::PseudoObject:
5917     return true;
5918 
5919   // The debugger mode could theoretically but currently does not try
5920   // to resolve unknown-typed arguments based on known parameter types.
5921   case BuiltinType::UnknownAny:
5922     return true;
5923 
5924   // These are always invalid as call arguments and should be reported.
5925   case BuiltinType::BoundMember:
5926   case BuiltinType::BuiltinFn:
5927   case BuiltinType::OMPArraySection:
5928   case BuiltinType::OMPArrayShaping:
5929   case BuiltinType::OMPIterator:
5930     return true;
5931 
5932   }
5933   llvm_unreachable("bad builtin type kind");
5934 }
5935 
5936 /// Check an argument list for placeholders that we won't try to
5937 /// handle later.
5938 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
5939   // Apply this processing to all the arguments at once instead of
5940   // dying at the first failure.
5941   bool hasInvalid = false;
5942   for (size_t i = 0, e = args.size(); i != e; i++) {
5943     if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
5944       ExprResult result = S.CheckPlaceholderExpr(args[i]);
5945       if (result.isInvalid()) hasInvalid = true;
5946       else args[i] = result.get();
5947     } else if (hasInvalid) {
5948       (void)S.CorrectDelayedTyposInExpr(args[i]);
5949     }
5950   }
5951   return hasInvalid;
5952 }
5953 
5954 /// If a builtin function has a pointer argument with no explicit address
5955 /// space, then it should be able to accept a pointer to any address
5956 /// space as input.  In order to do this, we need to replace the
5957 /// standard builtin declaration with one that uses the same address space
5958 /// as the call.
5959 ///
5960 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
5961 ///                  it does not contain any pointer arguments without
5962 ///                  an address space qualifer.  Otherwise the rewritten
5963 ///                  FunctionDecl is returned.
5964 /// TODO: Handle pointer return types.
5965 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
5966                                                 FunctionDecl *FDecl,
5967                                                 MultiExprArg ArgExprs) {
5968 
5969   QualType DeclType = FDecl->getType();
5970   const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
5971 
5972   if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT ||
5973       ArgExprs.size() < FT->getNumParams())
5974     return nullptr;
5975 
5976   bool NeedsNewDecl = false;
5977   unsigned i = 0;
5978   SmallVector<QualType, 8> OverloadParams;
5979 
5980   for (QualType ParamType : FT->param_types()) {
5981 
5982     // Convert array arguments to pointer to simplify type lookup.
5983     ExprResult ArgRes =
5984         Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
5985     if (ArgRes.isInvalid())
5986       return nullptr;
5987     Expr *Arg = ArgRes.get();
5988     QualType ArgType = Arg->getType();
5989     if (!ParamType->isPointerType() ||
5990         ParamType.hasAddressSpace() ||
5991         !ArgType->isPointerType() ||
5992         !ArgType->getPointeeType().hasAddressSpace()) {
5993       OverloadParams.push_back(ParamType);
5994       continue;
5995     }
5996 
5997     QualType PointeeType = ParamType->getPointeeType();
5998     if (PointeeType.hasAddressSpace())
5999       continue;
6000 
6001     NeedsNewDecl = true;
6002     LangAS AS = ArgType->getPointeeType().getAddressSpace();
6003 
6004     PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
6005     OverloadParams.push_back(Context.getPointerType(PointeeType));
6006   }
6007 
6008   if (!NeedsNewDecl)
6009     return nullptr;
6010 
6011   FunctionProtoType::ExtProtoInfo EPI;
6012   EPI.Variadic = FT->isVariadic();
6013   QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
6014                                                 OverloadParams, EPI);
6015   DeclContext *Parent = FDecl->getParent();
6016   FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
6017                                                     FDecl->getLocation(),
6018                                                     FDecl->getLocation(),
6019                                                     FDecl->getIdentifier(),
6020                                                     OverloadTy,
6021                                                     /*TInfo=*/nullptr,
6022                                                     SC_Extern, false,
6023                                                     /*hasPrototype=*/true);
6024   SmallVector<ParmVarDecl*, 16> Params;
6025   FT = cast<FunctionProtoType>(OverloadTy);
6026   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
6027     QualType ParamType = FT->getParamType(i);
6028     ParmVarDecl *Parm =
6029         ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
6030                                 SourceLocation(), nullptr, ParamType,
6031                                 /*TInfo=*/nullptr, SC_None, nullptr);
6032     Parm->setScopeInfo(0, i);
6033     Params.push_back(Parm);
6034   }
6035   OverloadDecl->setParams(Params);
6036   return OverloadDecl;
6037 }
6038 
6039 static void checkDirectCallValidity(Sema &S, const Expr *Fn,
6040                                     FunctionDecl *Callee,
6041                                     MultiExprArg ArgExprs) {
6042   // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
6043   // similar attributes) really don't like it when functions are called with an
6044   // invalid number of args.
6045   if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
6046                          /*PartialOverloading=*/false) &&
6047       !Callee->isVariadic())
6048     return;
6049   if (Callee->getMinRequiredArguments() > ArgExprs.size())
6050     return;
6051 
6052   if (const EnableIfAttr *Attr = S.CheckEnableIf(Callee, ArgExprs, true)) {
6053     S.Diag(Fn->getBeginLoc(),
6054            isa<CXXMethodDecl>(Callee)
6055                ? diag::err_ovl_no_viable_member_function_in_call
6056                : diag::err_ovl_no_viable_function_in_call)
6057         << Callee << Callee->getSourceRange();
6058     S.Diag(Callee->getLocation(),
6059            diag::note_ovl_candidate_disabled_by_function_cond_attr)
6060         << Attr->getCond()->getSourceRange() << Attr->getMessage();
6061     return;
6062   }
6063 }
6064 
6065 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(
6066     const UnresolvedMemberExpr *const UME, Sema &S) {
6067 
6068   const auto GetFunctionLevelDCIfCXXClass =
6069       [](Sema &S) -> const CXXRecordDecl * {
6070     const DeclContext *const DC = S.getFunctionLevelDeclContext();
6071     if (!DC || !DC->getParent())
6072       return nullptr;
6073 
6074     // If the call to some member function was made from within a member
6075     // function body 'M' return return 'M's parent.
6076     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
6077       return MD->getParent()->getCanonicalDecl();
6078     // else the call was made from within a default member initializer of a
6079     // class, so return the class.
6080     if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
6081       return RD->getCanonicalDecl();
6082     return nullptr;
6083   };
6084   // If our DeclContext is neither a member function nor a class (in the
6085   // case of a lambda in a default member initializer), we can't have an
6086   // enclosing 'this'.
6087 
6088   const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
6089   if (!CurParentClass)
6090     return false;
6091 
6092   // The naming class for implicit member functions call is the class in which
6093   // name lookup starts.
6094   const CXXRecordDecl *const NamingClass =
6095       UME->getNamingClass()->getCanonicalDecl();
6096   assert(NamingClass && "Must have naming class even for implicit access");
6097 
6098   // If the unresolved member functions were found in a 'naming class' that is
6099   // related (either the same or derived from) to the class that contains the
6100   // member function that itself contained the implicit member access.
6101 
6102   return CurParentClass == NamingClass ||
6103          CurParentClass->isDerivedFrom(NamingClass);
6104 }
6105 
6106 static void
6107 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
6108     Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
6109 
6110   if (!UME)
6111     return;
6112 
6113   LambdaScopeInfo *const CurLSI = S.getCurLambda();
6114   // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
6115   // already been captured, or if this is an implicit member function call (if
6116   // it isn't, an attempt to capture 'this' should already have been made).
6117   if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
6118       !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
6119     return;
6120 
6121   // Check if the naming class in which the unresolved members were found is
6122   // related (same as or is a base of) to the enclosing class.
6123 
6124   if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S))
6125     return;
6126 
6127 
6128   DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
6129   // If the enclosing function is not dependent, then this lambda is
6130   // capture ready, so if we can capture this, do so.
6131   if (!EnclosingFunctionCtx->isDependentContext()) {
6132     // If the current lambda and all enclosing lambdas can capture 'this' -
6133     // then go ahead and capture 'this' (since our unresolved overload set
6134     // contains at least one non-static member function).
6135     if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
6136       S.CheckCXXThisCapture(CallLoc);
6137   } else if (S.CurContext->isDependentContext()) {
6138     // ... since this is an implicit member reference, that might potentially
6139     // involve a 'this' capture, mark 'this' for potential capture in
6140     // enclosing lambdas.
6141     if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
6142       CurLSI->addPotentialThisCapture(CallLoc);
6143   }
6144 }
6145 
6146 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
6147                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
6148                                Expr *ExecConfig) {
6149   ExprResult Call =
6150       BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig);
6151   if (Call.isInvalid())
6152     return Call;
6153 
6154   // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier
6155   // language modes.
6156   if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) {
6157     if (ULE->hasExplicitTemplateArgs() &&
6158         ULE->decls_begin() == ULE->decls_end()) {
6159       Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus2a
6160                                  ? diag::warn_cxx17_compat_adl_only_template_id
6161                                  : diag::ext_adl_only_template_id)
6162           << ULE->getName();
6163     }
6164   }
6165 
6166   if (LangOpts.OpenMP)
6167     Call = ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc,
6168                            ExecConfig);
6169 
6170   return Call;
6171 }
6172 
6173 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments.
6174 /// This provides the location of the left/right parens and a list of comma
6175 /// locations.
6176 ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
6177                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
6178                                Expr *ExecConfig, bool IsExecConfig) {
6179   // Since this might be a postfix expression, get rid of ParenListExprs.
6180   ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
6181   if (Result.isInvalid()) return ExprError();
6182   Fn = Result.get();
6183 
6184   if (checkArgsForPlaceholders(*this, ArgExprs))
6185     return ExprError();
6186 
6187   if (getLangOpts().CPlusPlus) {
6188     // If this is a pseudo-destructor expression, build the call immediately.
6189     if (isa<CXXPseudoDestructorExpr>(Fn)) {
6190       if (!ArgExprs.empty()) {
6191         // Pseudo-destructor calls should not have any arguments.
6192         Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args)
6193             << FixItHint::CreateRemoval(
6194                    SourceRange(ArgExprs.front()->getBeginLoc(),
6195                                ArgExprs.back()->getEndLoc()));
6196       }
6197 
6198       return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy,
6199                               VK_RValue, RParenLoc);
6200     }
6201     if (Fn->getType() == Context.PseudoObjectTy) {
6202       ExprResult result = CheckPlaceholderExpr(Fn);
6203       if (result.isInvalid()) return ExprError();
6204       Fn = result.get();
6205     }
6206 
6207     // Determine whether this is a dependent call inside a C++ template,
6208     // in which case we won't do any semantic analysis now.
6209     if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) {
6210       if (ExecConfig) {
6211         return CUDAKernelCallExpr::Create(
6212             Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
6213             Context.DependentTy, VK_RValue, RParenLoc);
6214       } else {
6215 
6216         tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
6217             *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
6218             Fn->getBeginLoc());
6219 
6220         return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6221                                 VK_RValue, RParenLoc);
6222       }
6223     }
6224 
6225     // Determine whether this is a call to an object (C++ [over.call.object]).
6226     if (Fn->getType()->isRecordType())
6227       return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
6228                                           RParenLoc);
6229 
6230     if (Fn->getType() == Context.UnknownAnyTy) {
6231       ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6232       if (result.isInvalid()) return ExprError();
6233       Fn = result.get();
6234     }
6235 
6236     if (Fn->getType() == Context.BoundMemberTy) {
6237       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6238                                        RParenLoc);
6239     }
6240   }
6241 
6242   // Check for overloaded calls.  This can happen even in C due to extensions.
6243   if (Fn->getType() == Context.OverloadTy) {
6244     OverloadExpr::FindResult find = OverloadExpr::find(Fn);
6245 
6246     // We aren't supposed to apply this logic if there's an '&' involved.
6247     if (!find.HasFormOfMemberPointer) {
6248       if (Expr::hasAnyTypeDependentArguments(ArgExprs))
6249         return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6250                                 VK_RValue, RParenLoc);
6251       OverloadExpr *ovl = find.Expression;
6252       if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
6253         return BuildOverloadedCallExpr(
6254             Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6255             /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
6256       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6257                                        RParenLoc);
6258     }
6259   }
6260 
6261   // If we're directly calling a function, get the appropriate declaration.
6262   if (Fn->getType() == Context.UnknownAnyTy) {
6263     ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6264     if (result.isInvalid()) return ExprError();
6265     Fn = result.get();
6266   }
6267 
6268   Expr *NakedFn = Fn->IgnoreParens();
6269 
6270   bool CallingNDeclIndirectly = false;
6271   NamedDecl *NDecl = nullptr;
6272   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
6273     if (UnOp->getOpcode() == UO_AddrOf) {
6274       CallingNDeclIndirectly = true;
6275       NakedFn = UnOp->getSubExpr()->IgnoreParens();
6276     }
6277   }
6278 
6279   if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
6280     NDecl = DRE->getDecl();
6281 
6282     FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
6283     if (FDecl && FDecl->getBuiltinID()) {
6284       // Rewrite the function decl for this builtin by replacing parameters
6285       // with no explicit address space with the address space of the arguments
6286       // in ArgExprs.
6287       if ((FDecl =
6288                rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
6289         NDecl = FDecl;
6290         Fn = DeclRefExpr::Create(
6291             Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
6292             SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl,
6293             nullptr, DRE->isNonOdrUse());
6294       }
6295     }
6296   } else if (isa<MemberExpr>(NakedFn))
6297     NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
6298 
6299   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
6300     if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
6301                                       FD, /*Complain=*/true, Fn->getBeginLoc()))
6302       return ExprError();
6303 
6304     if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn))
6305       return ExprError();
6306 
6307     checkDirectCallValidity(*this, Fn, FD, ArgExprs);
6308   }
6309 
6310   return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
6311                                ExecConfig, IsExecConfig);
6312 }
6313 
6314 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
6315 ///
6316 /// __builtin_astype( value, dst type )
6317 ///
6318 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
6319                                  SourceLocation BuiltinLoc,
6320                                  SourceLocation RParenLoc) {
6321   ExprValueKind VK = VK_RValue;
6322   ExprObjectKind OK = OK_Ordinary;
6323   QualType DstTy = GetTypeFromParser(ParsedDestTy);
6324   QualType SrcTy = E->getType();
6325   if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
6326     return ExprError(Diag(BuiltinLoc,
6327                           diag::err_invalid_astype_of_different_size)
6328                      << DstTy
6329                      << SrcTy
6330                      << E->getSourceRange());
6331   return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
6332 }
6333 
6334 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
6335 /// provided arguments.
6336 ///
6337 /// __builtin_convertvector( value, dst type )
6338 ///
6339 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
6340                                         SourceLocation BuiltinLoc,
6341                                         SourceLocation RParenLoc) {
6342   TypeSourceInfo *TInfo;
6343   GetTypeFromParser(ParsedDestTy, &TInfo);
6344   return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
6345 }
6346 
6347 /// BuildResolvedCallExpr - Build a call to a resolved expression,
6348 /// i.e. an expression not of \p OverloadTy.  The expression should
6349 /// unary-convert to an expression of function-pointer or
6350 /// block-pointer type.
6351 ///
6352 /// \param NDecl the declaration being called, if available
6353 ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
6354                                        SourceLocation LParenLoc,
6355                                        ArrayRef<Expr *> Args,
6356                                        SourceLocation RParenLoc, Expr *Config,
6357                                        bool IsExecConfig, ADLCallKind UsesADL) {
6358   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
6359   unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
6360 
6361   // Functions with 'interrupt' attribute cannot be called directly.
6362   if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
6363     Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
6364     return ExprError();
6365   }
6366 
6367   // Interrupt handlers don't save off the VFP regs automatically on ARM,
6368   // so there's some risk when calling out to non-interrupt handler functions
6369   // that the callee might not preserve them. This is easy to diagnose here,
6370   // but can be very challenging to debug.
6371   if (auto *Caller = getCurFunctionDecl())
6372     if (Caller->hasAttr<ARMInterruptAttr>()) {
6373       bool VFP = Context.getTargetInfo().hasFeature("vfp");
6374       if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>()))
6375         Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention);
6376     }
6377 
6378   // Promote the function operand.
6379   // We special-case function promotion here because we only allow promoting
6380   // builtin functions to function pointers in the callee of a call.
6381   ExprResult Result;
6382   QualType ResultTy;
6383   if (BuiltinID &&
6384       Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
6385     // Extract the return type from the (builtin) function pointer type.
6386     // FIXME Several builtins still have setType in
6387     // Sema::CheckBuiltinFunctionCall. One should review their definitions in
6388     // Builtins.def to ensure they are correct before removing setType calls.
6389     QualType FnPtrTy = Context.getPointerType(FDecl->getType());
6390     Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get();
6391     ResultTy = FDecl->getCallResultType();
6392   } else {
6393     Result = CallExprUnaryConversions(Fn);
6394     ResultTy = Context.BoolTy;
6395   }
6396   if (Result.isInvalid())
6397     return ExprError();
6398   Fn = Result.get();
6399 
6400   // Check for a valid function type, but only if it is not a builtin which
6401   // requires custom type checking. These will be handled by
6402   // CheckBuiltinFunctionCall below just after creation of the call expression.
6403   const FunctionType *FuncT = nullptr;
6404   if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
6405   retry:
6406     if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
6407       // C99 6.5.2.2p1 - "The expression that denotes the called function shall
6408       // have type pointer to function".
6409       FuncT = PT->getPointeeType()->getAs<FunctionType>();
6410       if (!FuncT)
6411         return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
6412                          << Fn->getType() << Fn->getSourceRange());
6413     } else if (const BlockPointerType *BPT =
6414                    Fn->getType()->getAs<BlockPointerType>()) {
6415       FuncT = BPT->getPointeeType()->castAs<FunctionType>();
6416     } else {
6417       // Handle calls to expressions of unknown-any type.
6418       if (Fn->getType() == Context.UnknownAnyTy) {
6419         ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
6420         if (rewrite.isInvalid())
6421           return ExprError();
6422         Fn = rewrite.get();
6423         goto retry;
6424       }
6425 
6426       return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
6427                        << Fn->getType() << Fn->getSourceRange());
6428     }
6429   }
6430 
6431   // Get the number of parameters in the function prototype, if any.
6432   // We will allocate space for max(Args.size(), NumParams) arguments
6433   // in the call expression.
6434   const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT);
6435   unsigned NumParams = Proto ? Proto->getNumParams() : 0;
6436 
6437   CallExpr *TheCall;
6438   if (Config) {
6439     assert(UsesADL == ADLCallKind::NotADL &&
6440            "CUDAKernelCallExpr should not use ADL");
6441     TheCall =
6442         CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config), Args,
6443                                    ResultTy, VK_RValue, RParenLoc, NumParams);
6444   } else {
6445     TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue,
6446                                RParenLoc, NumParams, UsesADL);
6447   }
6448 
6449   if (!getLangOpts().CPlusPlus) {
6450     // Forget about the nulled arguments since typo correction
6451     // do not handle them well.
6452     TheCall->shrinkNumArgs(Args.size());
6453     // C cannot always handle TypoExpr nodes in builtin calls and direct
6454     // function calls as their argument checking don't necessarily handle
6455     // dependent types properly, so make sure any TypoExprs have been
6456     // dealt with.
6457     ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
6458     if (!Result.isUsable()) return ExprError();
6459     CallExpr *TheOldCall = TheCall;
6460     TheCall = dyn_cast<CallExpr>(Result.get());
6461     bool CorrectedTypos = TheCall != TheOldCall;
6462     if (!TheCall) return Result;
6463     Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
6464 
6465     // A new call expression node was created if some typos were corrected.
6466     // However it may not have been constructed with enough storage. In this
6467     // case, rebuild the node with enough storage. The waste of space is
6468     // immaterial since this only happens when some typos were corrected.
6469     if (CorrectedTypos && Args.size() < NumParams) {
6470       if (Config)
6471         TheCall = CUDAKernelCallExpr::Create(
6472             Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_RValue,
6473             RParenLoc, NumParams);
6474       else
6475         TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue,
6476                                    RParenLoc, NumParams, UsesADL);
6477     }
6478     // We can now handle the nulled arguments for the default arguments.
6479     TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams));
6480   }
6481 
6482   // Bail out early if calling a builtin with custom type checking.
6483   if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
6484     return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
6485 
6486   if (getLangOpts().CUDA) {
6487     if (Config) {
6488       // CUDA: Kernel calls must be to global functions
6489       if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
6490         return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
6491             << FDecl << Fn->getSourceRange());
6492 
6493       // CUDA: Kernel function must have 'void' return type
6494       if (!FuncT->getReturnType()->isVoidType() &&
6495           !FuncT->getReturnType()->getAs<AutoType>() &&
6496           !FuncT->getReturnType()->isInstantiationDependentType())
6497         return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
6498             << Fn->getType() << Fn->getSourceRange());
6499     } else {
6500       // CUDA: Calls to global functions must be configured
6501       if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
6502         return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
6503             << FDecl << Fn->getSourceRange());
6504     }
6505   }
6506 
6507   // Check for a valid return type
6508   if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall,
6509                           FDecl))
6510     return ExprError();
6511 
6512   // We know the result type of the call, set it.
6513   TheCall->setType(FuncT->getCallResultType(Context));
6514   TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
6515 
6516   if (Proto) {
6517     if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
6518                                 IsExecConfig))
6519       return ExprError();
6520   } else {
6521     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
6522 
6523     if (FDecl) {
6524       // Check if we have too few/too many template arguments, based
6525       // on our knowledge of the function definition.
6526       const FunctionDecl *Def = nullptr;
6527       if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
6528         Proto = Def->getType()->getAs<FunctionProtoType>();
6529        if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
6530           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
6531           << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
6532       }
6533 
6534       // If the function we're calling isn't a function prototype, but we have
6535       // a function prototype from a prior declaratiom, use that prototype.
6536       if (!FDecl->hasPrototype())
6537         Proto = FDecl->getType()->getAs<FunctionProtoType>();
6538     }
6539 
6540     // Promote the arguments (C99 6.5.2.2p6).
6541     for (unsigned i = 0, e = Args.size(); i != e; i++) {
6542       Expr *Arg = Args[i];
6543 
6544       if (Proto && i < Proto->getNumParams()) {
6545         InitializedEntity Entity = InitializedEntity::InitializeParameter(
6546             Context, Proto->getParamType(i), Proto->isParamConsumed(i));
6547         ExprResult ArgE =
6548             PerformCopyInitialization(Entity, SourceLocation(), Arg);
6549         if (ArgE.isInvalid())
6550           return true;
6551 
6552         Arg = ArgE.getAs<Expr>();
6553 
6554       } else {
6555         ExprResult ArgE = DefaultArgumentPromotion(Arg);
6556 
6557         if (ArgE.isInvalid())
6558           return true;
6559 
6560         Arg = ArgE.getAs<Expr>();
6561       }
6562 
6563       if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(),
6564                               diag::err_call_incomplete_argument, Arg))
6565         return ExprError();
6566 
6567       TheCall->setArg(i, Arg);
6568     }
6569   }
6570 
6571   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
6572     if (!Method->isStatic())
6573       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
6574         << Fn->getSourceRange());
6575 
6576   // Check for sentinels
6577   if (NDecl)
6578     DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
6579 
6580   // Do special checking on direct calls to functions.
6581   if (FDecl) {
6582     if (CheckFunctionCall(FDecl, TheCall, Proto))
6583       return ExprError();
6584 
6585     checkFortifiedBuiltinMemoryFunction(FDecl, TheCall);
6586 
6587     if (BuiltinID)
6588       return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
6589   } else if (NDecl) {
6590     if (CheckPointerCall(NDecl, TheCall, Proto))
6591       return ExprError();
6592   } else {
6593     if (CheckOtherCall(TheCall, Proto))
6594       return ExprError();
6595   }
6596 
6597   return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl);
6598 }
6599 
6600 ExprResult
6601 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
6602                            SourceLocation RParenLoc, Expr *InitExpr) {
6603   assert(Ty && "ActOnCompoundLiteral(): missing type");
6604   assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
6605 
6606   TypeSourceInfo *TInfo;
6607   QualType literalType = GetTypeFromParser(Ty, &TInfo);
6608   if (!TInfo)
6609     TInfo = Context.getTrivialTypeSourceInfo(literalType);
6610 
6611   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
6612 }
6613 
6614 ExprResult
6615 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
6616                                SourceLocation RParenLoc, Expr *LiteralExpr) {
6617   QualType literalType = TInfo->getType();
6618 
6619   if (literalType->isArrayType()) {
6620     if (RequireCompleteSizedType(
6621             LParenLoc, Context.getBaseElementType(literalType),
6622             diag::err_array_incomplete_or_sizeless_type,
6623             SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
6624       return ExprError();
6625     if (literalType->isVariableArrayType())
6626       return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
6627         << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
6628   } else if (!literalType->isDependentType() &&
6629              RequireCompleteType(LParenLoc, literalType,
6630                diag::err_typecheck_decl_incomplete_type,
6631                SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
6632     return ExprError();
6633 
6634   InitializedEntity Entity
6635     = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
6636   InitializationKind Kind
6637     = InitializationKind::CreateCStyleCast(LParenLoc,
6638                                            SourceRange(LParenLoc, RParenLoc),
6639                                            /*InitList=*/true);
6640   InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
6641   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
6642                                       &literalType);
6643   if (Result.isInvalid())
6644     return ExprError();
6645   LiteralExpr = Result.get();
6646 
6647   bool isFileScope = !CurContext->isFunctionOrMethod();
6648 
6649   // In C, compound literals are l-values for some reason.
6650   // For GCC compatibility, in C++, file-scope array compound literals with
6651   // constant initializers are also l-values, and compound literals are
6652   // otherwise prvalues.
6653   //
6654   // (GCC also treats C++ list-initialized file-scope array prvalues with
6655   // constant initializers as l-values, but that's non-conforming, so we don't
6656   // follow it there.)
6657   //
6658   // FIXME: It would be better to handle the lvalue cases as materializing and
6659   // lifetime-extending a temporary object, but our materialized temporaries
6660   // representation only supports lifetime extension from a variable, not "out
6661   // of thin air".
6662   // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
6663   // is bound to the result of applying array-to-pointer decay to the compound
6664   // literal.
6665   // FIXME: GCC supports compound literals of reference type, which should
6666   // obviously have a value kind derived from the kind of reference involved.
6667   ExprValueKind VK =
6668       (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
6669           ? VK_RValue
6670           : VK_LValue;
6671 
6672   if (isFileScope)
6673     if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr))
6674       for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {
6675         Expr *Init = ILE->getInit(i);
6676         ILE->setInit(i, ConstantExpr::Create(Context, Init));
6677       }
6678 
6679   auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
6680                                               VK, LiteralExpr, isFileScope);
6681   if (isFileScope) {
6682     if (!LiteralExpr->isTypeDependent() &&
6683         !LiteralExpr->isValueDependent() &&
6684         !literalType->isDependentType()) // C99 6.5.2.5p3
6685       if (CheckForConstantInitializer(LiteralExpr, literalType))
6686         return ExprError();
6687   } else if (literalType.getAddressSpace() != LangAS::opencl_private &&
6688              literalType.getAddressSpace() != LangAS::Default) {
6689     // Embedded-C extensions to C99 6.5.2.5:
6690     //   "If the compound literal occurs inside the body of a function, the
6691     //   type name shall not be qualified by an address-space qualifier."
6692     Diag(LParenLoc, diag::err_compound_literal_with_address_space)
6693       << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
6694     return ExprError();
6695   }
6696 
6697   if (!isFileScope && !getLangOpts().CPlusPlus) {
6698     // Compound literals that have automatic storage duration are destroyed at
6699     // the end of the scope in C; in C++, they're just temporaries.
6700 
6701     // Emit diagnostics if it is or contains a C union type that is non-trivial
6702     // to destruct.
6703     if (E->getType().hasNonTrivialToPrimitiveDestructCUnion())
6704       checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
6705                             NTCUC_CompoundLiteral, NTCUK_Destruct);
6706 
6707     // Diagnose jumps that enter or exit the lifetime of the compound literal.
6708     if (literalType.isDestructedType()) {
6709       Cleanup.setExprNeedsCleanups(true);
6710       ExprCleanupObjects.push_back(E);
6711       getCurFunction()->setHasBranchProtectedScope();
6712     }
6713   }
6714 
6715   if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
6716       E->getType().hasNonTrivialToPrimitiveCopyCUnion())
6717     checkNonTrivialCUnionInInitializer(E->getInitializer(),
6718                                        E->getInitializer()->getExprLoc());
6719 
6720   return MaybeBindToTemporary(E);
6721 }
6722 
6723 ExprResult
6724 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
6725                     SourceLocation RBraceLoc) {
6726   // Only produce each kind of designated initialization diagnostic once.
6727   SourceLocation FirstDesignator;
6728   bool DiagnosedArrayDesignator = false;
6729   bool DiagnosedNestedDesignator = false;
6730   bool DiagnosedMixedDesignator = false;
6731 
6732   // Check that any designated initializers are syntactically valid in the
6733   // current language mode.
6734   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
6735     if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) {
6736       if (FirstDesignator.isInvalid())
6737         FirstDesignator = DIE->getBeginLoc();
6738 
6739       if (!getLangOpts().CPlusPlus)
6740         break;
6741 
6742       if (!DiagnosedNestedDesignator && DIE->size() > 1) {
6743         DiagnosedNestedDesignator = true;
6744         Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested)
6745           << DIE->getDesignatorsSourceRange();
6746       }
6747 
6748       for (auto &Desig : DIE->designators()) {
6749         if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) {
6750           DiagnosedArrayDesignator = true;
6751           Diag(Desig.getBeginLoc(), diag::ext_designated_init_array)
6752             << Desig.getSourceRange();
6753         }
6754       }
6755 
6756       if (!DiagnosedMixedDesignator &&
6757           !isa<DesignatedInitExpr>(InitArgList[0])) {
6758         DiagnosedMixedDesignator = true;
6759         Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
6760           << DIE->getSourceRange();
6761         Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed)
6762           << InitArgList[0]->getSourceRange();
6763       }
6764     } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator &&
6765                isa<DesignatedInitExpr>(InitArgList[0])) {
6766       DiagnosedMixedDesignator = true;
6767       auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]);
6768       Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
6769         << DIE->getSourceRange();
6770       Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed)
6771         << InitArgList[I]->getSourceRange();
6772     }
6773   }
6774 
6775   if (FirstDesignator.isValid()) {
6776     // Only diagnose designated initiaization as a C++20 extension if we didn't
6777     // already diagnose use of (non-C++20) C99 designator syntax.
6778     if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator &&
6779         !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) {
6780       Diag(FirstDesignator, getLangOpts().CPlusPlus2a
6781                                 ? diag::warn_cxx17_compat_designated_init
6782                                 : diag::ext_cxx_designated_init);
6783     } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) {
6784       Diag(FirstDesignator, diag::ext_designated_init);
6785     }
6786   }
6787 
6788   return BuildInitList(LBraceLoc, InitArgList, RBraceLoc);
6789 }
6790 
6791 ExprResult
6792 Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
6793                     SourceLocation RBraceLoc) {
6794   // Semantic analysis for initializers is done by ActOnDeclarator() and
6795   // CheckInitializer() - it requires knowledge of the object being initialized.
6796 
6797   // Immediately handle non-overload placeholders.  Overloads can be
6798   // resolved contextually, but everything else here can't.
6799   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
6800     if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
6801       ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
6802 
6803       // Ignore failures; dropping the entire initializer list because
6804       // of one failure would be terrible for indexing/etc.
6805       if (result.isInvalid()) continue;
6806 
6807       InitArgList[I] = result.get();
6808     }
6809   }
6810 
6811   InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
6812                                                RBraceLoc);
6813   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
6814   return E;
6815 }
6816 
6817 /// Do an explicit extend of the given block pointer if we're in ARC.
6818 void Sema::maybeExtendBlockObject(ExprResult &E) {
6819   assert(E.get()->getType()->isBlockPointerType());
6820   assert(E.get()->isRValue());
6821 
6822   // Only do this in an r-value context.
6823   if (!getLangOpts().ObjCAutoRefCount) return;
6824 
6825   E = ImplicitCastExpr::Create(Context, E.get()->getType(),
6826                                CK_ARCExtendBlockObject, E.get(),
6827                                /*base path*/ nullptr, VK_RValue);
6828   Cleanup.setExprNeedsCleanups(true);
6829 }
6830 
6831 /// Prepare a conversion of the given expression to an ObjC object
6832 /// pointer type.
6833 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
6834   QualType type = E.get()->getType();
6835   if (type->isObjCObjectPointerType()) {
6836     return CK_BitCast;
6837   } else if (type->isBlockPointerType()) {
6838     maybeExtendBlockObject(E);
6839     return CK_BlockPointerToObjCPointerCast;
6840   } else {
6841     assert(type->isPointerType());
6842     return CK_CPointerToObjCPointerCast;
6843   }
6844 }
6845 
6846 /// Prepares for a scalar cast, performing all the necessary stages
6847 /// except the final cast and returning the kind required.
6848 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
6849   // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
6850   // Also, callers should have filtered out the invalid cases with
6851   // pointers.  Everything else should be possible.
6852 
6853   QualType SrcTy = Src.get()->getType();
6854   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
6855     return CK_NoOp;
6856 
6857   switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
6858   case Type::STK_MemberPointer:
6859     llvm_unreachable("member pointer type in C");
6860 
6861   case Type::STK_CPointer:
6862   case Type::STK_BlockPointer:
6863   case Type::STK_ObjCObjectPointer:
6864     switch (DestTy->getScalarTypeKind()) {
6865     case Type::STK_CPointer: {
6866       LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
6867       LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
6868       if (SrcAS != DestAS)
6869         return CK_AddressSpaceConversion;
6870       if (Context.hasCvrSimilarType(SrcTy, DestTy))
6871         return CK_NoOp;
6872       return CK_BitCast;
6873     }
6874     case Type::STK_BlockPointer:
6875       return (SrcKind == Type::STK_BlockPointer
6876                 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
6877     case Type::STK_ObjCObjectPointer:
6878       if (SrcKind == Type::STK_ObjCObjectPointer)
6879         return CK_BitCast;
6880       if (SrcKind == Type::STK_CPointer)
6881         return CK_CPointerToObjCPointerCast;
6882       maybeExtendBlockObject(Src);
6883       return CK_BlockPointerToObjCPointerCast;
6884     case Type::STK_Bool:
6885       return CK_PointerToBoolean;
6886     case Type::STK_Integral:
6887       return CK_PointerToIntegral;
6888     case Type::STK_Floating:
6889     case Type::STK_FloatingComplex:
6890     case Type::STK_IntegralComplex:
6891     case Type::STK_MemberPointer:
6892     case Type::STK_FixedPoint:
6893       llvm_unreachable("illegal cast from pointer");
6894     }
6895     llvm_unreachable("Should have returned before this");
6896 
6897   case Type::STK_FixedPoint:
6898     switch (DestTy->getScalarTypeKind()) {
6899     case Type::STK_FixedPoint:
6900       return CK_FixedPointCast;
6901     case Type::STK_Bool:
6902       return CK_FixedPointToBoolean;
6903     case Type::STK_Integral:
6904       return CK_FixedPointToIntegral;
6905     case Type::STK_Floating:
6906     case Type::STK_IntegralComplex:
6907     case Type::STK_FloatingComplex:
6908       Diag(Src.get()->getExprLoc(),
6909            diag::err_unimplemented_conversion_with_fixed_point_type)
6910           << DestTy;
6911       return CK_IntegralCast;
6912     case Type::STK_CPointer:
6913     case Type::STK_ObjCObjectPointer:
6914     case Type::STK_BlockPointer:
6915     case Type::STK_MemberPointer:
6916       llvm_unreachable("illegal cast to pointer type");
6917     }
6918     llvm_unreachable("Should have returned before this");
6919 
6920   case Type::STK_Bool: // casting from bool is like casting from an integer
6921   case Type::STK_Integral:
6922     switch (DestTy->getScalarTypeKind()) {
6923     case Type::STK_CPointer:
6924     case Type::STK_ObjCObjectPointer:
6925     case Type::STK_BlockPointer:
6926       if (Src.get()->isNullPointerConstant(Context,
6927                                            Expr::NPC_ValueDependentIsNull))
6928         return CK_NullToPointer;
6929       return CK_IntegralToPointer;
6930     case Type::STK_Bool:
6931       return CK_IntegralToBoolean;
6932     case Type::STK_Integral:
6933       return CK_IntegralCast;
6934     case Type::STK_Floating:
6935       return CK_IntegralToFloating;
6936     case Type::STK_IntegralComplex:
6937       Src = ImpCastExprToType(Src.get(),
6938                       DestTy->castAs<ComplexType>()->getElementType(),
6939                       CK_IntegralCast);
6940       return CK_IntegralRealToComplex;
6941     case Type::STK_FloatingComplex:
6942       Src = ImpCastExprToType(Src.get(),
6943                       DestTy->castAs<ComplexType>()->getElementType(),
6944                       CK_IntegralToFloating);
6945       return CK_FloatingRealToComplex;
6946     case Type::STK_MemberPointer:
6947       llvm_unreachable("member pointer type in C");
6948     case Type::STK_FixedPoint:
6949       return CK_IntegralToFixedPoint;
6950     }
6951     llvm_unreachable("Should have returned before this");
6952 
6953   case Type::STK_Floating:
6954     switch (DestTy->getScalarTypeKind()) {
6955     case Type::STK_Floating:
6956       return CK_FloatingCast;
6957     case Type::STK_Bool:
6958       return CK_FloatingToBoolean;
6959     case Type::STK_Integral:
6960       return CK_FloatingToIntegral;
6961     case Type::STK_FloatingComplex:
6962       Src = ImpCastExprToType(Src.get(),
6963                               DestTy->castAs<ComplexType>()->getElementType(),
6964                               CK_FloatingCast);
6965       return CK_FloatingRealToComplex;
6966     case Type::STK_IntegralComplex:
6967       Src = ImpCastExprToType(Src.get(),
6968                               DestTy->castAs<ComplexType>()->getElementType(),
6969                               CK_FloatingToIntegral);
6970       return CK_IntegralRealToComplex;
6971     case Type::STK_CPointer:
6972     case Type::STK_ObjCObjectPointer:
6973     case Type::STK_BlockPointer:
6974       llvm_unreachable("valid float->pointer cast?");
6975     case Type::STK_MemberPointer:
6976       llvm_unreachable("member pointer type in C");
6977     case Type::STK_FixedPoint:
6978       Diag(Src.get()->getExprLoc(),
6979            diag::err_unimplemented_conversion_with_fixed_point_type)
6980           << SrcTy;
6981       return CK_IntegralCast;
6982     }
6983     llvm_unreachable("Should have returned before this");
6984 
6985   case Type::STK_FloatingComplex:
6986     switch (DestTy->getScalarTypeKind()) {
6987     case Type::STK_FloatingComplex:
6988       return CK_FloatingComplexCast;
6989     case Type::STK_IntegralComplex:
6990       return CK_FloatingComplexToIntegralComplex;
6991     case Type::STK_Floating: {
6992       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
6993       if (Context.hasSameType(ET, DestTy))
6994         return CK_FloatingComplexToReal;
6995       Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
6996       return CK_FloatingCast;
6997     }
6998     case Type::STK_Bool:
6999       return CK_FloatingComplexToBoolean;
7000     case Type::STK_Integral:
7001       Src = ImpCastExprToType(Src.get(),
7002                               SrcTy->castAs<ComplexType>()->getElementType(),
7003                               CK_FloatingComplexToReal);
7004       return CK_FloatingToIntegral;
7005     case Type::STK_CPointer:
7006     case Type::STK_ObjCObjectPointer:
7007     case Type::STK_BlockPointer:
7008       llvm_unreachable("valid complex float->pointer cast?");
7009     case Type::STK_MemberPointer:
7010       llvm_unreachable("member pointer type in C");
7011     case Type::STK_FixedPoint:
7012       Diag(Src.get()->getExprLoc(),
7013            diag::err_unimplemented_conversion_with_fixed_point_type)
7014           << SrcTy;
7015       return CK_IntegralCast;
7016     }
7017     llvm_unreachable("Should have returned before this");
7018 
7019   case Type::STK_IntegralComplex:
7020     switch (DestTy->getScalarTypeKind()) {
7021     case Type::STK_FloatingComplex:
7022       return CK_IntegralComplexToFloatingComplex;
7023     case Type::STK_IntegralComplex:
7024       return CK_IntegralComplexCast;
7025     case Type::STK_Integral: {
7026       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7027       if (Context.hasSameType(ET, DestTy))
7028         return CK_IntegralComplexToReal;
7029       Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
7030       return CK_IntegralCast;
7031     }
7032     case Type::STK_Bool:
7033       return CK_IntegralComplexToBoolean;
7034     case Type::STK_Floating:
7035       Src = ImpCastExprToType(Src.get(),
7036                               SrcTy->castAs<ComplexType>()->getElementType(),
7037                               CK_IntegralComplexToReal);
7038       return CK_IntegralToFloating;
7039     case Type::STK_CPointer:
7040     case Type::STK_ObjCObjectPointer:
7041     case Type::STK_BlockPointer:
7042       llvm_unreachable("valid complex int->pointer cast?");
7043     case Type::STK_MemberPointer:
7044       llvm_unreachable("member pointer type in C");
7045     case Type::STK_FixedPoint:
7046       Diag(Src.get()->getExprLoc(),
7047            diag::err_unimplemented_conversion_with_fixed_point_type)
7048           << SrcTy;
7049       return CK_IntegralCast;
7050     }
7051     llvm_unreachable("Should have returned before this");
7052   }
7053 
7054   llvm_unreachable("Unhandled scalar cast");
7055 }
7056 
7057 static bool breakDownVectorType(QualType type, uint64_t &len,
7058                                 QualType &eltType) {
7059   // Vectors are simple.
7060   if (const VectorType *vecType = type->getAs<VectorType>()) {
7061     len = vecType->getNumElements();
7062     eltType = vecType->getElementType();
7063     assert(eltType->isScalarType());
7064     return true;
7065   }
7066 
7067   // We allow lax conversion to and from non-vector types, but only if
7068   // they're real types (i.e. non-complex, non-pointer scalar types).
7069   if (!type->isRealType()) return false;
7070 
7071   len = 1;
7072   eltType = type;
7073   return true;
7074 }
7075 
7076 /// Are the two types lax-compatible vector types?  That is, given
7077 /// that one of them is a vector, do they have equal storage sizes,
7078 /// where the storage size is the number of elements times the element
7079 /// size?
7080 ///
7081 /// This will also return false if either of the types is neither a
7082 /// vector nor a real type.
7083 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
7084   assert(destTy->isVectorType() || srcTy->isVectorType());
7085 
7086   // Disallow lax conversions between scalars and ExtVectors (these
7087   // conversions are allowed for other vector types because common headers
7088   // depend on them).  Most scalar OP ExtVector cases are handled by the
7089   // splat path anyway, which does what we want (convert, not bitcast).
7090   // What this rules out for ExtVectors is crazy things like char4*float.
7091   if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
7092   if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
7093 
7094   uint64_t srcLen, destLen;
7095   QualType srcEltTy, destEltTy;
7096   if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false;
7097   if (!breakDownVectorType(destTy, destLen, destEltTy)) return false;
7098 
7099   // ASTContext::getTypeSize will return the size rounded up to a
7100   // power of 2, so instead of using that, we need to use the raw
7101   // element size multiplied by the element count.
7102   uint64_t srcEltSize = Context.getTypeSize(srcEltTy);
7103   uint64_t destEltSize = Context.getTypeSize(destEltTy);
7104 
7105   return (srcLen * srcEltSize == destLen * destEltSize);
7106 }
7107 
7108 /// Is this a legal conversion between two types, one of which is
7109 /// known to be a vector type?
7110 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
7111   assert(destTy->isVectorType() || srcTy->isVectorType());
7112 
7113   switch (Context.getLangOpts().getLaxVectorConversions()) {
7114   case LangOptions::LaxVectorConversionKind::None:
7115     return false;
7116 
7117   case LangOptions::LaxVectorConversionKind::Integer:
7118     if (!srcTy->isIntegralOrEnumerationType()) {
7119       auto *Vec = srcTy->getAs<VectorType>();
7120       if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7121         return false;
7122     }
7123     if (!destTy->isIntegralOrEnumerationType()) {
7124       auto *Vec = destTy->getAs<VectorType>();
7125       if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7126         return false;
7127     }
7128     // OK, integer (vector) -> integer (vector) bitcast.
7129     break;
7130 
7131     case LangOptions::LaxVectorConversionKind::All:
7132     break;
7133   }
7134 
7135   return areLaxCompatibleVectorTypes(srcTy, destTy);
7136 }
7137 
7138 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
7139                            CastKind &Kind) {
7140   assert(VectorTy->isVectorType() && "Not a vector type!");
7141 
7142   if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
7143     if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
7144       return Diag(R.getBegin(),
7145                   Ty->isVectorType() ?
7146                   diag::err_invalid_conversion_between_vectors :
7147                   diag::err_invalid_conversion_between_vector_and_integer)
7148         << VectorTy << Ty << R;
7149   } else
7150     return Diag(R.getBegin(),
7151                 diag::err_invalid_conversion_between_vector_and_scalar)
7152       << VectorTy << Ty << R;
7153 
7154   Kind = CK_BitCast;
7155   return false;
7156 }
7157 
7158 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
7159   QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
7160 
7161   if (DestElemTy == SplattedExpr->getType())
7162     return SplattedExpr;
7163 
7164   assert(DestElemTy->isFloatingType() ||
7165          DestElemTy->isIntegralOrEnumerationType());
7166 
7167   CastKind CK;
7168   if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
7169     // OpenCL requires that we convert `true` boolean expressions to -1, but
7170     // only when splatting vectors.
7171     if (DestElemTy->isFloatingType()) {
7172       // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
7173       // in two steps: boolean to signed integral, then to floating.
7174       ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
7175                                                  CK_BooleanToSignedIntegral);
7176       SplattedExpr = CastExprRes.get();
7177       CK = CK_IntegralToFloating;
7178     } else {
7179       CK = CK_BooleanToSignedIntegral;
7180     }
7181   } else {
7182     ExprResult CastExprRes = SplattedExpr;
7183     CK = PrepareScalarCast(CastExprRes, DestElemTy);
7184     if (CastExprRes.isInvalid())
7185       return ExprError();
7186     SplattedExpr = CastExprRes.get();
7187   }
7188   return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
7189 }
7190 
7191 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
7192                                     Expr *CastExpr, CastKind &Kind) {
7193   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
7194 
7195   QualType SrcTy = CastExpr->getType();
7196 
7197   // If SrcTy is a VectorType, the total size must match to explicitly cast to
7198   // an ExtVectorType.
7199   // In OpenCL, casts between vectors of different types are not allowed.
7200   // (See OpenCL 6.2).
7201   if (SrcTy->isVectorType()) {
7202     if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
7203         (getLangOpts().OpenCL &&
7204          !Context.hasSameUnqualifiedType(DestTy, SrcTy))) {
7205       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
7206         << DestTy << SrcTy << R;
7207       return ExprError();
7208     }
7209     Kind = CK_BitCast;
7210     return CastExpr;
7211   }
7212 
7213   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
7214   // conversion will take place first from scalar to elt type, and then
7215   // splat from elt type to vector.
7216   if (SrcTy->isPointerType())
7217     return Diag(R.getBegin(),
7218                 diag::err_invalid_conversion_between_vector_and_scalar)
7219       << DestTy << SrcTy << R;
7220 
7221   Kind = CK_VectorSplat;
7222   return prepareVectorSplat(DestTy, CastExpr);
7223 }
7224 
7225 ExprResult
7226 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
7227                     Declarator &D, ParsedType &Ty,
7228                     SourceLocation RParenLoc, Expr *CastExpr) {
7229   assert(!D.isInvalidType() && (CastExpr != nullptr) &&
7230          "ActOnCastExpr(): missing type or expr");
7231 
7232   TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
7233   if (D.isInvalidType())
7234     return ExprError();
7235 
7236   if (getLangOpts().CPlusPlus) {
7237     // Check that there are no default arguments (C++ only).
7238     CheckExtraCXXDefaultArguments(D);
7239   } else {
7240     // Make sure any TypoExprs have been dealt with.
7241     ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
7242     if (!Res.isUsable())
7243       return ExprError();
7244     CastExpr = Res.get();
7245   }
7246 
7247   checkUnusedDeclAttributes(D);
7248 
7249   QualType castType = castTInfo->getType();
7250   Ty = CreateParsedType(castType, castTInfo);
7251 
7252   bool isVectorLiteral = false;
7253 
7254   // Check for an altivec or OpenCL literal,
7255   // i.e. all the elements are integer constants.
7256   ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
7257   ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
7258   if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
7259        && castType->isVectorType() && (PE || PLE)) {
7260     if (PLE && PLE->getNumExprs() == 0) {
7261       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
7262       return ExprError();
7263     }
7264     if (PE || PLE->getNumExprs() == 1) {
7265       Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
7266       if (!E->getType()->isVectorType())
7267         isVectorLiteral = true;
7268     }
7269     else
7270       isVectorLiteral = true;
7271   }
7272 
7273   // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
7274   // then handle it as such.
7275   if (isVectorLiteral)
7276     return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
7277 
7278   // If the Expr being casted is a ParenListExpr, handle it specially.
7279   // This is not an AltiVec-style cast, so turn the ParenListExpr into a
7280   // sequence of BinOp comma operators.
7281   if (isa<ParenListExpr>(CastExpr)) {
7282     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
7283     if (Result.isInvalid()) return ExprError();
7284     CastExpr = Result.get();
7285   }
7286 
7287   if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
7288       !getSourceManager().isInSystemMacro(LParenLoc))
7289     Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
7290 
7291   CheckTollFreeBridgeCast(castType, CastExpr);
7292 
7293   CheckObjCBridgeRelatedCast(castType, CastExpr);
7294 
7295   DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
7296 
7297   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
7298 }
7299 
7300 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
7301                                     SourceLocation RParenLoc, Expr *E,
7302                                     TypeSourceInfo *TInfo) {
7303   assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
7304          "Expected paren or paren list expression");
7305 
7306   Expr **exprs;
7307   unsigned numExprs;
7308   Expr *subExpr;
7309   SourceLocation LiteralLParenLoc, LiteralRParenLoc;
7310   if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
7311     LiteralLParenLoc = PE->getLParenLoc();
7312     LiteralRParenLoc = PE->getRParenLoc();
7313     exprs = PE->getExprs();
7314     numExprs = PE->getNumExprs();
7315   } else { // isa<ParenExpr> by assertion at function entrance
7316     LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
7317     LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
7318     subExpr = cast<ParenExpr>(E)->getSubExpr();
7319     exprs = &subExpr;
7320     numExprs = 1;
7321   }
7322 
7323   QualType Ty = TInfo->getType();
7324   assert(Ty->isVectorType() && "Expected vector type");
7325 
7326   SmallVector<Expr *, 8> initExprs;
7327   const VectorType *VTy = Ty->castAs<VectorType>();
7328   unsigned numElems = VTy->getNumElements();
7329 
7330   // '(...)' form of vector initialization in AltiVec: the number of
7331   // initializers must be one or must match the size of the vector.
7332   // If a single value is specified in the initializer then it will be
7333   // replicated to all the components of the vector
7334   if (VTy->getVectorKind() == VectorType::AltiVecVector) {
7335     // The number of initializers must be one or must match the size of the
7336     // vector. If a single value is specified in the initializer then it will
7337     // be replicated to all the components of the vector
7338     if (numExprs == 1) {
7339       QualType ElemTy = VTy->getElementType();
7340       ExprResult Literal = DefaultLvalueConversion(exprs[0]);
7341       if (Literal.isInvalid())
7342         return ExprError();
7343       Literal = ImpCastExprToType(Literal.get(), ElemTy,
7344                                   PrepareScalarCast(Literal, ElemTy));
7345       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
7346     }
7347     else if (numExprs < numElems) {
7348       Diag(E->getExprLoc(),
7349            diag::err_incorrect_number_of_vector_initializers);
7350       return ExprError();
7351     }
7352     else
7353       initExprs.append(exprs, exprs + numExprs);
7354   }
7355   else {
7356     // For OpenCL, when the number of initializers is a single value,
7357     // it will be replicated to all components of the vector.
7358     if (getLangOpts().OpenCL &&
7359         VTy->getVectorKind() == VectorType::GenericVector &&
7360         numExprs == 1) {
7361         QualType ElemTy = VTy->getElementType();
7362         ExprResult Literal = DefaultLvalueConversion(exprs[0]);
7363         if (Literal.isInvalid())
7364           return ExprError();
7365         Literal = ImpCastExprToType(Literal.get(), ElemTy,
7366                                     PrepareScalarCast(Literal, ElemTy));
7367         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
7368     }
7369 
7370     initExprs.append(exprs, exprs + numExprs);
7371   }
7372   // FIXME: This means that pretty-printing the final AST will produce curly
7373   // braces instead of the original commas.
7374   InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
7375                                                    initExprs, LiteralRParenLoc);
7376   initE->setType(Ty);
7377   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
7378 }
7379 
7380 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
7381 /// the ParenListExpr into a sequence of comma binary operators.
7382 ExprResult
7383 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
7384   ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
7385   if (!E)
7386     return OrigExpr;
7387 
7388   ExprResult Result(E->getExpr(0));
7389 
7390   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
7391     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
7392                         E->getExpr(i));
7393 
7394   if (Result.isInvalid()) return ExprError();
7395 
7396   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
7397 }
7398 
7399 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
7400                                     SourceLocation R,
7401                                     MultiExprArg Val) {
7402   return ParenListExpr::Create(Context, L, Val, R);
7403 }
7404 
7405 /// Emit a specialized diagnostic when one expression is a null pointer
7406 /// constant and the other is not a pointer.  Returns true if a diagnostic is
7407 /// emitted.
7408 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
7409                                       SourceLocation QuestionLoc) {
7410   Expr *NullExpr = LHSExpr;
7411   Expr *NonPointerExpr = RHSExpr;
7412   Expr::NullPointerConstantKind NullKind =
7413       NullExpr->isNullPointerConstant(Context,
7414                                       Expr::NPC_ValueDependentIsNotNull);
7415 
7416   if (NullKind == Expr::NPCK_NotNull) {
7417     NullExpr = RHSExpr;
7418     NonPointerExpr = LHSExpr;
7419     NullKind =
7420         NullExpr->isNullPointerConstant(Context,
7421                                         Expr::NPC_ValueDependentIsNotNull);
7422   }
7423 
7424   if (NullKind == Expr::NPCK_NotNull)
7425     return false;
7426 
7427   if (NullKind == Expr::NPCK_ZeroExpression)
7428     return false;
7429 
7430   if (NullKind == Expr::NPCK_ZeroLiteral) {
7431     // In this case, check to make sure that we got here from a "NULL"
7432     // string in the source code.
7433     NullExpr = NullExpr->IgnoreParenImpCasts();
7434     SourceLocation loc = NullExpr->getExprLoc();
7435     if (!findMacroSpelling(loc, "NULL"))
7436       return false;
7437   }
7438 
7439   int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
7440   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
7441       << NonPointerExpr->getType() << DiagType
7442       << NonPointerExpr->getSourceRange();
7443   return true;
7444 }
7445 
7446 /// Return false if the condition expression is valid, true otherwise.
7447 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
7448   QualType CondTy = Cond->getType();
7449 
7450   // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
7451   if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
7452     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
7453       << CondTy << Cond->getSourceRange();
7454     return true;
7455   }
7456 
7457   // C99 6.5.15p2
7458   if (CondTy->isScalarType()) return false;
7459 
7460   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
7461     << CondTy << Cond->getSourceRange();
7462   return true;
7463 }
7464 
7465 /// Handle when one or both operands are void type.
7466 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
7467                                          ExprResult &RHS) {
7468     Expr *LHSExpr = LHS.get();
7469     Expr *RHSExpr = RHS.get();
7470 
7471     if (!LHSExpr->getType()->isVoidType())
7472       S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
7473           << RHSExpr->getSourceRange();
7474     if (!RHSExpr->getType()->isVoidType())
7475       S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
7476           << LHSExpr->getSourceRange();
7477     LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
7478     RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
7479     return S.Context.VoidTy;
7480 }
7481 
7482 /// Return false if the NullExpr can be promoted to PointerTy,
7483 /// true otherwise.
7484 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
7485                                         QualType PointerTy) {
7486   if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
7487       !NullExpr.get()->isNullPointerConstant(S.Context,
7488                                             Expr::NPC_ValueDependentIsNull))
7489     return true;
7490 
7491   NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
7492   return false;
7493 }
7494 
7495 /// Checks compatibility between two pointers and return the resulting
7496 /// type.
7497 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
7498                                                      ExprResult &RHS,
7499                                                      SourceLocation Loc) {
7500   QualType LHSTy = LHS.get()->getType();
7501   QualType RHSTy = RHS.get()->getType();
7502 
7503   if (S.Context.hasSameType(LHSTy, RHSTy)) {
7504     // Two identical pointers types are always compatible.
7505     return LHSTy;
7506   }
7507 
7508   QualType lhptee, rhptee;
7509 
7510   // Get the pointee types.
7511   bool IsBlockPointer = false;
7512   if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
7513     lhptee = LHSBTy->getPointeeType();
7514     rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
7515     IsBlockPointer = true;
7516   } else {
7517     lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
7518     rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
7519   }
7520 
7521   // C99 6.5.15p6: If both operands are pointers to compatible types or to
7522   // differently qualified versions of compatible types, the result type is
7523   // a pointer to an appropriately qualified version of the composite
7524   // type.
7525 
7526   // Only CVR-qualifiers exist in the standard, and the differently-qualified
7527   // clause doesn't make sense for our extensions. E.g. address space 2 should
7528   // be incompatible with address space 3: they may live on different devices or
7529   // anything.
7530   Qualifiers lhQual = lhptee.getQualifiers();
7531   Qualifiers rhQual = rhptee.getQualifiers();
7532 
7533   LangAS ResultAddrSpace = LangAS::Default;
7534   LangAS LAddrSpace = lhQual.getAddressSpace();
7535   LangAS RAddrSpace = rhQual.getAddressSpace();
7536 
7537   // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
7538   // spaces is disallowed.
7539   if (lhQual.isAddressSpaceSupersetOf(rhQual))
7540     ResultAddrSpace = LAddrSpace;
7541   else if (rhQual.isAddressSpaceSupersetOf(lhQual))
7542     ResultAddrSpace = RAddrSpace;
7543   else {
7544     S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
7545         << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
7546         << RHS.get()->getSourceRange();
7547     return QualType();
7548   }
7549 
7550   unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
7551   auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
7552   lhQual.removeCVRQualifiers();
7553   rhQual.removeCVRQualifiers();
7554 
7555   // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
7556   // (C99 6.7.3) for address spaces. We assume that the check should behave in
7557   // the same manner as it's defined for CVR qualifiers, so for OpenCL two
7558   // qual types are compatible iff
7559   //  * corresponded types are compatible
7560   //  * CVR qualifiers are equal
7561   //  * address spaces are equal
7562   // Thus for conditional operator we merge CVR and address space unqualified
7563   // pointees and if there is a composite type we return a pointer to it with
7564   // merged qualifiers.
7565   LHSCastKind =
7566       LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
7567   RHSCastKind =
7568       RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
7569   lhQual.removeAddressSpace();
7570   rhQual.removeAddressSpace();
7571 
7572   lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
7573   rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
7574 
7575   QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
7576 
7577   if (CompositeTy.isNull()) {
7578     // In this situation, we assume void* type. No especially good
7579     // reason, but this is what gcc does, and we do have to pick
7580     // to get a consistent AST.
7581     QualType incompatTy;
7582     incompatTy = S.Context.getPointerType(
7583         S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
7584     LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
7585     RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
7586 
7587     // FIXME: For OpenCL the warning emission and cast to void* leaves a room
7588     // for casts between types with incompatible address space qualifiers.
7589     // For the following code the compiler produces casts between global and
7590     // local address spaces of the corresponded innermost pointees:
7591     // local int *global *a;
7592     // global int *global *b;
7593     // a = (0 ? a : b); // see C99 6.5.16.1.p1.
7594     S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
7595         << LHSTy << RHSTy << LHS.get()->getSourceRange()
7596         << RHS.get()->getSourceRange();
7597 
7598     return incompatTy;
7599   }
7600 
7601   // The pointer types are compatible.
7602   // In case of OpenCL ResultTy should have the address space qualifier
7603   // which is a superset of address spaces of both the 2nd and the 3rd
7604   // operands of the conditional operator.
7605   QualType ResultTy = [&, ResultAddrSpace]() {
7606     if (S.getLangOpts().OpenCL) {
7607       Qualifiers CompositeQuals = CompositeTy.getQualifiers();
7608       CompositeQuals.setAddressSpace(ResultAddrSpace);
7609       return S.Context
7610           .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
7611           .withCVRQualifiers(MergedCVRQual);
7612     }
7613     return CompositeTy.withCVRQualifiers(MergedCVRQual);
7614   }();
7615   if (IsBlockPointer)
7616     ResultTy = S.Context.getBlockPointerType(ResultTy);
7617   else
7618     ResultTy = S.Context.getPointerType(ResultTy);
7619 
7620   LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
7621   RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
7622   return ResultTy;
7623 }
7624 
7625 /// Return the resulting type when the operands are both block pointers.
7626 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
7627                                                           ExprResult &LHS,
7628                                                           ExprResult &RHS,
7629                                                           SourceLocation Loc) {
7630   QualType LHSTy = LHS.get()->getType();
7631   QualType RHSTy = RHS.get()->getType();
7632 
7633   if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
7634     if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
7635       QualType destType = S.Context.getPointerType(S.Context.VoidTy);
7636       LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
7637       RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
7638       return destType;
7639     }
7640     S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
7641       << LHSTy << RHSTy << LHS.get()->getSourceRange()
7642       << RHS.get()->getSourceRange();
7643     return QualType();
7644   }
7645 
7646   // We have 2 block pointer types.
7647   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
7648 }
7649 
7650 /// Return the resulting type when the operands are both pointers.
7651 static QualType
7652 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
7653                                             ExprResult &RHS,
7654                                             SourceLocation Loc) {
7655   // get the pointer types
7656   QualType LHSTy = LHS.get()->getType();
7657   QualType RHSTy = RHS.get()->getType();
7658 
7659   // get the "pointed to" types
7660   QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
7661   QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
7662 
7663   // ignore qualifiers on void (C99 6.5.15p3, clause 6)
7664   if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
7665     // Figure out necessary qualifiers (C99 6.5.15p6)
7666     QualType destPointee
7667       = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
7668     QualType destType = S.Context.getPointerType(destPointee);
7669     // Add qualifiers if necessary.
7670     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
7671     // Promote to void*.
7672     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
7673     return destType;
7674   }
7675   if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
7676     QualType destPointee
7677       = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
7678     QualType destType = S.Context.getPointerType(destPointee);
7679     // Add qualifiers if necessary.
7680     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
7681     // Promote to void*.
7682     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
7683     return destType;
7684   }
7685 
7686   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
7687 }
7688 
7689 /// Return false if the first expression is not an integer and the second
7690 /// expression is not a pointer, true otherwise.
7691 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
7692                                         Expr* PointerExpr, SourceLocation Loc,
7693                                         bool IsIntFirstExpr) {
7694   if (!PointerExpr->getType()->isPointerType() ||
7695       !Int.get()->getType()->isIntegerType())
7696     return false;
7697 
7698   Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
7699   Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
7700 
7701   S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
7702     << Expr1->getType() << Expr2->getType()
7703     << Expr1->getSourceRange() << Expr2->getSourceRange();
7704   Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
7705                             CK_IntegralToPointer);
7706   return true;
7707 }
7708 
7709 /// Simple conversion between integer and floating point types.
7710 ///
7711 /// Used when handling the OpenCL conditional operator where the
7712 /// condition is a vector while the other operands are scalar.
7713 ///
7714 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
7715 /// types are either integer or floating type. Between the two
7716 /// operands, the type with the higher rank is defined as the "result
7717 /// type". The other operand needs to be promoted to the same type. No
7718 /// other type promotion is allowed. We cannot use
7719 /// UsualArithmeticConversions() for this purpose, since it always
7720 /// promotes promotable types.
7721 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
7722                                             ExprResult &RHS,
7723                                             SourceLocation QuestionLoc) {
7724   LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
7725   if (LHS.isInvalid())
7726     return QualType();
7727   RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
7728   if (RHS.isInvalid())
7729     return QualType();
7730 
7731   // For conversion purposes, we ignore any qualifiers.
7732   // For example, "const float" and "float" are equivalent.
7733   QualType LHSType =
7734     S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
7735   QualType RHSType =
7736     S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
7737 
7738   if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
7739     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
7740       << LHSType << LHS.get()->getSourceRange();
7741     return QualType();
7742   }
7743 
7744   if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
7745     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
7746       << RHSType << RHS.get()->getSourceRange();
7747     return QualType();
7748   }
7749 
7750   // If both types are identical, no conversion is needed.
7751   if (LHSType == RHSType)
7752     return LHSType;
7753 
7754   // Now handle "real" floating types (i.e. float, double, long double).
7755   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
7756     return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
7757                                  /*IsCompAssign = */ false);
7758 
7759   // Finally, we have two differing integer types.
7760   return handleIntegerConversion<doIntegralCast, doIntegralCast>
7761   (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
7762 }
7763 
7764 /// Convert scalar operands to a vector that matches the
7765 ///        condition in length.
7766 ///
7767 /// Used when handling the OpenCL conditional operator where the
7768 /// condition is a vector while the other operands are scalar.
7769 ///
7770 /// We first compute the "result type" for the scalar operands
7771 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
7772 /// into a vector of that type where the length matches the condition
7773 /// vector type. s6.11.6 requires that the element types of the result
7774 /// and the condition must have the same number of bits.
7775 static QualType
7776 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
7777                               QualType CondTy, SourceLocation QuestionLoc) {
7778   QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
7779   if (ResTy.isNull()) return QualType();
7780 
7781   const VectorType *CV = CondTy->getAs<VectorType>();
7782   assert(CV);
7783 
7784   // Determine the vector result type
7785   unsigned NumElements = CV->getNumElements();
7786   QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
7787 
7788   // Ensure that all types have the same number of bits
7789   if (S.Context.getTypeSize(CV->getElementType())
7790       != S.Context.getTypeSize(ResTy)) {
7791     // Since VectorTy is created internally, it does not pretty print
7792     // with an OpenCL name. Instead, we just print a description.
7793     std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
7794     SmallString<64> Str;
7795     llvm::raw_svector_ostream OS(Str);
7796     OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
7797     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
7798       << CondTy << OS.str();
7799     return QualType();
7800   }
7801 
7802   // Convert operands to the vector result type
7803   LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
7804   RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
7805 
7806   return VectorTy;
7807 }
7808 
7809 /// Return false if this is a valid OpenCL condition vector
7810 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
7811                                        SourceLocation QuestionLoc) {
7812   // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
7813   // integral type.
7814   const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
7815   assert(CondTy);
7816   QualType EleTy = CondTy->getElementType();
7817   if (EleTy->isIntegerType()) return false;
7818 
7819   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
7820     << Cond->getType() << Cond->getSourceRange();
7821   return true;
7822 }
7823 
7824 /// Return false if the vector condition type and the vector
7825 ///        result type are compatible.
7826 ///
7827 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
7828 /// number of elements, and their element types have the same number
7829 /// of bits.
7830 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
7831                               SourceLocation QuestionLoc) {
7832   const VectorType *CV = CondTy->getAs<VectorType>();
7833   const VectorType *RV = VecResTy->getAs<VectorType>();
7834   assert(CV && RV);
7835 
7836   if (CV->getNumElements() != RV->getNumElements()) {
7837     S.Diag(QuestionLoc, diag::err_conditional_vector_size)
7838       << CondTy << VecResTy;
7839     return true;
7840   }
7841 
7842   QualType CVE = CV->getElementType();
7843   QualType RVE = RV->getElementType();
7844 
7845   if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
7846     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
7847       << CondTy << VecResTy;
7848     return true;
7849   }
7850 
7851   return false;
7852 }
7853 
7854 /// Return the resulting type for the conditional operator in
7855 ///        OpenCL (aka "ternary selection operator", OpenCL v1.1
7856 ///        s6.3.i) when the condition is a vector type.
7857 static QualType
7858 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
7859                              ExprResult &LHS, ExprResult &RHS,
7860                              SourceLocation QuestionLoc) {
7861   Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
7862   if (Cond.isInvalid())
7863     return QualType();
7864   QualType CondTy = Cond.get()->getType();
7865 
7866   if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
7867     return QualType();
7868 
7869   // If either operand is a vector then find the vector type of the
7870   // result as specified in OpenCL v1.1 s6.3.i.
7871   if (LHS.get()->getType()->isVectorType() ||
7872       RHS.get()->getType()->isVectorType()) {
7873     QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
7874                                               /*isCompAssign*/false,
7875                                               /*AllowBothBool*/true,
7876                                               /*AllowBoolConversions*/false);
7877     if (VecResTy.isNull()) return QualType();
7878     // The result type must match the condition type as specified in
7879     // OpenCL v1.1 s6.11.6.
7880     if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
7881       return QualType();
7882     return VecResTy;
7883   }
7884 
7885   // Both operands are scalar.
7886   return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
7887 }
7888 
7889 /// Return true if the Expr is block type
7890 static bool checkBlockType(Sema &S, const Expr *E) {
7891   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
7892     QualType Ty = CE->getCallee()->getType();
7893     if (Ty->isBlockPointerType()) {
7894       S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
7895       return true;
7896     }
7897   }
7898   return false;
7899 }
7900 
7901 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
7902 /// In that case, LHS = cond.
7903 /// C99 6.5.15
7904 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
7905                                         ExprResult &RHS, ExprValueKind &VK,
7906                                         ExprObjectKind &OK,
7907                                         SourceLocation QuestionLoc) {
7908 
7909   ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
7910   if (!LHSResult.isUsable()) return QualType();
7911   LHS = LHSResult;
7912 
7913   ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
7914   if (!RHSResult.isUsable()) return QualType();
7915   RHS = RHSResult;
7916 
7917   // C++ is sufficiently different to merit its own checker.
7918   if (getLangOpts().CPlusPlus)
7919     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
7920 
7921   VK = VK_RValue;
7922   OK = OK_Ordinary;
7923 
7924   // The OpenCL operator with a vector condition is sufficiently
7925   // different to merit its own checker.
7926   if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType())
7927     return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
7928 
7929   // First, check the condition.
7930   Cond = UsualUnaryConversions(Cond.get());
7931   if (Cond.isInvalid())
7932     return QualType();
7933   if (checkCondition(*this, Cond.get(), QuestionLoc))
7934     return QualType();
7935 
7936   // Now check the two expressions.
7937   if (LHS.get()->getType()->isVectorType() ||
7938       RHS.get()->getType()->isVectorType())
7939     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
7940                                /*AllowBothBool*/true,
7941                                /*AllowBoolConversions*/false);
7942 
7943   QualType ResTy =
7944       UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional);
7945   if (LHS.isInvalid() || RHS.isInvalid())
7946     return QualType();
7947 
7948   QualType LHSTy = LHS.get()->getType();
7949   QualType RHSTy = RHS.get()->getType();
7950 
7951   // Diagnose attempts to convert between __float128 and long double where
7952   // such conversions currently can't be handled.
7953   if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
7954     Diag(QuestionLoc,
7955          diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
7956       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7957     return QualType();
7958   }
7959 
7960   // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
7961   // selection operator (?:).
7962   if (getLangOpts().OpenCL &&
7963       (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) {
7964     return QualType();
7965   }
7966 
7967   // If both operands have arithmetic type, do the usual arithmetic conversions
7968   // to find a common type: C99 6.5.15p3,5.
7969   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
7970     LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
7971     RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
7972 
7973     return ResTy;
7974   }
7975 
7976   // If both operands are the same structure or union type, the result is that
7977   // type.
7978   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
7979     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
7980       if (LHSRT->getDecl() == RHSRT->getDecl())
7981         // "If both the operands have structure or union type, the result has
7982         // that type."  This implies that CV qualifiers are dropped.
7983         return LHSTy.getUnqualifiedType();
7984     // FIXME: Type of conditional expression must be complete in C mode.
7985   }
7986 
7987   // C99 6.5.15p5: "If both operands have void type, the result has void type."
7988   // The following || allows only one side to be void (a GCC-ism).
7989   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
7990     return checkConditionalVoidType(*this, LHS, RHS);
7991   }
7992 
7993   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
7994   // the type of the other operand."
7995   if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
7996   if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
7997 
7998   // All objective-c pointer type analysis is done here.
7999   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
8000                                                         QuestionLoc);
8001   if (LHS.isInvalid() || RHS.isInvalid())
8002     return QualType();
8003   if (!compositeType.isNull())
8004     return compositeType;
8005 
8006 
8007   // Handle block pointer types.
8008   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
8009     return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
8010                                                      QuestionLoc);
8011 
8012   // Check constraints for C object pointers types (C99 6.5.15p3,6).
8013   if (LHSTy->isPointerType() && RHSTy->isPointerType())
8014     return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
8015                                                        QuestionLoc);
8016 
8017   // GCC compatibility: soften pointer/integer mismatch.  Note that
8018   // null pointers have been filtered out by this point.
8019   if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
8020       /*IsIntFirstExpr=*/true))
8021     return RHSTy;
8022   if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
8023       /*IsIntFirstExpr=*/false))
8024     return LHSTy;
8025 
8026   // Allow ?: operations in which both operands have the same
8027   // built-in sizeless type.
8028   if (LHSTy->isSizelessBuiltinType() && LHSTy == RHSTy)
8029     return LHSTy;
8030 
8031   // Emit a better diagnostic if one of the expressions is a null pointer
8032   // constant and the other is not a pointer type. In this case, the user most
8033   // likely forgot to take the address of the other expression.
8034   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
8035     return QualType();
8036 
8037   // Otherwise, the operands are not compatible.
8038   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
8039     << LHSTy << RHSTy << LHS.get()->getSourceRange()
8040     << RHS.get()->getSourceRange();
8041   return QualType();
8042 }
8043 
8044 /// FindCompositeObjCPointerType - Helper method to find composite type of
8045 /// two objective-c pointer types of the two input expressions.
8046 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
8047                                             SourceLocation QuestionLoc) {
8048   QualType LHSTy = LHS.get()->getType();
8049   QualType RHSTy = RHS.get()->getType();
8050 
8051   // Handle things like Class and struct objc_class*.  Here we case the result
8052   // to the pseudo-builtin, because that will be implicitly cast back to the
8053   // redefinition type if an attempt is made to access its fields.
8054   if (LHSTy->isObjCClassType() &&
8055       (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
8056     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
8057     return LHSTy;
8058   }
8059   if (RHSTy->isObjCClassType() &&
8060       (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
8061     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
8062     return RHSTy;
8063   }
8064   // And the same for struct objc_object* / id
8065   if (LHSTy->isObjCIdType() &&
8066       (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
8067     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
8068     return LHSTy;
8069   }
8070   if (RHSTy->isObjCIdType() &&
8071       (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
8072     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
8073     return RHSTy;
8074   }
8075   // And the same for struct objc_selector* / SEL
8076   if (Context.isObjCSelType(LHSTy) &&
8077       (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
8078     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
8079     return LHSTy;
8080   }
8081   if (Context.isObjCSelType(RHSTy) &&
8082       (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
8083     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
8084     return RHSTy;
8085   }
8086   // Check constraints for Objective-C object pointers types.
8087   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
8088 
8089     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
8090       // Two identical object pointer types are always compatible.
8091       return LHSTy;
8092     }
8093     const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
8094     const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
8095     QualType compositeType = LHSTy;
8096 
8097     // If both operands are interfaces and either operand can be
8098     // assigned to the other, use that type as the composite
8099     // type. This allows
8100     //   xxx ? (A*) a : (B*) b
8101     // where B is a subclass of A.
8102     //
8103     // Additionally, as for assignment, if either type is 'id'
8104     // allow silent coercion. Finally, if the types are
8105     // incompatible then make sure to use 'id' as the composite
8106     // type so the result is acceptable for sending messages to.
8107 
8108     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
8109     // It could return the composite type.
8110     if (!(compositeType =
8111           Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
8112       // Nothing more to do.
8113     } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
8114       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
8115     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
8116       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
8117     } else if ((LHSOPT->isObjCQualifiedIdType() ||
8118                 RHSOPT->isObjCQualifiedIdType()) &&
8119                Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT,
8120                                                          true)) {
8121       // Need to handle "id<xx>" explicitly.
8122       // GCC allows qualified id and any Objective-C type to devolve to
8123       // id. Currently localizing to here until clear this should be
8124       // part of ObjCQualifiedIdTypesAreCompatible.
8125       compositeType = Context.getObjCIdType();
8126     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
8127       compositeType = Context.getObjCIdType();
8128     } else {
8129       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
8130       << LHSTy << RHSTy
8131       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8132       QualType incompatTy = Context.getObjCIdType();
8133       LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
8134       RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
8135       return incompatTy;
8136     }
8137     // The object pointer types are compatible.
8138     LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
8139     RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
8140     return compositeType;
8141   }
8142   // Check Objective-C object pointer types and 'void *'
8143   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
8144     if (getLangOpts().ObjCAutoRefCount) {
8145       // ARC forbids the implicit conversion of object pointers to 'void *',
8146       // so these types are not compatible.
8147       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
8148           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8149       LHS = RHS = true;
8150       return QualType();
8151     }
8152     QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8153     QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
8154     QualType destPointee
8155     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
8156     QualType destType = Context.getPointerType(destPointee);
8157     // Add qualifiers if necessary.
8158     LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
8159     // Promote to void*.
8160     RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8161     return destType;
8162   }
8163   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
8164     if (getLangOpts().ObjCAutoRefCount) {
8165       // ARC forbids the implicit conversion of object pointers to 'void *',
8166       // so these types are not compatible.
8167       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
8168           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8169       LHS = RHS = true;
8170       return QualType();
8171     }
8172     QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
8173     QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8174     QualType destPointee
8175     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
8176     QualType destType = Context.getPointerType(destPointee);
8177     // Add qualifiers if necessary.
8178     RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
8179     // Promote to void*.
8180     LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8181     return destType;
8182   }
8183   return QualType();
8184 }
8185 
8186 /// SuggestParentheses - Emit a note with a fixit hint that wraps
8187 /// ParenRange in parentheses.
8188 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
8189                                const PartialDiagnostic &Note,
8190                                SourceRange ParenRange) {
8191   SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
8192   if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
8193       EndLoc.isValid()) {
8194     Self.Diag(Loc, Note)
8195       << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
8196       << FixItHint::CreateInsertion(EndLoc, ")");
8197   } else {
8198     // We can't display the parentheses, so just show the bare note.
8199     Self.Diag(Loc, Note) << ParenRange;
8200   }
8201 }
8202 
8203 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
8204   return BinaryOperator::isAdditiveOp(Opc) ||
8205          BinaryOperator::isMultiplicativeOp(Opc) ||
8206          BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or;
8207   // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and
8208   // not any of the logical operators.  Bitwise-xor is commonly used as a
8209   // logical-xor because there is no logical-xor operator.  The logical
8210   // operators, including uses of xor, have a high false positive rate for
8211   // precedence warnings.
8212 }
8213 
8214 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
8215 /// expression, either using a built-in or overloaded operator,
8216 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
8217 /// expression.
8218 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
8219                                    Expr **RHSExprs) {
8220   // Don't strip parenthesis: we should not warn if E is in parenthesis.
8221   E = E->IgnoreImpCasts();
8222   E = E->IgnoreConversionOperator();
8223   E = E->IgnoreImpCasts();
8224   if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
8225     E = MTE->getSubExpr();
8226     E = E->IgnoreImpCasts();
8227   }
8228 
8229   // Built-in binary operator.
8230   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
8231     if (IsArithmeticOp(OP->getOpcode())) {
8232       *Opcode = OP->getOpcode();
8233       *RHSExprs = OP->getRHS();
8234       return true;
8235     }
8236   }
8237 
8238   // Overloaded operator.
8239   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
8240     if (Call->getNumArgs() != 2)
8241       return false;
8242 
8243     // Make sure this is really a binary operator that is safe to pass into
8244     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
8245     OverloadedOperatorKind OO = Call->getOperator();
8246     if (OO < OO_Plus || OO > OO_Arrow ||
8247         OO == OO_PlusPlus || OO == OO_MinusMinus)
8248       return false;
8249 
8250     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
8251     if (IsArithmeticOp(OpKind)) {
8252       *Opcode = OpKind;
8253       *RHSExprs = Call->getArg(1);
8254       return true;
8255     }
8256   }
8257 
8258   return false;
8259 }
8260 
8261 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
8262 /// or is a logical expression such as (x==y) which has int type, but is
8263 /// commonly interpreted as boolean.
8264 static bool ExprLooksBoolean(Expr *E) {
8265   E = E->IgnoreParenImpCasts();
8266 
8267   if (E->getType()->isBooleanType())
8268     return true;
8269   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
8270     return OP->isComparisonOp() || OP->isLogicalOp();
8271   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
8272     return OP->getOpcode() == UO_LNot;
8273   if (E->getType()->isPointerType())
8274     return true;
8275   // FIXME: What about overloaded operator calls returning "unspecified boolean
8276   // type"s (commonly pointer-to-members)?
8277 
8278   return false;
8279 }
8280 
8281 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
8282 /// and binary operator are mixed in a way that suggests the programmer assumed
8283 /// the conditional operator has higher precedence, for example:
8284 /// "int x = a + someBinaryCondition ? 1 : 2".
8285 static void DiagnoseConditionalPrecedence(Sema &Self,
8286                                           SourceLocation OpLoc,
8287                                           Expr *Condition,
8288                                           Expr *LHSExpr,
8289                                           Expr *RHSExpr) {
8290   BinaryOperatorKind CondOpcode;
8291   Expr *CondRHS;
8292 
8293   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
8294     return;
8295   if (!ExprLooksBoolean(CondRHS))
8296     return;
8297 
8298   // The condition is an arithmetic binary expression, with a right-
8299   // hand side that looks boolean, so warn.
8300 
8301   unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode)
8302                         ? diag::warn_precedence_bitwise_conditional
8303                         : diag::warn_precedence_conditional;
8304 
8305   Self.Diag(OpLoc, DiagID)
8306       << Condition->getSourceRange()
8307       << BinaryOperator::getOpcodeStr(CondOpcode);
8308 
8309   SuggestParentheses(
8310       Self, OpLoc,
8311       Self.PDiag(diag::note_precedence_silence)
8312           << BinaryOperator::getOpcodeStr(CondOpcode),
8313       SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
8314 
8315   SuggestParentheses(Self, OpLoc,
8316                      Self.PDiag(diag::note_precedence_conditional_first),
8317                      SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
8318 }
8319 
8320 /// Compute the nullability of a conditional expression.
8321 static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
8322                                               QualType LHSTy, QualType RHSTy,
8323                                               ASTContext &Ctx) {
8324   if (!ResTy->isAnyPointerType())
8325     return ResTy;
8326 
8327   auto GetNullability = [&Ctx](QualType Ty) {
8328     Optional<NullabilityKind> Kind = Ty->getNullability(Ctx);
8329     if (Kind)
8330       return *Kind;
8331     return NullabilityKind::Unspecified;
8332   };
8333 
8334   auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
8335   NullabilityKind MergedKind;
8336 
8337   // Compute nullability of a binary conditional expression.
8338   if (IsBin) {
8339     if (LHSKind == NullabilityKind::NonNull)
8340       MergedKind = NullabilityKind::NonNull;
8341     else
8342       MergedKind = RHSKind;
8343   // Compute nullability of a normal conditional expression.
8344   } else {
8345     if (LHSKind == NullabilityKind::Nullable ||
8346         RHSKind == NullabilityKind::Nullable)
8347       MergedKind = NullabilityKind::Nullable;
8348     else if (LHSKind == NullabilityKind::NonNull)
8349       MergedKind = RHSKind;
8350     else if (RHSKind == NullabilityKind::NonNull)
8351       MergedKind = LHSKind;
8352     else
8353       MergedKind = NullabilityKind::Unspecified;
8354   }
8355 
8356   // Return if ResTy already has the correct nullability.
8357   if (GetNullability(ResTy) == MergedKind)
8358     return ResTy;
8359 
8360   // Strip all nullability from ResTy.
8361   while (ResTy->getNullability(Ctx))
8362     ResTy = ResTy.getSingleStepDesugaredType(Ctx);
8363 
8364   // Create a new AttributedType with the new nullability kind.
8365   auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
8366   return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
8367 }
8368 
8369 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
8370 /// in the case of a the GNU conditional expr extension.
8371 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
8372                                     SourceLocation ColonLoc,
8373                                     Expr *CondExpr, Expr *LHSExpr,
8374                                     Expr *RHSExpr) {
8375   if (!getLangOpts().CPlusPlus) {
8376     // C cannot handle TypoExpr nodes in the condition because it
8377     // doesn't handle dependent types properly, so make sure any TypoExprs have
8378     // been dealt with before checking the operands.
8379     ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
8380     ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
8381     ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
8382 
8383     if (!CondResult.isUsable())
8384       return ExprError();
8385 
8386     if (LHSExpr) {
8387       if (!LHSResult.isUsable())
8388         return ExprError();
8389     }
8390 
8391     if (!RHSResult.isUsable())
8392       return ExprError();
8393 
8394     CondExpr = CondResult.get();
8395     LHSExpr = LHSResult.get();
8396     RHSExpr = RHSResult.get();
8397   }
8398 
8399   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
8400   // was the condition.
8401   OpaqueValueExpr *opaqueValue = nullptr;
8402   Expr *commonExpr = nullptr;
8403   if (!LHSExpr) {
8404     commonExpr = CondExpr;
8405     // Lower out placeholder types first.  This is important so that we don't
8406     // try to capture a placeholder. This happens in few cases in C++; such
8407     // as Objective-C++'s dictionary subscripting syntax.
8408     if (commonExpr->hasPlaceholderType()) {
8409       ExprResult result = CheckPlaceholderExpr(commonExpr);
8410       if (!result.isUsable()) return ExprError();
8411       commonExpr = result.get();
8412     }
8413     // We usually want to apply unary conversions *before* saving, except
8414     // in the special case of a C++ l-value conditional.
8415     if (!(getLangOpts().CPlusPlus
8416           && !commonExpr->isTypeDependent()
8417           && commonExpr->getValueKind() == RHSExpr->getValueKind()
8418           && commonExpr->isGLValue()
8419           && commonExpr->isOrdinaryOrBitFieldObject()
8420           && RHSExpr->isOrdinaryOrBitFieldObject()
8421           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
8422       ExprResult commonRes = UsualUnaryConversions(commonExpr);
8423       if (commonRes.isInvalid())
8424         return ExprError();
8425       commonExpr = commonRes.get();
8426     }
8427 
8428     // If the common expression is a class or array prvalue, materialize it
8429     // so that we can safely refer to it multiple times.
8430     if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() ||
8431                                    commonExpr->getType()->isArrayType())) {
8432       ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
8433       if (MatExpr.isInvalid())
8434         return ExprError();
8435       commonExpr = MatExpr.get();
8436     }
8437 
8438     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
8439                                                 commonExpr->getType(),
8440                                                 commonExpr->getValueKind(),
8441                                                 commonExpr->getObjectKind(),
8442                                                 commonExpr);
8443     LHSExpr = CondExpr = opaqueValue;
8444   }
8445 
8446   QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
8447   ExprValueKind VK = VK_RValue;
8448   ExprObjectKind OK = OK_Ordinary;
8449   ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
8450   QualType result = CheckConditionalOperands(Cond, LHS, RHS,
8451                                              VK, OK, QuestionLoc);
8452   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
8453       RHS.isInvalid())
8454     return ExprError();
8455 
8456   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
8457                                 RHS.get());
8458 
8459   CheckBoolLikeConversion(Cond.get(), QuestionLoc);
8460 
8461   result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
8462                                          Context);
8463 
8464   if (!commonExpr)
8465     return new (Context)
8466         ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
8467                             RHS.get(), result, VK, OK);
8468 
8469   return new (Context) BinaryConditionalOperator(
8470       commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
8471       ColonLoc, result, VK, OK);
8472 }
8473 
8474 // Check if we have a conversion between incompatible cmse function pointer
8475 // types, that is, a conversion between a function pointer with the
8476 // cmse_nonsecure_call attribute and one without.
8477 static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType,
8478                                           QualType ToType) {
8479   if (const auto *ToFn =
8480           dyn_cast<FunctionType>(S.Context.getCanonicalType(ToType))) {
8481     if (const auto *FromFn =
8482             dyn_cast<FunctionType>(S.Context.getCanonicalType(FromType))) {
8483       FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
8484       FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
8485 
8486       return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall();
8487     }
8488   }
8489   return false;
8490 }
8491 
8492 // checkPointerTypesForAssignment - This is a very tricky routine (despite
8493 // being closely modeled after the C99 spec:-). The odd characteristic of this
8494 // routine is it effectively iqnores the qualifiers on the top level pointee.
8495 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
8496 // FIXME: add a couple examples in this comment.
8497 static Sema::AssignConvertType
8498 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
8499   assert(LHSType.isCanonical() && "LHS not canonicalized!");
8500   assert(RHSType.isCanonical() && "RHS not canonicalized!");
8501 
8502   // get the "pointed to" type (ignoring qualifiers at the top level)
8503   const Type *lhptee, *rhptee;
8504   Qualifiers lhq, rhq;
8505   std::tie(lhptee, lhq) =
8506       cast<PointerType>(LHSType)->getPointeeType().split().asPair();
8507   std::tie(rhptee, rhq) =
8508       cast<PointerType>(RHSType)->getPointeeType().split().asPair();
8509 
8510   Sema::AssignConvertType ConvTy = Sema::Compatible;
8511 
8512   // C99 6.5.16.1p1: This following citation is common to constraints
8513   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
8514   // qualifiers of the type *pointed to* by the right;
8515 
8516   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
8517   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
8518       lhq.compatiblyIncludesObjCLifetime(rhq)) {
8519     // Ignore lifetime for further calculation.
8520     lhq.removeObjCLifetime();
8521     rhq.removeObjCLifetime();
8522   }
8523 
8524   if (!lhq.compatiblyIncludes(rhq)) {
8525     // Treat address-space mismatches as fatal.
8526     if (!lhq.isAddressSpaceSupersetOf(rhq))
8527       return Sema::IncompatiblePointerDiscardsQualifiers;
8528 
8529     // It's okay to add or remove GC or lifetime qualifiers when converting to
8530     // and from void*.
8531     else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
8532                         .compatiblyIncludes(
8533                                 rhq.withoutObjCGCAttr().withoutObjCLifetime())
8534              && (lhptee->isVoidType() || rhptee->isVoidType()))
8535       ; // keep old
8536 
8537     // Treat lifetime mismatches as fatal.
8538     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
8539       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
8540 
8541     // For GCC/MS compatibility, other qualifier mismatches are treated
8542     // as still compatible in C.
8543     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
8544   }
8545 
8546   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
8547   // incomplete type and the other is a pointer to a qualified or unqualified
8548   // version of void...
8549   if (lhptee->isVoidType()) {
8550     if (rhptee->isIncompleteOrObjectType())
8551       return ConvTy;
8552 
8553     // As an extension, we allow cast to/from void* to function pointer.
8554     assert(rhptee->isFunctionType());
8555     return Sema::FunctionVoidPointer;
8556   }
8557 
8558   if (rhptee->isVoidType()) {
8559     if (lhptee->isIncompleteOrObjectType())
8560       return ConvTy;
8561 
8562     // As an extension, we allow cast to/from void* to function pointer.
8563     assert(lhptee->isFunctionType());
8564     return Sema::FunctionVoidPointer;
8565   }
8566 
8567   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
8568   // unqualified versions of compatible types, ...
8569   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
8570   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
8571     // Check if the pointee types are compatible ignoring the sign.
8572     // We explicitly check for char so that we catch "char" vs
8573     // "unsigned char" on systems where "char" is unsigned.
8574     if (lhptee->isCharType())
8575       ltrans = S.Context.UnsignedCharTy;
8576     else if (lhptee->hasSignedIntegerRepresentation())
8577       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
8578 
8579     if (rhptee->isCharType())
8580       rtrans = S.Context.UnsignedCharTy;
8581     else if (rhptee->hasSignedIntegerRepresentation())
8582       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
8583 
8584     if (ltrans == rtrans) {
8585       // Types are compatible ignoring the sign. Qualifier incompatibility
8586       // takes priority over sign incompatibility because the sign
8587       // warning can be disabled.
8588       if (ConvTy != Sema::Compatible)
8589         return ConvTy;
8590 
8591       return Sema::IncompatiblePointerSign;
8592     }
8593 
8594     // If we are a multi-level pointer, it's possible that our issue is simply
8595     // one of qualification - e.g. char ** -> const char ** is not allowed. If
8596     // the eventual target type is the same and the pointers have the same
8597     // level of indirection, this must be the issue.
8598     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
8599       do {
8600         std::tie(lhptee, lhq) =
8601           cast<PointerType>(lhptee)->getPointeeType().split().asPair();
8602         std::tie(rhptee, rhq) =
8603           cast<PointerType>(rhptee)->getPointeeType().split().asPair();
8604 
8605         // Inconsistent address spaces at this point is invalid, even if the
8606         // address spaces would be compatible.
8607         // FIXME: This doesn't catch address space mismatches for pointers of
8608         // different nesting levels, like:
8609         //   __local int *** a;
8610         //   int ** b = a;
8611         // It's not clear how to actually determine when such pointers are
8612         // invalidly incompatible.
8613         if (lhq.getAddressSpace() != rhq.getAddressSpace())
8614           return Sema::IncompatibleNestedPointerAddressSpaceMismatch;
8615 
8616       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
8617 
8618       if (lhptee == rhptee)
8619         return Sema::IncompatibleNestedPointerQualifiers;
8620     }
8621 
8622     // General pointer incompatibility takes priority over qualifiers.
8623     if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType())
8624       return Sema::IncompatibleFunctionPointer;
8625     return Sema::IncompatiblePointer;
8626   }
8627   if (!S.getLangOpts().CPlusPlus &&
8628       S.IsFunctionConversion(ltrans, rtrans, ltrans))
8629     return Sema::IncompatibleFunctionPointer;
8630   if (IsInvalidCmseNSCallConversion(S, ltrans, rtrans))
8631     return Sema::IncompatibleFunctionPointer;
8632   return ConvTy;
8633 }
8634 
8635 /// checkBlockPointerTypesForAssignment - This routine determines whether two
8636 /// block pointer types are compatible or whether a block and normal pointer
8637 /// are compatible. It is more restrict than comparing two function pointer
8638 // types.
8639 static Sema::AssignConvertType
8640 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
8641                                     QualType RHSType) {
8642   assert(LHSType.isCanonical() && "LHS not canonicalized!");
8643   assert(RHSType.isCanonical() && "RHS not canonicalized!");
8644 
8645   QualType lhptee, rhptee;
8646 
8647   // get the "pointed to" type (ignoring qualifiers at the top level)
8648   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
8649   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
8650 
8651   // In C++, the types have to match exactly.
8652   if (S.getLangOpts().CPlusPlus)
8653     return Sema::IncompatibleBlockPointer;
8654 
8655   Sema::AssignConvertType ConvTy = Sema::Compatible;
8656 
8657   // For blocks we enforce that qualifiers are identical.
8658   Qualifiers LQuals = lhptee.getLocalQualifiers();
8659   Qualifiers RQuals = rhptee.getLocalQualifiers();
8660   if (S.getLangOpts().OpenCL) {
8661     LQuals.removeAddressSpace();
8662     RQuals.removeAddressSpace();
8663   }
8664   if (LQuals != RQuals)
8665     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
8666 
8667   // FIXME: OpenCL doesn't define the exact compile time semantics for a block
8668   // assignment.
8669   // The current behavior is similar to C++ lambdas. A block might be
8670   // assigned to a variable iff its return type and parameters are compatible
8671   // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
8672   // an assignment. Presumably it should behave in way that a function pointer
8673   // assignment does in C, so for each parameter and return type:
8674   //  * CVR and address space of LHS should be a superset of CVR and address
8675   //  space of RHS.
8676   //  * unqualified types should be compatible.
8677   if (S.getLangOpts().OpenCL) {
8678     if (!S.Context.typesAreBlockPointerCompatible(
8679             S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
8680             S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
8681       return Sema::IncompatibleBlockPointer;
8682   } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
8683     return Sema::IncompatibleBlockPointer;
8684 
8685   return ConvTy;
8686 }
8687 
8688 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
8689 /// for assignment compatibility.
8690 static Sema::AssignConvertType
8691 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
8692                                    QualType RHSType) {
8693   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
8694   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
8695 
8696   if (LHSType->isObjCBuiltinType()) {
8697     // Class is not compatible with ObjC object pointers.
8698     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
8699         !RHSType->isObjCQualifiedClassType())
8700       return Sema::IncompatiblePointer;
8701     return Sema::Compatible;
8702   }
8703   if (RHSType->isObjCBuiltinType()) {
8704     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
8705         !LHSType->isObjCQualifiedClassType())
8706       return Sema::IncompatiblePointer;
8707     return Sema::Compatible;
8708   }
8709   QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
8710   QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
8711 
8712   if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
8713       // make an exception for id<P>
8714       !LHSType->isObjCQualifiedIdType())
8715     return Sema::CompatiblePointerDiscardsQualifiers;
8716 
8717   if (S.Context.typesAreCompatible(LHSType, RHSType))
8718     return Sema::Compatible;
8719   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
8720     return Sema::IncompatibleObjCQualifiedId;
8721   return Sema::IncompatiblePointer;
8722 }
8723 
8724 Sema::AssignConvertType
8725 Sema::CheckAssignmentConstraints(SourceLocation Loc,
8726                                  QualType LHSType, QualType RHSType) {
8727   // Fake up an opaque expression.  We don't actually care about what
8728   // cast operations are required, so if CheckAssignmentConstraints
8729   // adds casts to this they'll be wasted, but fortunately that doesn't
8730   // usually happen on valid code.
8731   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
8732   ExprResult RHSPtr = &RHSExpr;
8733   CastKind K;
8734 
8735   return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
8736 }
8737 
8738 /// This helper function returns true if QT is a vector type that has element
8739 /// type ElementType.
8740 static bool isVector(QualType QT, QualType ElementType) {
8741   if (const VectorType *VT = QT->getAs<VectorType>())
8742     return VT->getElementType().getCanonicalType() == ElementType;
8743   return false;
8744 }
8745 
8746 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
8747 /// has code to accommodate several GCC extensions when type checking
8748 /// pointers. Here are some objectionable examples that GCC considers warnings:
8749 ///
8750 ///  int a, *pint;
8751 ///  short *pshort;
8752 ///  struct foo *pfoo;
8753 ///
8754 ///  pint = pshort; // warning: assignment from incompatible pointer type
8755 ///  a = pint; // warning: assignment makes integer from pointer without a cast
8756 ///  pint = a; // warning: assignment makes pointer from integer without a cast
8757 ///  pint = pfoo; // warning: assignment from incompatible pointer type
8758 ///
8759 /// As a result, the code for dealing with pointers is more complex than the
8760 /// C99 spec dictates.
8761 ///
8762 /// Sets 'Kind' for any result kind except Incompatible.
8763 Sema::AssignConvertType
8764 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
8765                                  CastKind &Kind, bool ConvertRHS) {
8766   QualType RHSType = RHS.get()->getType();
8767   QualType OrigLHSType = LHSType;
8768 
8769   // Get canonical types.  We're not formatting these types, just comparing
8770   // them.
8771   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
8772   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
8773 
8774   // Common case: no conversion required.
8775   if (LHSType == RHSType) {
8776     Kind = CK_NoOp;
8777     return Compatible;
8778   }
8779 
8780   // If we have an atomic type, try a non-atomic assignment, then just add an
8781   // atomic qualification step.
8782   if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
8783     Sema::AssignConvertType result =
8784       CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
8785     if (result != Compatible)
8786       return result;
8787     if (Kind != CK_NoOp && ConvertRHS)
8788       RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
8789     Kind = CK_NonAtomicToAtomic;
8790     return Compatible;
8791   }
8792 
8793   // If the left-hand side is a reference type, then we are in a
8794   // (rare!) case where we've allowed the use of references in C,
8795   // e.g., as a parameter type in a built-in function. In this case,
8796   // just make sure that the type referenced is compatible with the
8797   // right-hand side type. The caller is responsible for adjusting
8798   // LHSType so that the resulting expression does not have reference
8799   // type.
8800   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
8801     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
8802       Kind = CK_LValueBitCast;
8803       return Compatible;
8804     }
8805     return Incompatible;
8806   }
8807 
8808   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
8809   // to the same ExtVector type.
8810   if (LHSType->isExtVectorType()) {
8811     if (RHSType->isExtVectorType())
8812       return Incompatible;
8813     if (RHSType->isArithmeticType()) {
8814       // CK_VectorSplat does T -> vector T, so first cast to the element type.
8815       if (ConvertRHS)
8816         RHS = prepareVectorSplat(LHSType, RHS.get());
8817       Kind = CK_VectorSplat;
8818       return Compatible;
8819     }
8820   }
8821 
8822   // Conversions to or from vector type.
8823   if (LHSType->isVectorType() || RHSType->isVectorType()) {
8824     if (LHSType->isVectorType() && RHSType->isVectorType()) {
8825       // Allow assignments of an AltiVec vector type to an equivalent GCC
8826       // vector type and vice versa
8827       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
8828         Kind = CK_BitCast;
8829         return Compatible;
8830       }
8831 
8832       // If we are allowing lax vector conversions, and LHS and RHS are both
8833       // vectors, the total size only needs to be the same. This is a bitcast;
8834       // no bits are changed but the result type is different.
8835       if (isLaxVectorConversion(RHSType, LHSType)) {
8836         Kind = CK_BitCast;
8837         return IncompatibleVectors;
8838       }
8839     }
8840 
8841     // When the RHS comes from another lax conversion (e.g. binops between
8842     // scalars and vectors) the result is canonicalized as a vector. When the
8843     // LHS is also a vector, the lax is allowed by the condition above. Handle
8844     // the case where LHS is a scalar.
8845     if (LHSType->isScalarType()) {
8846       const VectorType *VecType = RHSType->getAs<VectorType>();
8847       if (VecType && VecType->getNumElements() == 1 &&
8848           isLaxVectorConversion(RHSType, LHSType)) {
8849         ExprResult *VecExpr = &RHS;
8850         *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
8851         Kind = CK_BitCast;
8852         return Compatible;
8853       }
8854     }
8855 
8856     return Incompatible;
8857   }
8858 
8859   // Diagnose attempts to convert between __float128 and long double where
8860   // such conversions currently can't be handled.
8861   if (unsupportedTypeConversion(*this, LHSType, RHSType))
8862     return Incompatible;
8863 
8864   // Disallow assigning a _Complex to a real type in C++ mode since it simply
8865   // discards the imaginary part.
8866   if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
8867       !LHSType->getAs<ComplexType>())
8868     return Incompatible;
8869 
8870   // Arithmetic conversions.
8871   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
8872       !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
8873     if (ConvertRHS)
8874       Kind = PrepareScalarCast(RHS, LHSType);
8875     return Compatible;
8876   }
8877 
8878   // Conversions to normal pointers.
8879   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
8880     // U* -> T*
8881     if (isa<PointerType>(RHSType)) {
8882       LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
8883       LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
8884       if (AddrSpaceL != AddrSpaceR)
8885         Kind = CK_AddressSpaceConversion;
8886       else if (Context.hasCvrSimilarType(RHSType, LHSType))
8887         Kind = CK_NoOp;
8888       else
8889         Kind = CK_BitCast;
8890       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
8891     }
8892 
8893     // int -> T*
8894     if (RHSType->isIntegerType()) {
8895       Kind = CK_IntegralToPointer; // FIXME: null?
8896       return IntToPointer;
8897     }
8898 
8899     // C pointers are not compatible with ObjC object pointers,
8900     // with two exceptions:
8901     if (isa<ObjCObjectPointerType>(RHSType)) {
8902       //  - conversions to void*
8903       if (LHSPointer->getPointeeType()->isVoidType()) {
8904         Kind = CK_BitCast;
8905         return Compatible;
8906       }
8907 
8908       //  - conversions from 'Class' to the redefinition type
8909       if (RHSType->isObjCClassType() &&
8910           Context.hasSameType(LHSType,
8911                               Context.getObjCClassRedefinitionType())) {
8912         Kind = CK_BitCast;
8913         return Compatible;
8914       }
8915 
8916       Kind = CK_BitCast;
8917       return IncompatiblePointer;
8918     }
8919 
8920     // U^ -> void*
8921     if (RHSType->getAs<BlockPointerType>()) {
8922       if (LHSPointer->getPointeeType()->isVoidType()) {
8923         LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
8924         LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
8925                                 ->getPointeeType()
8926                                 .getAddressSpace();
8927         Kind =
8928             AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
8929         return Compatible;
8930       }
8931     }
8932 
8933     return Incompatible;
8934   }
8935 
8936   // Conversions to block pointers.
8937   if (isa<BlockPointerType>(LHSType)) {
8938     // U^ -> T^
8939     if (RHSType->isBlockPointerType()) {
8940       LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
8941                               ->getPointeeType()
8942                               .getAddressSpace();
8943       LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
8944                               ->getPointeeType()
8945                               .getAddressSpace();
8946       Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
8947       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
8948     }
8949 
8950     // int or null -> T^
8951     if (RHSType->isIntegerType()) {
8952       Kind = CK_IntegralToPointer; // FIXME: null
8953       return IntToBlockPointer;
8954     }
8955 
8956     // id -> T^
8957     if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
8958       Kind = CK_AnyPointerToBlockPointerCast;
8959       return Compatible;
8960     }
8961 
8962     // void* -> T^
8963     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
8964       if (RHSPT->getPointeeType()->isVoidType()) {
8965         Kind = CK_AnyPointerToBlockPointerCast;
8966         return Compatible;
8967       }
8968 
8969     return Incompatible;
8970   }
8971 
8972   // Conversions to Objective-C pointers.
8973   if (isa<ObjCObjectPointerType>(LHSType)) {
8974     // A* -> B*
8975     if (RHSType->isObjCObjectPointerType()) {
8976       Kind = CK_BitCast;
8977       Sema::AssignConvertType result =
8978         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
8979       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
8980           result == Compatible &&
8981           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
8982         result = IncompatibleObjCWeakRef;
8983       return result;
8984     }
8985 
8986     // int or null -> A*
8987     if (RHSType->isIntegerType()) {
8988       Kind = CK_IntegralToPointer; // FIXME: null
8989       return IntToPointer;
8990     }
8991 
8992     // In general, C pointers are not compatible with ObjC object pointers,
8993     // with two exceptions:
8994     if (isa<PointerType>(RHSType)) {
8995       Kind = CK_CPointerToObjCPointerCast;
8996 
8997       //  - conversions from 'void*'
8998       if (RHSType->isVoidPointerType()) {
8999         return Compatible;
9000       }
9001 
9002       //  - conversions to 'Class' from its redefinition type
9003       if (LHSType->isObjCClassType() &&
9004           Context.hasSameType(RHSType,
9005                               Context.getObjCClassRedefinitionType())) {
9006         return Compatible;
9007       }
9008 
9009       return IncompatiblePointer;
9010     }
9011 
9012     // Only under strict condition T^ is compatible with an Objective-C pointer.
9013     if (RHSType->isBlockPointerType() &&
9014         LHSType->isBlockCompatibleObjCPointerType(Context)) {
9015       if (ConvertRHS)
9016         maybeExtendBlockObject(RHS);
9017       Kind = CK_BlockPointerToObjCPointerCast;
9018       return Compatible;
9019     }
9020 
9021     return Incompatible;
9022   }
9023 
9024   // Conversions from pointers that are not covered by the above.
9025   if (isa<PointerType>(RHSType)) {
9026     // T* -> _Bool
9027     if (LHSType == Context.BoolTy) {
9028       Kind = CK_PointerToBoolean;
9029       return Compatible;
9030     }
9031 
9032     // T* -> int
9033     if (LHSType->isIntegerType()) {
9034       Kind = CK_PointerToIntegral;
9035       return PointerToInt;
9036     }
9037 
9038     return Incompatible;
9039   }
9040 
9041   // Conversions from Objective-C pointers that are not covered by the above.
9042   if (isa<ObjCObjectPointerType>(RHSType)) {
9043     // T* -> _Bool
9044     if (LHSType == Context.BoolTy) {
9045       Kind = CK_PointerToBoolean;
9046       return Compatible;
9047     }
9048 
9049     // T* -> int
9050     if (LHSType->isIntegerType()) {
9051       Kind = CK_PointerToIntegral;
9052       return PointerToInt;
9053     }
9054 
9055     return Incompatible;
9056   }
9057 
9058   // struct A -> struct B
9059   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
9060     if (Context.typesAreCompatible(LHSType, RHSType)) {
9061       Kind = CK_NoOp;
9062       return Compatible;
9063     }
9064   }
9065 
9066   if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
9067     Kind = CK_IntToOCLSampler;
9068     return Compatible;
9069   }
9070 
9071   return Incompatible;
9072 }
9073 
9074 /// Constructs a transparent union from an expression that is
9075 /// used to initialize the transparent union.
9076 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
9077                                       ExprResult &EResult, QualType UnionType,
9078                                       FieldDecl *Field) {
9079   // Build an initializer list that designates the appropriate member
9080   // of the transparent union.
9081   Expr *E = EResult.get();
9082   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
9083                                                    E, SourceLocation());
9084   Initializer->setType(UnionType);
9085   Initializer->setInitializedFieldInUnion(Field);
9086 
9087   // Build a compound literal constructing a value of the transparent
9088   // union type from this initializer list.
9089   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
9090   EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
9091                                         VK_RValue, Initializer, false);
9092 }
9093 
9094 Sema::AssignConvertType
9095 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
9096                                                ExprResult &RHS) {
9097   QualType RHSType = RHS.get()->getType();
9098 
9099   // If the ArgType is a Union type, we want to handle a potential
9100   // transparent_union GCC extension.
9101   const RecordType *UT = ArgType->getAsUnionType();
9102   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
9103     return Incompatible;
9104 
9105   // The field to initialize within the transparent union.
9106   RecordDecl *UD = UT->getDecl();
9107   FieldDecl *InitField = nullptr;
9108   // It's compatible if the expression matches any of the fields.
9109   for (auto *it : UD->fields()) {
9110     if (it->getType()->isPointerType()) {
9111       // If the transparent union contains a pointer type, we allow:
9112       // 1) void pointer
9113       // 2) null pointer constant
9114       if (RHSType->isPointerType())
9115         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
9116           RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
9117           InitField = it;
9118           break;
9119         }
9120 
9121       if (RHS.get()->isNullPointerConstant(Context,
9122                                            Expr::NPC_ValueDependentIsNull)) {
9123         RHS = ImpCastExprToType(RHS.get(), it->getType(),
9124                                 CK_NullToPointer);
9125         InitField = it;
9126         break;
9127       }
9128     }
9129 
9130     CastKind Kind;
9131     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
9132           == Compatible) {
9133       RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
9134       InitField = it;
9135       break;
9136     }
9137   }
9138 
9139   if (!InitField)
9140     return Incompatible;
9141 
9142   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
9143   return Compatible;
9144 }
9145 
9146 Sema::AssignConvertType
9147 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
9148                                        bool Diagnose,
9149                                        bool DiagnoseCFAudited,
9150                                        bool ConvertRHS) {
9151   // We need to be able to tell the caller whether we diagnosed a problem, if
9152   // they ask us to issue diagnostics.
9153   assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
9154 
9155   // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
9156   // we can't avoid *all* modifications at the moment, so we need some somewhere
9157   // to put the updated value.
9158   ExprResult LocalRHS = CallerRHS;
9159   ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
9160 
9161   if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
9162     if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
9163       if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
9164           !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
9165         Diag(RHS.get()->getExprLoc(),
9166              diag::warn_noderef_to_dereferenceable_pointer)
9167             << RHS.get()->getSourceRange();
9168       }
9169     }
9170   }
9171 
9172   if (getLangOpts().CPlusPlus) {
9173     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
9174       // C++ 5.17p3: If the left operand is not of class type, the
9175       // expression is implicitly converted (C++ 4) to the
9176       // cv-unqualified type of the left operand.
9177       QualType RHSType = RHS.get()->getType();
9178       if (Diagnose) {
9179         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9180                                         AA_Assigning);
9181       } else {
9182         ImplicitConversionSequence ICS =
9183             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9184                                   /*SuppressUserConversions=*/false,
9185                                   AllowedExplicit::None,
9186                                   /*InOverloadResolution=*/false,
9187                                   /*CStyle=*/false,
9188                                   /*AllowObjCWritebackConversion=*/false);
9189         if (ICS.isFailure())
9190           return Incompatible;
9191         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9192                                         ICS, AA_Assigning);
9193       }
9194       if (RHS.isInvalid())
9195         return Incompatible;
9196       Sema::AssignConvertType result = Compatible;
9197       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9198           !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
9199         result = IncompatibleObjCWeakRef;
9200       return result;
9201     }
9202 
9203     // FIXME: Currently, we fall through and treat C++ classes like C
9204     // structures.
9205     // FIXME: We also fall through for atomics; not sure what should
9206     // happen there, though.
9207   } else if (RHS.get()->getType() == Context.OverloadTy) {
9208     // As a set of extensions to C, we support overloading on functions. These
9209     // functions need to be resolved here.
9210     DeclAccessPair DAP;
9211     if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
9212             RHS.get(), LHSType, /*Complain=*/false, DAP))
9213       RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
9214     else
9215       return Incompatible;
9216   }
9217 
9218   // C99 6.5.16.1p1: the left operand is a pointer and the right is
9219   // a null pointer constant.
9220   if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
9221        LHSType->isBlockPointerType()) &&
9222       RHS.get()->isNullPointerConstant(Context,
9223                                        Expr::NPC_ValueDependentIsNull)) {
9224     if (Diagnose || ConvertRHS) {
9225       CastKind Kind;
9226       CXXCastPath Path;
9227       CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
9228                              /*IgnoreBaseAccess=*/false, Diagnose);
9229       if (ConvertRHS)
9230         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
9231     }
9232     return Compatible;
9233   }
9234 
9235   // OpenCL queue_t type assignment.
9236   if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
9237                                  Context, Expr::NPC_ValueDependentIsNull)) {
9238     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9239     return Compatible;
9240   }
9241 
9242   // This check seems unnatural, however it is necessary to ensure the proper
9243   // conversion of functions/arrays. If the conversion were done for all
9244   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
9245   // expressions that suppress this implicit conversion (&, sizeof).
9246   //
9247   // Suppress this for references: C++ 8.5.3p5.
9248   if (!LHSType->isReferenceType()) {
9249     // FIXME: We potentially allocate here even if ConvertRHS is false.
9250     RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
9251     if (RHS.isInvalid())
9252       return Incompatible;
9253   }
9254   CastKind Kind;
9255   Sema::AssignConvertType result =
9256     CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
9257 
9258   // C99 6.5.16.1p2: The value of the right operand is converted to the
9259   // type of the assignment expression.
9260   // CheckAssignmentConstraints allows the left-hand side to be a reference,
9261   // so that we can use references in built-in functions even in C.
9262   // The getNonReferenceType() call makes sure that the resulting expression
9263   // does not have reference type.
9264   if (result != Incompatible && RHS.get()->getType() != LHSType) {
9265     QualType Ty = LHSType.getNonLValueExprType(Context);
9266     Expr *E = RHS.get();
9267 
9268     // Check for various Objective-C errors. If we are not reporting
9269     // diagnostics and just checking for errors, e.g., during overload
9270     // resolution, return Incompatible to indicate the failure.
9271     if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9272         CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
9273                             Diagnose, DiagnoseCFAudited) != ACR_okay) {
9274       if (!Diagnose)
9275         return Incompatible;
9276     }
9277     if (getLangOpts().ObjC &&
9278         (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType,
9279                                            E->getType(), E, Diagnose) ||
9280          ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) {
9281       if (!Diagnose)
9282         return Incompatible;
9283       // Replace the expression with a corrected version and continue so we
9284       // can find further errors.
9285       RHS = E;
9286       return Compatible;
9287     }
9288 
9289     if (ConvertRHS)
9290       RHS = ImpCastExprToType(E, Ty, Kind);
9291   }
9292 
9293   return result;
9294 }
9295 
9296 namespace {
9297 /// The original operand to an operator, prior to the application of the usual
9298 /// arithmetic conversions and converting the arguments of a builtin operator
9299 /// candidate.
9300 struct OriginalOperand {
9301   explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
9302     if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op))
9303       Op = MTE->getSubExpr();
9304     if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op))
9305       Op = BTE->getSubExpr();
9306     if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) {
9307       Orig = ICE->getSubExprAsWritten();
9308       Conversion = ICE->getConversionFunction();
9309     }
9310   }
9311 
9312   QualType getType() const { return Orig->getType(); }
9313 
9314   Expr *Orig;
9315   NamedDecl *Conversion;
9316 };
9317 }
9318 
9319 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
9320                                ExprResult &RHS) {
9321   OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
9322 
9323   Diag(Loc, diag::err_typecheck_invalid_operands)
9324     << OrigLHS.getType() << OrigRHS.getType()
9325     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9326 
9327   // If a user-defined conversion was applied to either of the operands prior
9328   // to applying the built-in operator rules, tell the user about it.
9329   if (OrigLHS.Conversion) {
9330     Diag(OrigLHS.Conversion->getLocation(),
9331          diag::note_typecheck_invalid_operands_converted)
9332       << 0 << LHS.get()->getType();
9333   }
9334   if (OrigRHS.Conversion) {
9335     Diag(OrigRHS.Conversion->getLocation(),
9336          diag::note_typecheck_invalid_operands_converted)
9337       << 1 << RHS.get()->getType();
9338   }
9339 
9340   return QualType();
9341 }
9342 
9343 // Diagnose cases where a scalar was implicitly converted to a vector and
9344 // diagnose the underlying types. Otherwise, diagnose the error
9345 // as invalid vector logical operands for non-C++ cases.
9346 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
9347                                             ExprResult &RHS) {
9348   QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
9349   QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
9350 
9351   bool LHSNatVec = LHSType->isVectorType();
9352   bool RHSNatVec = RHSType->isVectorType();
9353 
9354   if (!(LHSNatVec && RHSNatVec)) {
9355     Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
9356     Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
9357     Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
9358         << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
9359         << Vector->getSourceRange();
9360     return QualType();
9361   }
9362 
9363   Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
9364       << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
9365       << RHS.get()->getSourceRange();
9366 
9367   return QualType();
9368 }
9369 
9370 /// Try to convert a value of non-vector type to a vector type by converting
9371 /// the type to the element type of the vector and then performing a splat.
9372 /// If the language is OpenCL, we only use conversions that promote scalar
9373 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
9374 /// for float->int.
9375 ///
9376 /// OpenCL V2.0 6.2.6.p2:
9377 /// An error shall occur if any scalar operand type has greater rank
9378 /// than the type of the vector element.
9379 ///
9380 /// \param scalar - if non-null, actually perform the conversions
9381 /// \return true if the operation fails (but without diagnosing the failure)
9382 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
9383                                      QualType scalarTy,
9384                                      QualType vectorEltTy,
9385                                      QualType vectorTy,
9386                                      unsigned &DiagID) {
9387   // The conversion to apply to the scalar before splatting it,
9388   // if necessary.
9389   CastKind scalarCast = CK_NoOp;
9390 
9391   if (vectorEltTy->isIntegralType(S.Context)) {
9392     if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
9393         (scalarTy->isIntegerType() &&
9394          S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
9395       DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
9396       return true;
9397     }
9398     if (!scalarTy->isIntegralType(S.Context))
9399       return true;
9400     scalarCast = CK_IntegralCast;
9401   } else if (vectorEltTy->isRealFloatingType()) {
9402     if (scalarTy->isRealFloatingType()) {
9403       if (S.getLangOpts().OpenCL &&
9404           S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
9405         DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
9406         return true;
9407       }
9408       scalarCast = CK_FloatingCast;
9409     }
9410     else if (scalarTy->isIntegralType(S.Context))
9411       scalarCast = CK_IntegralToFloating;
9412     else
9413       return true;
9414   } else {
9415     return true;
9416   }
9417 
9418   // Adjust scalar if desired.
9419   if (scalar) {
9420     if (scalarCast != CK_NoOp)
9421       *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
9422     *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
9423   }
9424   return false;
9425 }
9426 
9427 /// Convert vector E to a vector with the same number of elements but different
9428 /// element type.
9429 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
9430   const auto *VecTy = E->getType()->getAs<VectorType>();
9431   assert(VecTy && "Expression E must be a vector");
9432   QualType NewVecTy = S.Context.getVectorType(ElementType,
9433                                               VecTy->getNumElements(),
9434                                               VecTy->getVectorKind());
9435 
9436   // Look through the implicit cast. Return the subexpression if its type is
9437   // NewVecTy.
9438   if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
9439     if (ICE->getSubExpr()->getType() == NewVecTy)
9440       return ICE->getSubExpr();
9441 
9442   auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
9443   return S.ImpCastExprToType(E, NewVecTy, Cast);
9444 }
9445 
9446 /// Test if a (constant) integer Int can be casted to another integer type
9447 /// IntTy without losing precision.
9448 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int,
9449                                       QualType OtherIntTy) {
9450   QualType IntTy = Int->get()->getType().getUnqualifiedType();
9451 
9452   // Reject cases where the value of the Int is unknown as that would
9453   // possibly cause truncation, but accept cases where the scalar can be
9454   // demoted without loss of precision.
9455   Expr::EvalResult EVResult;
9456   bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
9457   int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
9458   bool IntSigned = IntTy->hasSignedIntegerRepresentation();
9459   bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
9460 
9461   if (CstInt) {
9462     // If the scalar is constant and is of a higher order and has more active
9463     // bits that the vector element type, reject it.
9464     llvm::APSInt Result = EVResult.Val.getInt();
9465     unsigned NumBits = IntSigned
9466                            ? (Result.isNegative() ? Result.getMinSignedBits()
9467                                                   : Result.getActiveBits())
9468                            : Result.getActiveBits();
9469     if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
9470       return true;
9471 
9472     // If the signedness of the scalar type and the vector element type
9473     // differs and the number of bits is greater than that of the vector
9474     // element reject it.
9475     return (IntSigned != OtherIntSigned &&
9476             NumBits > S.Context.getIntWidth(OtherIntTy));
9477   }
9478 
9479   // Reject cases where the value of the scalar is not constant and it's
9480   // order is greater than that of the vector element type.
9481   return (Order < 0);
9482 }
9483 
9484 /// Test if a (constant) integer Int can be casted to floating point type
9485 /// FloatTy without losing precision.
9486 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int,
9487                                      QualType FloatTy) {
9488   QualType IntTy = Int->get()->getType().getUnqualifiedType();
9489 
9490   // Determine if the integer constant can be expressed as a floating point
9491   // number of the appropriate type.
9492   Expr::EvalResult EVResult;
9493   bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
9494 
9495   uint64_t Bits = 0;
9496   if (CstInt) {
9497     // Reject constants that would be truncated if they were converted to
9498     // the floating point type. Test by simple to/from conversion.
9499     // FIXME: Ideally the conversion to an APFloat and from an APFloat
9500     //        could be avoided if there was a convertFromAPInt method
9501     //        which could signal back if implicit truncation occurred.
9502     llvm::APSInt Result = EVResult.Val.getInt();
9503     llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
9504     Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
9505                            llvm::APFloat::rmTowardZero);
9506     llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
9507                              !IntTy->hasSignedIntegerRepresentation());
9508     bool Ignored = false;
9509     Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
9510                            &Ignored);
9511     if (Result != ConvertBack)
9512       return true;
9513   } else {
9514     // Reject types that cannot be fully encoded into the mantissa of
9515     // the float.
9516     Bits = S.Context.getTypeSize(IntTy);
9517     unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
9518         S.Context.getFloatTypeSemantics(FloatTy));
9519     if (Bits > FloatPrec)
9520       return true;
9521   }
9522 
9523   return false;
9524 }
9525 
9526 /// Attempt to convert and splat Scalar into a vector whose types matches
9527 /// Vector following GCC conversion rules. The rule is that implicit
9528 /// conversion can occur when Scalar can be casted to match Vector's element
9529 /// type without causing truncation of Scalar.
9530 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar,
9531                                         ExprResult *Vector) {
9532   QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
9533   QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
9534   const VectorType *VT = VectorTy->getAs<VectorType>();
9535 
9536   assert(!isa<ExtVectorType>(VT) &&
9537          "ExtVectorTypes should not be handled here!");
9538 
9539   QualType VectorEltTy = VT->getElementType();
9540 
9541   // Reject cases where the vector element type or the scalar element type are
9542   // not integral or floating point types.
9543   if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
9544     return true;
9545 
9546   // The conversion to apply to the scalar before splatting it,
9547   // if necessary.
9548   CastKind ScalarCast = CK_NoOp;
9549 
9550   // Accept cases where the vector elements are integers and the scalar is
9551   // an integer.
9552   // FIXME: Notionally if the scalar was a floating point value with a precise
9553   //        integral representation, we could cast it to an appropriate integer
9554   //        type and then perform the rest of the checks here. GCC will perform
9555   //        this conversion in some cases as determined by the input language.
9556   //        We should accept it on a language independent basis.
9557   if (VectorEltTy->isIntegralType(S.Context) &&
9558       ScalarTy->isIntegralType(S.Context) &&
9559       S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
9560 
9561     if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
9562       return true;
9563 
9564     ScalarCast = CK_IntegralCast;
9565   } else if (VectorEltTy->isIntegralType(S.Context) &&
9566              ScalarTy->isRealFloatingType()) {
9567     if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy))
9568       ScalarCast = CK_FloatingToIntegral;
9569     else
9570       return true;
9571   } else if (VectorEltTy->isRealFloatingType()) {
9572     if (ScalarTy->isRealFloatingType()) {
9573 
9574       // Reject cases where the scalar type is not a constant and has a higher
9575       // Order than the vector element type.
9576       llvm::APFloat Result(0.0);
9577 
9578       // Determine whether this is a constant scalar. In the event that the
9579       // value is dependent (and thus cannot be evaluated by the constant
9580       // evaluator), skip the evaluation. This will then diagnose once the
9581       // expression is instantiated.
9582       bool CstScalar = Scalar->get()->isValueDependent() ||
9583                        Scalar->get()->EvaluateAsFloat(Result, S.Context);
9584       int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
9585       if (!CstScalar && Order < 0)
9586         return true;
9587 
9588       // If the scalar cannot be safely casted to the vector element type,
9589       // reject it.
9590       if (CstScalar) {
9591         bool Truncated = false;
9592         Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
9593                        llvm::APFloat::rmNearestTiesToEven, &Truncated);
9594         if (Truncated)
9595           return true;
9596       }
9597 
9598       ScalarCast = CK_FloatingCast;
9599     } else if (ScalarTy->isIntegralType(S.Context)) {
9600       if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
9601         return true;
9602 
9603       ScalarCast = CK_IntegralToFloating;
9604     } else
9605       return true;
9606   }
9607 
9608   // Adjust scalar if desired.
9609   if (Scalar) {
9610     if (ScalarCast != CK_NoOp)
9611       *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
9612     *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
9613   }
9614   return false;
9615 }
9616 
9617 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
9618                                    SourceLocation Loc, bool IsCompAssign,
9619                                    bool AllowBothBool,
9620                                    bool AllowBoolConversions) {
9621   if (!IsCompAssign) {
9622     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
9623     if (LHS.isInvalid())
9624       return QualType();
9625   }
9626   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
9627   if (RHS.isInvalid())
9628     return QualType();
9629 
9630   // For conversion purposes, we ignore any qualifiers.
9631   // For example, "const float" and "float" are equivalent.
9632   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
9633   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
9634 
9635   const VectorType *LHSVecType = LHSType->getAs<VectorType>();
9636   const VectorType *RHSVecType = RHSType->getAs<VectorType>();
9637   assert(LHSVecType || RHSVecType);
9638 
9639   // AltiVec-style "vector bool op vector bool" combinations are allowed
9640   // for some operators but not others.
9641   if (!AllowBothBool &&
9642       LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
9643       RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
9644     return InvalidOperands(Loc, LHS, RHS);
9645 
9646   // If the vector types are identical, return.
9647   if (Context.hasSameType(LHSType, RHSType))
9648     return LHSType;
9649 
9650   // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
9651   if (LHSVecType && RHSVecType &&
9652       Context.areCompatibleVectorTypes(LHSType, RHSType)) {
9653     if (isa<ExtVectorType>(LHSVecType)) {
9654       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9655       return LHSType;
9656     }
9657 
9658     if (!IsCompAssign)
9659       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
9660     return RHSType;
9661   }
9662 
9663   // AllowBoolConversions says that bool and non-bool AltiVec vectors
9664   // can be mixed, with the result being the non-bool type.  The non-bool
9665   // operand must have integer element type.
9666   if (AllowBoolConversions && LHSVecType && RHSVecType &&
9667       LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
9668       (Context.getTypeSize(LHSVecType->getElementType()) ==
9669        Context.getTypeSize(RHSVecType->getElementType()))) {
9670     if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
9671         LHSVecType->getElementType()->isIntegerType() &&
9672         RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
9673       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9674       return LHSType;
9675     }
9676     if (!IsCompAssign &&
9677         LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
9678         RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
9679         RHSVecType->getElementType()->isIntegerType()) {
9680       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
9681       return RHSType;
9682     }
9683   }
9684 
9685   // If there's a vector type and a scalar, try to convert the scalar to
9686   // the vector element type and splat.
9687   unsigned DiagID = diag::err_typecheck_vector_not_convertable;
9688   if (!RHSVecType) {
9689     if (isa<ExtVectorType>(LHSVecType)) {
9690       if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
9691                                     LHSVecType->getElementType(), LHSType,
9692                                     DiagID))
9693         return LHSType;
9694     } else {
9695       if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
9696         return LHSType;
9697     }
9698   }
9699   if (!LHSVecType) {
9700     if (isa<ExtVectorType>(RHSVecType)) {
9701       if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
9702                                     LHSType, RHSVecType->getElementType(),
9703                                     RHSType, DiagID))
9704         return RHSType;
9705     } else {
9706       if (LHS.get()->getValueKind() == VK_LValue ||
9707           !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
9708         return RHSType;
9709     }
9710   }
9711 
9712   // FIXME: The code below also handles conversion between vectors and
9713   // non-scalars, we should break this down into fine grained specific checks
9714   // and emit proper diagnostics.
9715   QualType VecType = LHSVecType ? LHSType : RHSType;
9716   const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
9717   QualType OtherType = LHSVecType ? RHSType : LHSType;
9718   ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
9719   if (isLaxVectorConversion(OtherType, VecType)) {
9720     // If we're allowing lax vector conversions, only the total (data) size
9721     // needs to be the same. For non compound assignment, if one of the types is
9722     // scalar, the result is always the vector type.
9723     if (!IsCompAssign) {
9724       *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
9725       return VecType;
9726     // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
9727     // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
9728     // type. Note that this is already done by non-compound assignments in
9729     // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
9730     // <1 x T> -> T. The result is also a vector type.
9731     } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
9732                (OtherType->isScalarType() && VT->getNumElements() == 1)) {
9733       ExprResult *RHSExpr = &RHS;
9734       *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
9735       return VecType;
9736     }
9737   }
9738 
9739   // Okay, the expression is invalid.
9740 
9741   // If there's a non-vector, non-real operand, diagnose that.
9742   if ((!RHSVecType && !RHSType->isRealType()) ||
9743       (!LHSVecType && !LHSType->isRealType())) {
9744     Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
9745       << LHSType << RHSType
9746       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9747     return QualType();
9748   }
9749 
9750   // OpenCL V1.1 6.2.6.p1:
9751   // If the operands are of more than one vector type, then an error shall
9752   // occur. Implicit conversions between vector types are not permitted, per
9753   // section 6.2.1.
9754   if (getLangOpts().OpenCL &&
9755       RHSVecType && isa<ExtVectorType>(RHSVecType) &&
9756       LHSVecType && isa<ExtVectorType>(LHSVecType)) {
9757     Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
9758                                                            << RHSType;
9759     return QualType();
9760   }
9761 
9762 
9763   // If there is a vector type that is not a ExtVector and a scalar, we reach
9764   // this point if scalar could not be converted to the vector's element type
9765   // without truncation.
9766   if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
9767       (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
9768     QualType Scalar = LHSVecType ? RHSType : LHSType;
9769     QualType Vector = LHSVecType ? LHSType : RHSType;
9770     unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
9771     Diag(Loc,
9772          diag::err_typecheck_vector_not_convertable_implict_truncation)
9773         << ScalarOrVector << Scalar << Vector;
9774 
9775     return QualType();
9776   }
9777 
9778   // Otherwise, use the generic diagnostic.
9779   Diag(Loc, DiagID)
9780     << LHSType << RHSType
9781     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9782   return QualType();
9783 }
9784 
9785 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
9786 // expression.  These are mainly cases where the null pointer is used as an
9787 // integer instead of a pointer.
9788 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
9789                                 SourceLocation Loc, bool IsCompare) {
9790   // The canonical way to check for a GNU null is with isNullPointerConstant,
9791   // but we use a bit of a hack here for speed; this is a relatively
9792   // hot path, and isNullPointerConstant is slow.
9793   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
9794   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
9795 
9796   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
9797 
9798   // Avoid analyzing cases where the result will either be invalid (and
9799   // diagnosed as such) or entirely valid and not something to warn about.
9800   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
9801       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
9802     return;
9803 
9804   // Comparison operations would not make sense with a null pointer no matter
9805   // what the other expression is.
9806   if (!IsCompare) {
9807     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
9808         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
9809         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
9810     return;
9811   }
9812 
9813   // The rest of the operations only make sense with a null pointer
9814   // if the other expression is a pointer.
9815   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
9816       NonNullType->canDecayToPointerType())
9817     return;
9818 
9819   S.Diag(Loc, diag::warn_null_in_comparison_operation)
9820       << LHSNull /* LHS is NULL */ << NonNullType
9821       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9822 }
9823 
9824 static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS,
9825                                           SourceLocation Loc) {
9826   const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS);
9827   const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS);
9828   if (!LUE || !RUE)
9829     return;
9830   if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
9831       RUE->getKind() != UETT_SizeOf)
9832     return;
9833 
9834   const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens();
9835   QualType LHSTy = LHSArg->getType();
9836   QualType RHSTy;
9837 
9838   if (RUE->isArgumentType())
9839     RHSTy = RUE->getArgumentType();
9840   else
9841     RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
9842 
9843   if (LHSTy->isPointerType() && !RHSTy->isPointerType()) {
9844     if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy))
9845       return;
9846 
9847     S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
9848     if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
9849       if (const ValueDecl *LHSArgDecl = DRE->getDecl())
9850         S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here)
9851             << LHSArgDecl;
9852     }
9853   } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) {
9854     QualType ArrayElemTy = ArrayTy->getElementType();
9855     if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) ||
9856         ArrayElemTy->isDependentType() || RHSTy->isDependentType() ||
9857         ArrayElemTy->isCharType() ||
9858         S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy))
9859       return;
9860     S.Diag(Loc, diag::warn_division_sizeof_array)
9861         << LHSArg->getSourceRange() << ArrayElemTy << RHSTy;
9862     if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
9863       if (const ValueDecl *LHSArgDecl = DRE->getDecl())
9864         S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here)
9865             << LHSArgDecl;
9866     }
9867 
9868     S.Diag(Loc, diag::note_precedence_silence) << RHS;
9869   }
9870 }
9871 
9872 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
9873                                                ExprResult &RHS,
9874                                                SourceLocation Loc, bool IsDiv) {
9875   // Check for division/remainder by zero.
9876   Expr::EvalResult RHSValue;
9877   if (!RHS.get()->isValueDependent() &&
9878       RHS.get()->EvaluateAsInt(RHSValue, S.Context) &&
9879       RHSValue.Val.getInt() == 0)
9880     S.DiagRuntimeBehavior(Loc, RHS.get(),
9881                           S.PDiag(diag::warn_remainder_division_by_zero)
9882                             << IsDiv << RHS.get()->getSourceRange());
9883 }
9884 
9885 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
9886                                            SourceLocation Loc,
9887                                            bool IsCompAssign, bool IsDiv) {
9888   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
9889 
9890   if (LHS.get()->getType()->isVectorType() ||
9891       RHS.get()->getType()->isVectorType())
9892     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
9893                                /*AllowBothBool*/getLangOpts().AltiVec,
9894                                /*AllowBoolConversions*/false);
9895 
9896   QualType compType = UsualArithmeticConversions(
9897       LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
9898   if (LHS.isInvalid() || RHS.isInvalid())
9899     return QualType();
9900 
9901 
9902   if (compType.isNull() || !compType->isArithmeticType())
9903     return InvalidOperands(Loc, LHS, RHS);
9904   if (IsDiv) {
9905     DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
9906     DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc);
9907   }
9908   return compType;
9909 }
9910 
9911 QualType Sema::CheckRemainderOperands(
9912   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
9913   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
9914 
9915   if (LHS.get()->getType()->isVectorType() ||
9916       RHS.get()->getType()->isVectorType()) {
9917     if (LHS.get()->getType()->hasIntegerRepresentation() &&
9918         RHS.get()->getType()->hasIntegerRepresentation())
9919       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
9920                                  /*AllowBothBool*/getLangOpts().AltiVec,
9921                                  /*AllowBoolConversions*/false);
9922     return InvalidOperands(Loc, LHS, RHS);
9923   }
9924 
9925   QualType compType = UsualArithmeticConversions(
9926       LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
9927   if (LHS.isInvalid() || RHS.isInvalid())
9928     return QualType();
9929 
9930   if (compType.isNull() || !compType->isIntegerType())
9931     return InvalidOperands(Loc, LHS, RHS);
9932   DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
9933   return compType;
9934 }
9935 
9936 /// Diagnose invalid arithmetic on two void pointers.
9937 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
9938                                                 Expr *LHSExpr, Expr *RHSExpr) {
9939   S.Diag(Loc, S.getLangOpts().CPlusPlus
9940                 ? diag::err_typecheck_pointer_arith_void_type
9941                 : diag::ext_gnu_void_ptr)
9942     << 1 /* two pointers */ << LHSExpr->getSourceRange()
9943                             << RHSExpr->getSourceRange();
9944 }
9945 
9946 /// Diagnose invalid arithmetic on a void pointer.
9947 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
9948                                             Expr *Pointer) {
9949   S.Diag(Loc, S.getLangOpts().CPlusPlus
9950                 ? diag::err_typecheck_pointer_arith_void_type
9951                 : diag::ext_gnu_void_ptr)
9952     << 0 /* one pointer */ << Pointer->getSourceRange();
9953 }
9954 
9955 /// Diagnose invalid arithmetic on a null pointer.
9956 ///
9957 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
9958 /// idiom, which we recognize as a GNU extension.
9959 ///
9960 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc,
9961                                             Expr *Pointer, bool IsGNUIdiom) {
9962   if (IsGNUIdiom)
9963     S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
9964       << Pointer->getSourceRange();
9965   else
9966     S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
9967       << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
9968 }
9969 
9970 /// Diagnose invalid arithmetic on two function pointers.
9971 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
9972                                                     Expr *LHS, Expr *RHS) {
9973   assert(LHS->getType()->isAnyPointerType());
9974   assert(RHS->getType()->isAnyPointerType());
9975   S.Diag(Loc, S.getLangOpts().CPlusPlus
9976                 ? diag::err_typecheck_pointer_arith_function_type
9977                 : diag::ext_gnu_ptr_func_arith)
9978     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
9979     // We only show the second type if it differs from the first.
9980     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
9981                                                    RHS->getType())
9982     << RHS->getType()->getPointeeType()
9983     << LHS->getSourceRange() << RHS->getSourceRange();
9984 }
9985 
9986 /// Diagnose invalid arithmetic on a function pointer.
9987 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
9988                                                 Expr *Pointer) {
9989   assert(Pointer->getType()->isAnyPointerType());
9990   S.Diag(Loc, S.getLangOpts().CPlusPlus
9991                 ? diag::err_typecheck_pointer_arith_function_type
9992                 : diag::ext_gnu_ptr_func_arith)
9993     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
9994     << 0 /* one pointer, so only one type */
9995     << Pointer->getSourceRange();
9996 }
9997 
9998 /// Emit error if Operand is incomplete pointer type
9999 ///
10000 /// \returns True if pointer has incomplete type
10001 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
10002                                                  Expr *Operand) {
10003   QualType ResType = Operand->getType();
10004   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10005     ResType = ResAtomicType->getValueType();
10006 
10007   assert(ResType->isAnyPointerType() && !ResType->isDependentType());
10008   QualType PointeeTy = ResType->getPointeeType();
10009   return S.RequireCompleteSizedType(
10010       Loc, PointeeTy,
10011       diag::err_typecheck_arithmetic_incomplete_or_sizeless_type,
10012       Operand->getSourceRange());
10013 }
10014 
10015 /// Check the validity of an arithmetic pointer operand.
10016 ///
10017 /// If the operand has pointer type, this code will check for pointer types
10018 /// which are invalid in arithmetic operations. These will be diagnosed
10019 /// appropriately, including whether or not the use is supported as an
10020 /// extension.
10021 ///
10022 /// \returns True when the operand is valid to use (even if as an extension).
10023 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
10024                                             Expr *Operand) {
10025   QualType ResType = Operand->getType();
10026   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10027     ResType = ResAtomicType->getValueType();
10028 
10029   if (!ResType->isAnyPointerType()) return true;
10030 
10031   QualType PointeeTy = ResType->getPointeeType();
10032   if (PointeeTy->isVoidType()) {
10033     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
10034     return !S.getLangOpts().CPlusPlus;
10035   }
10036   if (PointeeTy->isFunctionType()) {
10037     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
10038     return !S.getLangOpts().CPlusPlus;
10039   }
10040 
10041   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
10042 
10043   return true;
10044 }
10045 
10046 /// Check the validity of a binary arithmetic operation w.r.t. pointer
10047 /// operands.
10048 ///
10049 /// This routine will diagnose any invalid arithmetic on pointer operands much
10050 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
10051 /// for emitting a single diagnostic even for operations where both LHS and RHS
10052 /// are (potentially problematic) pointers.
10053 ///
10054 /// \returns True when the operand is valid to use (even if as an extension).
10055 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
10056                                                 Expr *LHSExpr, Expr *RHSExpr) {
10057   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
10058   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
10059   if (!isLHSPointer && !isRHSPointer) return true;
10060 
10061   QualType LHSPointeeTy, RHSPointeeTy;
10062   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
10063   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
10064 
10065   // if both are pointers check if operation is valid wrt address spaces
10066   if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) {
10067     const PointerType *lhsPtr = LHSExpr->getType()->castAs<PointerType>();
10068     const PointerType *rhsPtr = RHSExpr->getType()->castAs<PointerType>();
10069     if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) {
10070       S.Diag(Loc,
10071              diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
10072           << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
10073           << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
10074       return false;
10075     }
10076   }
10077 
10078   // Check for arithmetic on pointers to incomplete types.
10079   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
10080   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
10081   if (isLHSVoidPtr || isRHSVoidPtr) {
10082     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
10083     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
10084     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
10085 
10086     return !S.getLangOpts().CPlusPlus;
10087   }
10088 
10089   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
10090   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
10091   if (isLHSFuncPtr || isRHSFuncPtr) {
10092     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
10093     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
10094                                                                 RHSExpr);
10095     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
10096 
10097     return !S.getLangOpts().CPlusPlus;
10098   }
10099 
10100   if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
10101     return false;
10102   if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
10103     return false;
10104 
10105   return true;
10106 }
10107 
10108 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
10109 /// literal.
10110 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
10111                                   Expr *LHSExpr, Expr *RHSExpr) {
10112   StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
10113   Expr* IndexExpr = RHSExpr;
10114   if (!StrExpr) {
10115     StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
10116     IndexExpr = LHSExpr;
10117   }
10118 
10119   bool IsStringPlusInt = StrExpr &&
10120       IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
10121   if (!IsStringPlusInt || IndexExpr->isValueDependent())
10122     return;
10123 
10124   SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
10125   Self.Diag(OpLoc, diag::warn_string_plus_int)
10126       << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
10127 
10128   // Only print a fixit for "str" + int, not for int + "str".
10129   if (IndexExpr == RHSExpr) {
10130     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
10131     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
10132         << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
10133         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
10134         << FixItHint::CreateInsertion(EndLoc, "]");
10135   } else
10136     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
10137 }
10138 
10139 /// Emit a warning when adding a char literal to a string.
10140 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
10141                                    Expr *LHSExpr, Expr *RHSExpr) {
10142   const Expr *StringRefExpr = LHSExpr;
10143   const CharacterLiteral *CharExpr =
10144       dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
10145 
10146   if (!CharExpr) {
10147     CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
10148     StringRefExpr = RHSExpr;
10149   }
10150 
10151   if (!CharExpr || !StringRefExpr)
10152     return;
10153 
10154   const QualType StringType = StringRefExpr->getType();
10155 
10156   // Return if not a PointerType.
10157   if (!StringType->isAnyPointerType())
10158     return;
10159 
10160   // Return if not a CharacterType.
10161   if (!StringType->getPointeeType()->isAnyCharacterType())
10162     return;
10163 
10164   ASTContext &Ctx = Self.getASTContext();
10165   SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
10166 
10167   const QualType CharType = CharExpr->getType();
10168   if (!CharType->isAnyCharacterType() &&
10169       CharType->isIntegerType() &&
10170       llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
10171     Self.Diag(OpLoc, diag::warn_string_plus_char)
10172         << DiagRange << Ctx.CharTy;
10173   } else {
10174     Self.Diag(OpLoc, diag::warn_string_plus_char)
10175         << DiagRange << CharExpr->getType();
10176   }
10177 
10178   // Only print a fixit for str + char, not for char + str.
10179   if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
10180     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
10181     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
10182         << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
10183         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
10184         << FixItHint::CreateInsertion(EndLoc, "]");
10185   } else {
10186     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
10187   }
10188 }
10189 
10190 /// Emit error when two pointers are incompatible.
10191 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
10192                                            Expr *LHSExpr, Expr *RHSExpr) {
10193   assert(LHSExpr->getType()->isAnyPointerType());
10194   assert(RHSExpr->getType()->isAnyPointerType());
10195   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
10196     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
10197     << RHSExpr->getSourceRange();
10198 }
10199 
10200 // C99 6.5.6
10201 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
10202                                      SourceLocation Loc, BinaryOperatorKind Opc,
10203                                      QualType* CompLHSTy) {
10204   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10205 
10206   if (LHS.get()->getType()->isVectorType() ||
10207       RHS.get()->getType()->isVectorType()) {
10208     QualType compType = CheckVectorOperands(
10209         LHS, RHS, Loc, CompLHSTy,
10210         /*AllowBothBool*/getLangOpts().AltiVec,
10211         /*AllowBoolConversions*/getLangOpts().ZVector);
10212     if (CompLHSTy) *CompLHSTy = compType;
10213     return compType;
10214   }
10215 
10216   QualType compType = UsualArithmeticConversions(
10217       LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
10218   if (LHS.isInvalid() || RHS.isInvalid())
10219     return QualType();
10220 
10221   // Diagnose "string literal" '+' int and string '+' "char literal".
10222   if (Opc == BO_Add) {
10223     diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
10224     diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
10225   }
10226 
10227   // handle the common case first (both operands are arithmetic).
10228   if (!compType.isNull() && compType->isArithmeticType()) {
10229     if (CompLHSTy) *CompLHSTy = compType;
10230     return compType;
10231   }
10232 
10233   // Type-checking.  Ultimately the pointer's going to be in PExp;
10234   // note that we bias towards the LHS being the pointer.
10235   Expr *PExp = LHS.get(), *IExp = RHS.get();
10236 
10237   bool isObjCPointer;
10238   if (PExp->getType()->isPointerType()) {
10239     isObjCPointer = false;
10240   } else if (PExp->getType()->isObjCObjectPointerType()) {
10241     isObjCPointer = true;
10242   } else {
10243     std::swap(PExp, IExp);
10244     if (PExp->getType()->isPointerType()) {
10245       isObjCPointer = false;
10246     } else if (PExp->getType()->isObjCObjectPointerType()) {
10247       isObjCPointer = true;
10248     } else {
10249       return InvalidOperands(Loc, LHS, RHS);
10250     }
10251   }
10252   assert(PExp->getType()->isAnyPointerType());
10253 
10254   if (!IExp->getType()->isIntegerType())
10255     return InvalidOperands(Loc, LHS, RHS);
10256 
10257   // Adding to a null pointer results in undefined behavior.
10258   if (PExp->IgnoreParenCasts()->isNullPointerConstant(
10259           Context, Expr::NPC_ValueDependentIsNotNull)) {
10260     // In C++ adding zero to a null pointer is defined.
10261     Expr::EvalResult KnownVal;
10262     if (!getLangOpts().CPlusPlus ||
10263         (!IExp->isValueDependent() &&
10264          (!IExp->EvaluateAsInt(KnownVal, Context) ||
10265           KnownVal.Val.getInt() != 0))) {
10266       // Check the conditions to see if this is the 'p = nullptr + n' idiom.
10267       bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension(
10268           Context, BO_Add, PExp, IExp);
10269       diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
10270     }
10271   }
10272 
10273   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
10274     return QualType();
10275 
10276   if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
10277     return QualType();
10278 
10279   // Check array bounds for pointer arithemtic
10280   CheckArrayAccess(PExp, IExp);
10281 
10282   if (CompLHSTy) {
10283     QualType LHSTy = Context.isPromotableBitField(LHS.get());
10284     if (LHSTy.isNull()) {
10285       LHSTy = LHS.get()->getType();
10286       if (LHSTy->isPromotableIntegerType())
10287         LHSTy = Context.getPromotedIntegerType(LHSTy);
10288     }
10289     *CompLHSTy = LHSTy;
10290   }
10291 
10292   return PExp->getType();
10293 }
10294 
10295 // C99 6.5.6
10296 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
10297                                         SourceLocation Loc,
10298                                         QualType* CompLHSTy) {
10299   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10300 
10301   if (LHS.get()->getType()->isVectorType() ||
10302       RHS.get()->getType()->isVectorType()) {
10303     QualType compType = CheckVectorOperands(
10304         LHS, RHS, Loc, CompLHSTy,
10305         /*AllowBothBool*/getLangOpts().AltiVec,
10306         /*AllowBoolConversions*/getLangOpts().ZVector);
10307     if (CompLHSTy) *CompLHSTy = compType;
10308     return compType;
10309   }
10310 
10311   QualType compType = UsualArithmeticConversions(
10312       LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
10313   if (LHS.isInvalid() || RHS.isInvalid())
10314     return QualType();
10315 
10316   // Enforce type constraints: C99 6.5.6p3.
10317 
10318   // Handle the common case first (both operands are arithmetic).
10319   if (!compType.isNull() && compType->isArithmeticType()) {
10320     if (CompLHSTy) *CompLHSTy = compType;
10321     return compType;
10322   }
10323 
10324   // Either ptr - int   or   ptr - ptr.
10325   if (LHS.get()->getType()->isAnyPointerType()) {
10326     QualType lpointee = LHS.get()->getType()->getPointeeType();
10327 
10328     // Diagnose bad cases where we step over interface counts.
10329     if (LHS.get()->getType()->isObjCObjectPointerType() &&
10330         checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
10331       return QualType();
10332 
10333     // The result type of a pointer-int computation is the pointer type.
10334     if (RHS.get()->getType()->isIntegerType()) {
10335       // Subtracting from a null pointer should produce a warning.
10336       // The last argument to the diagnose call says this doesn't match the
10337       // GNU int-to-pointer idiom.
10338       if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context,
10339                                            Expr::NPC_ValueDependentIsNotNull)) {
10340         // In C++ adding zero to a null pointer is defined.
10341         Expr::EvalResult KnownVal;
10342         if (!getLangOpts().CPlusPlus ||
10343             (!RHS.get()->isValueDependent() &&
10344              (!RHS.get()->EvaluateAsInt(KnownVal, Context) ||
10345               KnownVal.Val.getInt() != 0))) {
10346           diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
10347         }
10348       }
10349 
10350       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
10351         return QualType();
10352 
10353       // Check array bounds for pointer arithemtic
10354       CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
10355                        /*AllowOnePastEnd*/true, /*IndexNegated*/true);
10356 
10357       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
10358       return LHS.get()->getType();
10359     }
10360 
10361     // Handle pointer-pointer subtractions.
10362     if (const PointerType *RHSPTy
10363           = RHS.get()->getType()->getAs<PointerType>()) {
10364       QualType rpointee = RHSPTy->getPointeeType();
10365 
10366       if (getLangOpts().CPlusPlus) {
10367         // Pointee types must be the same: C++ [expr.add]
10368         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
10369           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
10370         }
10371       } else {
10372         // Pointee types must be compatible C99 6.5.6p3
10373         if (!Context.typesAreCompatible(
10374                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
10375                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
10376           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
10377           return QualType();
10378         }
10379       }
10380 
10381       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
10382                                                LHS.get(), RHS.get()))
10383         return QualType();
10384 
10385       // FIXME: Add warnings for nullptr - ptr.
10386 
10387       // The pointee type may have zero size.  As an extension, a structure or
10388       // union may have zero size or an array may have zero length.  In this
10389       // case subtraction does not make sense.
10390       if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
10391         CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
10392         if (ElementSize.isZero()) {
10393           Diag(Loc,diag::warn_sub_ptr_zero_size_types)
10394             << rpointee.getUnqualifiedType()
10395             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10396         }
10397       }
10398 
10399       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
10400       return Context.getPointerDiffType();
10401     }
10402   }
10403 
10404   return InvalidOperands(Loc, LHS, RHS);
10405 }
10406 
10407 static bool isScopedEnumerationType(QualType T) {
10408   if (const EnumType *ET = T->getAs<EnumType>())
10409     return ET->getDecl()->isScoped();
10410   return false;
10411 }
10412 
10413 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
10414                                    SourceLocation Loc, BinaryOperatorKind Opc,
10415                                    QualType LHSType) {
10416   // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
10417   // so skip remaining warnings as we don't want to modify values within Sema.
10418   if (S.getLangOpts().OpenCL)
10419     return;
10420 
10421   // Check right/shifter operand
10422   Expr::EvalResult RHSResult;
10423   if (RHS.get()->isValueDependent() ||
10424       !RHS.get()->EvaluateAsInt(RHSResult, S.Context))
10425     return;
10426   llvm::APSInt Right = RHSResult.Val.getInt();
10427 
10428   if (Right.isNegative()) {
10429     S.DiagRuntimeBehavior(Loc, RHS.get(),
10430                           S.PDiag(diag::warn_shift_negative)
10431                             << RHS.get()->getSourceRange());
10432     return;
10433   }
10434   llvm::APInt LeftBits(Right.getBitWidth(),
10435                        S.Context.getTypeSize(LHS.get()->getType()));
10436   if (Right.uge(LeftBits)) {
10437     S.DiagRuntimeBehavior(Loc, RHS.get(),
10438                           S.PDiag(diag::warn_shift_gt_typewidth)
10439                             << RHS.get()->getSourceRange());
10440     return;
10441   }
10442   if (Opc != BO_Shl)
10443     return;
10444 
10445   // When left shifting an ICE which is signed, we can check for overflow which
10446   // according to C++ standards prior to C++2a has undefined behavior
10447   // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one
10448   // more than the maximum value representable in the result type, so never
10449   // warn for those. (FIXME: Unsigned left-shift overflow in a constant
10450   // expression is still probably a bug.)
10451   Expr::EvalResult LHSResult;
10452   if (LHS.get()->isValueDependent() ||
10453       LHSType->hasUnsignedIntegerRepresentation() ||
10454       !LHS.get()->EvaluateAsInt(LHSResult, S.Context))
10455     return;
10456   llvm::APSInt Left = LHSResult.Val.getInt();
10457 
10458   // If LHS does not have a signed type and non-negative value
10459   // then, the behavior is undefined before C++2a. Warn about it.
10460   if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined() &&
10461       !S.getLangOpts().CPlusPlus2a) {
10462     S.DiagRuntimeBehavior(Loc, LHS.get(),
10463                           S.PDiag(diag::warn_shift_lhs_negative)
10464                             << LHS.get()->getSourceRange());
10465     return;
10466   }
10467 
10468   llvm::APInt ResultBits =
10469       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
10470   if (LeftBits.uge(ResultBits))
10471     return;
10472   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
10473   Result = Result.shl(Right);
10474 
10475   // Print the bit representation of the signed integer as an unsigned
10476   // hexadecimal number.
10477   SmallString<40> HexResult;
10478   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
10479 
10480   // If we are only missing a sign bit, this is less likely to result in actual
10481   // bugs -- if the result is cast back to an unsigned type, it will have the
10482   // expected value. Thus we place this behind a different warning that can be
10483   // turned off separately if needed.
10484   if (LeftBits == ResultBits - 1) {
10485     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
10486         << HexResult << LHSType
10487         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10488     return;
10489   }
10490 
10491   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
10492     << HexResult.str() << Result.getMinSignedBits() << LHSType
10493     << Left.getBitWidth() << LHS.get()->getSourceRange()
10494     << RHS.get()->getSourceRange();
10495 }
10496 
10497 /// Return the resulting type when a vector is shifted
10498 ///        by a scalar or vector shift amount.
10499 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
10500                                  SourceLocation Loc, bool IsCompAssign) {
10501   // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
10502   if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
10503       !LHS.get()->getType()->isVectorType()) {
10504     S.Diag(Loc, diag::err_shift_rhs_only_vector)
10505       << RHS.get()->getType() << LHS.get()->getType()
10506       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10507     return QualType();
10508   }
10509 
10510   if (!IsCompAssign) {
10511     LHS = S.UsualUnaryConversions(LHS.get());
10512     if (LHS.isInvalid()) return QualType();
10513   }
10514 
10515   RHS = S.UsualUnaryConversions(RHS.get());
10516   if (RHS.isInvalid()) return QualType();
10517 
10518   QualType LHSType = LHS.get()->getType();
10519   // Note that LHS might be a scalar because the routine calls not only in
10520   // OpenCL case.
10521   const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
10522   QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
10523 
10524   // Note that RHS might not be a vector.
10525   QualType RHSType = RHS.get()->getType();
10526   const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
10527   QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
10528 
10529   // The operands need to be integers.
10530   if (!LHSEleType->isIntegerType()) {
10531     S.Diag(Loc, diag::err_typecheck_expect_int)
10532       << LHS.get()->getType() << LHS.get()->getSourceRange();
10533     return QualType();
10534   }
10535 
10536   if (!RHSEleType->isIntegerType()) {
10537     S.Diag(Loc, diag::err_typecheck_expect_int)
10538       << RHS.get()->getType() << RHS.get()->getSourceRange();
10539     return QualType();
10540   }
10541 
10542   if (!LHSVecTy) {
10543     assert(RHSVecTy);
10544     if (IsCompAssign)
10545       return RHSType;
10546     if (LHSEleType != RHSEleType) {
10547       LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
10548       LHSEleType = RHSEleType;
10549     }
10550     QualType VecTy =
10551         S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
10552     LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
10553     LHSType = VecTy;
10554   } else if (RHSVecTy) {
10555     // OpenCL v1.1 s6.3.j says that for vector types, the operators
10556     // are applied component-wise. So if RHS is a vector, then ensure
10557     // that the number of elements is the same as LHS...
10558     if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
10559       S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
10560         << LHS.get()->getType() << RHS.get()->getType()
10561         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10562       return QualType();
10563     }
10564     if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
10565       const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
10566       const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
10567       if (LHSBT != RHSBT &&
10568           S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
10569         S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
10570             << LHS.get()->getType() << RHS.get()->getType()
10571             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10572       }
10573     }
10574   } else {
10575     // ...else expand RHS to match the number of elements in LHS.
10576     QualType VecTy =
10577       S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
10578     RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
10579   }
10580 
10581   return LHSType;
10582 }
10583 
10584 // C99 6.5.7
10585 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
10586                                   SourceLocation Loc, BinaryOperatorKind Opc,
10587                                   bool IsCompAssign) {
10588   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10589 
10590   // Vector shifts promote their scalar inputs to vector type.
10591   if (LHS.get()->getType()->isVectorType() ||
10592       RHS.get()->getType()->isVectorType()) {
10593     if (LangOpts.ZVector) {
10594       // The shift operators for the z vector extensions work basically
10595       // like general shifts, except that neither the LHS nor the RHS is
10596       // allowed to be a "vector bool".
10597       if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
10598         if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
10599           return InvalidOperands(Loc, LHS, RHS);
10600       if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
10601         if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
10602           return InvalidOperands(Loc, LHS, RHS);
10603     }
10604     return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
10605   }
10606 
10607   // Shifts don't perform usual arithmetic conversions, they just do integer
10608   // promotions on each operand. C99 6.5.7p3
10609 
10610   // For the LHS, do usual unary conversions, but then reset them away
10611   // if this is a compound assignment.
10612   ExprResult OldLHS = LHS;
10613   LHS = UsualUnaryConversions(LHS.get());
10614   if (LHS.isInvalid())
10615     return QualType();
10616   QualType LHSType = LHS.get()->getType();
10617   if (IsCompAssign) LHS = OldLHS;
10618 
10619   // The RHS is simpler.
10620   RHS = UsualUnaryConversions(RHS.get());
10621   if (RHS.isInvalid())
10622     return QualType();
10623   QualType RHSType = RHS.get()->getType();
10624 
10625   // C99 6.5.7p2: Each of the operands shall have integer type.
10626   if (!LHSType->hasIntegerRepresentation() ||
10627       !RHSType->hasIntegerRepresentation())
10628     return InvalidOperands(Loc, LHS, RHS);
10629 
10630   // C++0x: Don't allow scoped enums. FIXME: Use something better than
10631   // hasIntegerRepresentation() above instead of this.
10632   if (isScopedEnumerationType(LHSType) ||
10633       isScopedEnumerationType(RHSType)) {
10634     return InvalidOperands(Loc, LHS, RHS);
10635   }
10636   // Sanity-check shift operands
10637   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
10638 
10639   // "The type of the result is that of the promoted left operand."
10640   return LHSType;
10641 }
10642 
10643 /// Diagnose bad pointer comparisons.
10644 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
10645                                               ExprResult &LHS, ExprResult &RHS,
10646                                               bool IsError) {
10647   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
10648                       : diag::ext_typecheck_comparison_of_distinct_pointers)
10649     << LHS.get()->getType() << RHS.get()->getType()
10650     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10651 }
10652 
10653 /// Returns false if the pointers are converted to a composite type,
10654 /// true otherwise.
10655 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
10656                                            ExprResult &LHS, ExprResult &RHS) {
10657   // C++ [expr.rel]p2:
10658   //   [...] Pointer conversions (4.10) and qualification
10659   //   conversions (4.4) are performed on pointer operands (or on
10660   //   a pointer operand and a null pointer constant) to bring
10661   //   them to their composite pointer type. [...]
10662   //
10663   // C++ [expr.eq]p1 uses the same notion for (in)equality
10664   // comparisons of pointers.
10665 
10666   QualType LHSType = LHS.get()->getType();
10667   QualType RHSType = RHS.get()->getType();
10668   assert(LHSType->isPointerType() || RHSType->isPointerType() ||
10669          LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
10670 
10671   QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
10672   if (T.isNull()) {
10673     if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) &&
10674         (RHSType->isAnyPointerType() || RHSType->isMemberPointerType()))
10675       diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
10676     else
10677       S.InvalidOperands(Loc, LHS, RHS);
10678     return true;
10679   }
10680 
10681   return false;
10682 }
10683 
10684 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
10685                                                     ExprResult &LHS,
10686                                                     ExprResult &RHS,
10687                                                     bool IsError) {
10688   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
10689                       : diag::ext_typecheck_comparison_of_fptr_to_void)
10690     << LHS.get()->getType() << RHS.get()->getType()
10691     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10692 }
10693 
10694 static bool isObjCObjectLiteral(ExprResult &E) {
10695   switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
10696   case Stmt::ObjCArrayLiteralClass:
10697   case Stmt::ObjCDictionaryLiteralClass:
10698   case Stmt::ObjCStringLiteralClass:
10699   case Stmt::ObjCBoxedExprClass:
10700     return true;
10701   default:
10702     // Note that ObjCBoolLiteral is NOT an object literal!
10703     return false;
10704   }
10705 }
10706 
10707 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
10708   const ObjCObjectPointerType *Type =
10709     LHS->getType()->getAs<ObjCObjectPointerType>();
10710 
10711   // If this is not actually an Objective-C object, bail out.
10712   if (!Type)
10713     return false;
10714 
10715   // Get the LHS object's interface type.
10716   QualType InterfaceType = Type->getPointeeType();
10717 
10718   // If the RHS isn't an Objective-C object, bail out.
10719   if (!RHS->getType()->isObjCObjectPointerType())
10720     return false;
10721 
10722   // Try to find the -isEqual: method.
10723   Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
10724   ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
10725                                                       InterfaceType,
10726                                                       /*IsInstance=*/true);
10727   if (!Method) {
10728     if (Type->isObjCIdType()) {
10729       // For 'id', just check the global pool.
10730       Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
10731                                                   /*receiverId=*/true);
10732     } else {
10733       // Check protocols.
10734       Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
10735                                              /*IsInstance=*/true);
10736     }
10737   }
10738 
10739   if (!Method)
10740     return false;
10741 
10742   QualType T = Method->parameters()[0]->getType();
10743   if (!T->isObjCObjectPointerType())
10744     return false;
10745 
10746   QualType R = Method->getReturnType();
10747   if (!R->isScalarType())
10748     return false;
10749 
10750   return true;
10751 }
10752 
10753 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
10754   FromE = FromE->IgnoreParenImpCasts();
10755   switch (FromE->getStmtClass()) {
10756     default:
10757       break;
10758     case Stmt::ObjCStringLiteralClass:
10759       // "string literal"
10760       return LK_String;
10761     case Stmt::ObjCArrayLiteralClass:
10762       // "array literal"
10763       return LK_Array;
10764     case Stmt::ObjCDictionaryLiteralClass:
10765       // "dictionary literal"
10766       return LK_Dictionary;
10767     case Stmt::BlockExprClass:
10768       return LK_Block;
10769     case Stmt::ObjCBoxedExprClass: {
10770       Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
10771       switch (Inner->getStmtClass()) {
10772         case Stmt::IntegerLiteralClass:
10773         case Stmt::FloatingLiteralClass:
10774         case Stmt::CharacterLiteralClass:
10775         case Stmt::ObjCBoolLiteralExprClass:
10776         case Stmt::CXXBoolLiteralExprClass:
10777           // "numeric literal"
10778           return LK_Numeric;
10779         case Stmt::ImplicitCastExprClass: {
10780           CastKind CK = cast<CastExpr>(Inner)->getCastKind();
10781           // Boolean literals can be represented by implicit casts.
10782           if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
10783             return LK_Numeric;
10784           break;
10785         }
10786         default:
10787           break;
10788       }
10789       return LK_Boxed;
10790     }
10791   }
10792   return LK_None;
10793 }
10794 
10795 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
10796                                           ExprResult &LHS, ExprResult &RHS,
10797                                           BinaryOperator::Opcode Opc){
10798   Expr *Literal;
10799   Expr *Other;
10800   if (isObjCObjectLiteral(LHS)) {
10801     Literal = LHS.get();
10802     Other = RHS.get();
10803   } else {
10804     Literal = RHS.get();
10805     Other = LHS.get();
10806   }
10807 
10808   // Don't warn on comparisons against nil.
10809   Other = Other->IgnoreParenCasts();
10810   if (Other->isNullPointerConstant(S.getASTContext(),
10811                                    Expr::NPC_ValueDependentIsNotNull))
10812     return;
10813 
10814   // This should be kept in sync with warn_objc_literal_comparison.
10815   // LK_String should always be after the other literals, since it has its own
10816   // warning flag.
10817   Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
10818   assert(LiteralKind != Sema::LK_Block);
10819   if (LiteralKind == Sema::LK_None) {
10820     llvm_unreachable("Unknown Objective-C object literal kind");
10821   }
10822 
10823   if (LiteralKind == Sema::LK_String)
10824     S.Diag(Loc, diag::warn_objc_string_literal_comparison)
10825       << Literal->getSourceRange();
10826   else
10827     S.Diag(Loc, diag::warn_objc_literal_comparison)
10828       << LiteralKind << Literal->getSourceRange();
10829 
10830   if (BinaryOperator::isEqualityOp(Opc) &&
10831       hasIsEqualMethod(S, LHS.get(), RHS.get())) {
10832     SourceLocation Start = LHS.get()->getBeginLoc();
10833     SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc());
10834     CharSourceRange OpRange =
10835       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
10836 
10837     S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
10838       << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
10839       << FixItHint::CreateReplacement(OpRange, " isEqual:")
10840       << FixItHint::CreateInsertion(End, "]");
10841   }
10842 }
10843 
10844 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
10845 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
10846                                            ExprResult &RHS, SourceLocation Loc,
10847                                            BinaryOperatorKind Opc) {
10848   // Check that left hand side is !something.
10849   UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
10850   if (!UO || UO->getOpcode() != UO_LNot) return;
10851 
10852   // Only check if the right hand side is non-bool arithmetic type.
10853   if (RHS.get()->isKnownToHaveBooleanValue()) return;
10854 
10855   // Make sure that the something in !something is not bool.
10856   Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
10857   if (SubExpr->isKnownToHaveBooleanValue()) return;
10858 
10859   // Emit warning.
10860   bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
10861   S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
10862       << Loc << IsBitwiseOp;
10863 
10864   // First note suggest !(x < y)
10865   SourceLocation FirstOpen = SubExpr->getBeginLoc();
10866   SourceLocation FirstClose = RHS.get()->getEndLoc();
10867   FirstClose = S.getLocForEndOfToken(FirstClose);
10868   if (FirstClose.isInvalid())
10869     FirstOpen = SourceLocation();
10870   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
10871       << IsBitwiseOp
10872       << FixItHint::CreateInsertion(FirstOpen, "(")
10873       << FixItHint::CreateInsertion(FirstClose, ")");
10874 
10875   // Second note suggests (!x) < y
10876   SourceLocation SecondOpen = LHS.get()->getBeginLoc();
10877   SourceLocation SecondClose = LHS.get()->getEndLoc();
10878   SecondClose = S.getLocForEndOfToken(SecondClose);
10879   if (SecondClose.isInvalid())
10880     SecondOpen = SourceLocation();
10881   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
10882       << FixItHint::CreateInsertion(SecondOpen, "(")
10883       << FixItHint::CreateInsertion(SecondClose, ")");
10884 }
10885 
10886 // Returns true if E refers to a non-weak array.
10887 static bool checkForArray(const Expr *E) {
10888   const ValueDecl *D = nullptr;
10889   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
10890     D = DR->getDecl();
10891   } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
10892     if (Mem->isImplicitAccess())
10893       D = Mem->getMemberDecl();
10894   }
10895   if (!D)
10896     return false;
10897   return D->getType()->isArrayType() && !D->isWeak();
10898 }
10899 
10900 /// Diagnose some forms of syntactically-obvious tautological comparison.
10901 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc,
10902                                            Expr *LHS, Expr *RHS,
10903                                            BinaryOperatorKind Opc) {
10904   Expr *LHSStripped = LHS->IgnoreParenImpCasts();
10905   Expr *RHSStripped = RHS->IgnoreParenImpCasts();
10906 
10907   QualType LHSType = LHS->getType();
10908   QualType RHSType = RHS->getType();
10909   if (LHSType->hasFloatingRepresentation() ||
10910       (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
10911       S.inTemplateInstantiation())
10912     return;
10913 
10914   // Comparisons between two array types are ill-formed for operator<=>, so
10915   // we shouldn't emit any additional warnings about it.
10916   if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
10917     return;
10918 
10919   // For non-floating point types, check for self-comparisons of the form
10920   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
10921   // often indicate logic errors in the program.
10922   //
10923   // NOTE: Don't warn about comparison expressions resulting from macro
10924   // expansion. Also don't warn about comparisons which are only self
10925   // comparisons within a template instantiation. The warnings should catch
10926   // obvious cases in the definition of the template anyways. The idea is to
10927   // warn when the typed comparison operator will always evaluate to the same
10928   // result.
10929 
10930   // Used for indexing into %select in warn_comparison_always
10931   enum {
10932     AlwaysConstant,
10933     AlwaysTrue,
10934     AlwaysFalse,
10935     AlwaysEqual, // std::strong_ordering::equal from operator<=>
10936   };
10937 
10938   // C++2a [depr.array.comp]:
10939   //   Equality and relational comparisons ([expr.eq], [expr.rel]) between two
10940   //   operands of array type are deprecated.
10941   if (S.getLangOpts().CPlusPlus2a && LHSStripped->getType()->isArrayType() &&
10942       RHSStripped->getType()->isArrayType()) {
10943     S.Diag(Loc, diag::warn_depr_array_comparison)
10944         << LHS->getSourceRange() << RHS->getSourceRange()
10945         << LHSStripped->getType() << RHSStripped->getType();
10946     // Carry on to produce the tautological comparison warning, if this
10947     // expression is potentially-evaluated, we can resolve the array to a
10948     // non-weak declaration, and so on.
10949   }
10950 
10951   if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) {
10952     if (Expr::isSameComparisonOperand(LHS, RHS)) {
10953       unsigned Result;
10954       switch (Opc) {
10955       case BO_EQ:
10956       case BO_LE:
10957       case BO_GE:
10958         Result = AlwaysTrue;
10959         break;
10960       case BO_NE:
10961       case BO_LT:
10962       case BO_GT:
10963         Result = AlwaysFalse;
10964         break;
10965       case BO_Cmp:
10966         Result = AlwaysEqual;
10967         break;
10968       default:
10969         Result = AlwaysConstant;
10970         break;
10971       }
10972       S.DiagRuntimeBehavior(Loc, nullptr,
10973                             S.PDiag(diag::warn_comparison_always)
10974                                 << 0 /*self-comparison*/
10975                                 << Result);
10976     } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) {
10977       // What is it always going to evaluate to?
10978       unsigned Result;
10979       switch (Opc) {
10980       case BO_EQ: // e.g. array1 == array2
10981         Result = AlwaysFalse;
10982         break;
10983       case BO_NE: // e.g. array1 != array2
10984         Result = AlwaysTrue;
10985         break;
10986       default: // e.g. array1 <= array2
10987         // The best we can say is 'a constant'
10988         Result = AlwaysConstant;
10989         break;
10990       }
10991       S.DiagRuntimeBehavior(Loc, nullptr,
10992                             S.PDiag(diag::warn_comparison_always)
10993                                 << 1 /*array comparison*/
10994                                 << Result);
10995     }
10996   }
10997 
10998   if (isa<CastExpr>(LHSStripped))
10999     LHSStripped = LHSStripped->IgnoreParenCasts();
11000   if (isa<CastExpr>(RHSStripped))
11001     RHSStripped = RHSStripped->IgnoreParenCasts();
11002 
11003   // Warn about comparisons against a string constant (unless the other
11004   // operand is null); the user probably wants string comparison function.
11005   Expr *LiteralString = nullptr;
11006   Expr *LiteralStringStripped = nullptr;
11007   if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
11008       !RHSStripped->isNullPointerConstant(S.Context,
11009                                           Expr::NPC_ValueDependentIsNull)) {
11010     LiteralString = LHS;
11011     LiteralStringStripped = LHSStripped;
11012   } else if ((isa<StringLiteral>(RHSStripped) ||
11013               isa<ObjCEncodeExpr>(RHSStripped)) &&
11014              !LHSStripped->isNullPointerConstant(S.Context,
11015                                           Expr::NPC_ValueDependentIsNull)) {
11016     LiteralString = RHS;
11017     LiteralStringStripped = RHSStripped;
11018   }
11019 
11020   if (LiteralString) {
11021     S.DiagRuntimeBehavior(Loc, nullptr,
11022                           S.PDiag(diag::warn_stringcompare)
11023                               << isa<ObjCEncodeExpr>(LiteralStringStripped)
11024                               << LiteralString->getSourceRange());
11025   }
11026 }
11027 
11028 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) {
11029   switch (CK) {
11030   default: {
11031 #ifndef NDEBUG
11032     llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
11033                  << "\n";
11034 #endif
11035     llvm_unreachable("unhandled cast kind");
11036   }
11037   case CK_UserDefinedConversion:
11038     return ICK_Identity;
11039   case CK_LValueToRValue:
11040     return ICK_Lvalue_To_Rvalue;
11041   case CK_ArrayToPointerDecay:
11042     return ICK_Array_To_Pointer;
11043   case CK_FunctionToPointerDecay:
11044     return ICK_Function_To_Pointer;
11045   case CK_IntegralCast:
11046     return ICK_Integral_Conversion;
11047   case CK_FloatingCast:
11048     return ICK_Floating_Conversion;
11049   case CK_IntegralToFloating:
11050   case CK_FloatingToIntegral:
11051     return ICK_Floating_Integral;
11052   case CK_IntegralComplexCast:
11053   case CK_FloatingComplexCast:
11054   case CK_FloatingComplexToIntegralComplex:
11055   case CK_IntegralComplexToFloatingComplex:
11056     return ICK_Complex_Conversion;
11057   case CK_FloatingComplexToReal:
11058   case CK_FloatingRealToComplex:
11059   case CK_IntegralComplexToReal:
11060   case CK_IntegralRealToComplex:
11061     return ICK_Complex_Real;
11062   }
11063 }
11064 
11065 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E,
11066                                              QualType FromType,
11067                                              SourceLocation Loc) {
11068   // Check for a narrowing implicit conversion.
11069   StandardConversionSequence SCS;
11070   SCS.setAsIdentityConversion();
11071   SCS.setToType(0, FromType);
11072   SCS.setToType(1, ToType);
11073   if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
11074     SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
11075 
11076   APValue PreNarrowingValue;
11077   QualType PreNarrowingType;
11078   switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
11079                                PreNarrowingType,
11080                                /*IgnoreFloatToIntegralConversion*/ true)) {
11081   case NK_Dependent_Narrowing:
11082     // Implicit conversion to a narrower type, but the expression is
11083     // value-dependent so we can't tell whether it's actually narrowing.
11084   case NK_Not_Narrowing:
11085     return false;
11086 
11087   case NK_Constant_Narrowing:
11088     // Implicit conversion to a narrower type, and the value is not a constant
11089     // expression.
11090     S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
11091         << /*Constant*/ 1
11092         << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
11093     return true;
11094 
11095   case NK_Variable_Narrowing:
11096     // Implicit conversion to a narrower type, and the value is not a constant
11097     // expression.
11098   case NK_Type_Narrowing:
11099     S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
11100         << /*Constant*/ 0 << FromType << ToType;
11101     // TODO: It's not a constant expression, but what if the user intended it
11102     // to be? Can we produce notes to help them figure out why it isn't?
11103     return true;
11104   }
11105   llvm_unreachable("unhandled case in switch");
11106 }
11107 
11108 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S,
11109                                                          ExprResult &LHS,
11110                                                          ExprResult &RHS,
11111                                                          SourceLocation Loc) {
11112   QualType LHSType = LHS.get()->getType();
11113   QualType RHSType = RHS.get()->getType();
11114   // Dig out the original argument type and expression before implicit casts
11115   // were applied. These are the types/expressions we need to check the
11116   // [expr.spaceship] requirements against.
11117   ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
11118   ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
11119   QualType LHSStrippedType = LHSStripped.get()->getType();
11120   QualType RHSStrippedType = RHSStripped.get()->getType();
11121 
11122   // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
11123   // other is not, the program is ill-formed.
11124   if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
11125     S.InvalidOperands(Loc, LHSStripped, RHSStripped);
11126     return QualType();
11127   }
11128 
11129   // FIXME: Consider combining this with checkEnumArithmeticConversions.
11130   int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
11131                     RHSStrippedType->isEnumeralType();
11132   if (NumEnumArgs == 1) {
11133     bool LHSIsEnum = LHSStrippedType->isEnumeralType();
11134     QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
11135     if (OtherTy->hasFloatingRepresentation()) {
11136       S.InvalidOperands(Loc, LHSStripped, RHSStripped);
11137       return QualType();
11138     }
11139   }
11140   if (NumEnumArgs == 2) {
11141     // C++2a [expr.spaceship]p5: If both operands have the same enumeration
11142     // type E, the operator yields the result of converting the operands
11143     // to the underlying type of E and applying <=> to the converted operands.
11144     if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
11145       S.InvalidOperands(Loc, LHS, RHS);
11146       return QualType();
11147     }
11148     QualType IntType =
11149         LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType();
11150     assert(IntType->isArithmeticType());
11151 
11152     // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
11153     // promote the boolean type, and all other promotable integer types, to
11154     // avoid this.
11155     if (IntType->isPromotableIntegerType())
11156       IntType = S.Context.getPromotedIntegerType(IntType);
11157 
11158     LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
11159     RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
11160     LHSType = RHSType = IntType;
11161   }
11162 
11163   // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
11164   // usual arithmetic conversions are applied to the operands.
11165   QualType Type =
11166       S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison);
11167   if (LHS.isInvalid() || RHS.isInvalid())
11168     return QualType();
11169   if (Type.isNull())
11170     return S.InvalidOperands(Loc, LHS, RHS);
11171 
11172   Optional<ComparisonCategoryType> CCT =
11173       getComparisonCategoryForBuiltinCmp(Type);
11174   if (!CCT)
11175     return S.InvalidOperands(Loc, LHS, RHS);
11176 
11177   bool HasNarrowing = checkThreeWayNarrowingConversion(
11178       S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc());
11179   HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType,
11180                                                    RHS.get()->getBeginLoc());
11181   if (HasNarrowing)
11182     return QualType();
11183 
11184   assert(!Type.isNull() && "composite type for <=> has not been set");
11185 
11186   return S.CheckComparisonCategoryType(
11187       *CCT, Loc, Sema::ComparisonCategoryUsage::OperatorInExpression);
11188 }
11189 
11190 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS,
11191                                                  ExprResult &RHS,
11192                                                  SourceLocation Loc,
11193                                                  BinaryOperatorKind Opc) {
11194   if (Opc == BO_Cmp)
11195     return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
11196 
11197   // C99 6.5.8p3 / C99 6.5.9p4
11198   QualType Type =
11199       S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison);
11200   if (LHS.isInvalid() || RHS.isInvalid())
11201     return QualType();
11202   if (Type.isNull())
11203     return S.InvalidOperands(Loc, LHS, RHS);
11204   assert(Type->isArithmeticType() || Type->isEnumeralType());
11205 
11206   if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc))
11207     return S.InvalidOperands(Loc, LHS, RHS);
11208 
11209   // Check for comparisons of floating point operands using != and ==.
11210   if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc))
11211     S.CheckFloatComparison(Loc, LHS.get(), RHS.get());
11212 
11213   // The result of comparisons is 'bool' in C++, 'int' in C.
11214   return S.Context.getLogicalOperationType();
11215 }
11216 
11217 void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) {
11218   if (!NullE.get()->getType()->isAnyPointerType())
11219     return;
11220   int NullValue = PP.isMacroDefined("NULL") ? 0 : 1;
11221   if (!E.get()->getType()->isAnyPointerType() &&
11222       E.get()->isNullPointerConstant(Context,
11223                                      Expr::NPC_ValueDependentIsNotNull) ==
11224         Expr::NPCK_ZeroExpression) {
11225     if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) {
11226       if (CL->getValue() == 0)
11227         Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
11228             << NullValue
11229             << FixItHint::CreateReplacement(E.get()->getExprLoc(),
11230                                             NullValue ? "NULL" : "(void *)0");
11231     } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) {
11232         TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
11233         QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType();
11234         if (T == Context.CharTy)
11235           Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
11236               << NullValue
11237               << FixItHint::CreateReplacement(E.get()->getExprLoc(),
11238                                               NullValue ? "NULL" : "(void *)0");
11239       }
11240   }
11241 }
11242 
11243 // C99 6.5.8, C++ [expr.rel]
11244 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
11245                                     SourceLocation Loc,
11246                                     BinaryOperatorKind Opc) {
11247   bool IsRelational = BinaryOperator::isRelationalOp(Opc);
11248   bool IsThreeWay = Opc == BO_Cmp;
11249   bool IsOrdered = IsRelational || IsThreeWay;
11250   auto IsAnyPointerType = [](ExprResult E) {
11251     QualType Ty = E.get()->getType();
11252     return Ty->isPointerType() || Ty->isMemberPointerType();
11253   };
11254 
11255   // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
11256   // type, array-to-pointer, ..., conversions are performed on both operands to
11257   // bring them to their composite type.
11258   // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
11259   // any type-related checks.
11260   if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
11261     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
11262     if (LHS.isInvalid())
11263       return QualType();
11264     RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
11265     if (RHS.isInvalid())
11266       return QualType();
11267   } else {
11268     LHS = DefaultLvalueConversion(LHS.get());
11269     if (LHS.isInvalid())
11270       return QualType();
11271     RHS = DefaultLvalueConversion(RHS.get());
11272     if (RHS.isInvalid())
11273       return QualType();
11274   }
11275 
11276   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true);
11277   if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) {
11278     CheckPtrComparisonWithNullChar(LHS, RHS);
11279     CheckPtrComparisonWithNullChar(RHS, LHS);
11280   }
11281 
11282   // Handle vector comparisons separately.
11283   if (LHS.get()->getType()->isVectorType() ||
11284       RHS.get()->getType()->isVectorType())
11285     return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
11286 
11287   diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
11288   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
11289 
11290   QualType LHSType = LHS.get()->getType();
11291   QualType RHSType = RHS.get()->getType();
11292   if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
11293       (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
11294     return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
11295 
11296   const Expr::NullPointerConstantKind LHSNullKind =
11297       LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
11298   const Expr::NullPointerConstantKind RHSNullKind =
11299       RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
11300   bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
11301   bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
11302 
11303   auto computeResultTy = [&]() {
11304     if (Opc != BO_Cmp)
11305       return Context.getLogicalOperationType();
11306     assert(getLangOpts().CPlusPlus);
11307     assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
11308 
11309     QualType CompositeTy = LHS.get()->getType();
11310     assert(!CompositeTy->isReferenceType());
11311 
11312     Optional<ComparisonCategoryType> CCT =
11313         getComparisonCategoryForBuiltinCmp(CompositeTy);
11314     if (!CCT)
11315       return InvalidOperands(Loc, LHS, RHS);
11316 
11317     if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) {
11318       // P0946R0: Comparisons between a null pointer constant and an object
11319       // pointer result in std::strong_equality, which is ill-formed under
11320       // P1959R0.
11321       Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero)
11322           << (LHSIsNull ? LHS.get()->getSourceRange()
11323                         : RHS.get()->getSourceRange());
11324       return QualType();
11325     }
11326 
11327     return CheckComparisonCategoryType(
11328         *CCT, Loc, ComparisonCategoryUsage::OperatorInExpression);
11329   };
11330 
11331   if (!IsOrdered && LHSIsNull != RHSIsNull) {
11332     bool IsEquality = Opc == BO_EQ;
11333     if (RHSIsNull)
11334       DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
11335                                    RHS.get()->getSourceRange());
11336     else
11337       DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
11338                                    LHS.get()->getSourceRange());
11339   }
11340 
11341   if ((LHSType->isIntegerType() && !LHSIsNull) ||
11342       (RHSType->isIntegerType() && !RHSIsNull)) {
11343     // Skip normal pointer conversion checks in this case; we have better
11344     // diagnostics for this below.
11345   } else if (getLangOpts().CPlusPlus) {
11346     // Equality comparison of a function pointer to a void pointer is invalid,
11347     // but we allow it as an extension.
11348     // FIXME: If we really want to allow this, should it be part of composite
11349     // pointer type computation so it works in conditionals too?
11350     if (!IsOrdered &&
11351         ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
11352          (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
11353       // This is a gcc extension compatibility comparison.
11354       // In a SFINAE context, we treat this as a hard error to maintain
11355       // conformance with the C++ standard.
11356       diagnoseFunctionPointerToVoidComparison(
11357           *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
11358 
11359       if (isSFINAEContext())
11360         return QualType();
11361 
11362       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
11363       return computeResultTy();
11364     }
11365 
11366     // C++ [expr.eq]p2:
11367     //   If at least one operand is a pointer [...] bring them to their
11368     //   composite pointer type.
11369     // C++ [expr.spaceship]p6
11370     //  If at least one of the operands is of pointer type, [...] bring them
11371     //  to their composite pointer type.
11372     // C++ [expr.rel]p2:
11373     //   If both operands are pointers, [...] bring them to their composite
11374     //   pointer type.
11375     // For <=>, the only valid non-pointer types are arrays and functions, and
11376     // we already decayed those, so this is really the same as the relational
11377     // comparison rule.
11378     if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
11379             (IsOrdered ? 2 : 1) &&
11380         (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
11381                                          RHSType->isObjCObjectPointerType()))) {
11382       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
11383         return QualType();
11384       return computeResultTy();
11385     }
11386   } else if (LHSType->isPointerType() &&
11387              RHSType->isPointerType()) { // C99 6.5.8p2
11388     // All of the following pointer-related warnings are GCC extensions, except
11389     // when handling null pointer constants.
11390     QualType LCanPointeeTy =
11391       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
11392     QualType RCanPointeeTy =
11393       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
11394 
11395     // C99 6.5.9p2 and C99 6.5.8p2
11396     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
11397                                    RCanPointeeTy.getUnqualifiedType())) {
11398       // Valid unless a relational comparison of function pointers
11399       if (IsRelational && LCanPointeeTy->isFunctionType()) {
11400         Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
11401           << LHSType << RHSType << LHS.get()->getSourceRange()
11402           << RHS.get()->getSourceRange();
11403       }
11404     } else if (!IsRelational &&
11405                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
11406       // Valid unless comparison between non-null pointer and function pointer
11407       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
11408           && !LHSIsNull && !RHSIsNull)
11409         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
11410                                                 /*isError*/false);
11411     } else {
11412       // Invalid
11413       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
11414     }
11415     if (LCanPointeeTy != RCanPointeeTy) {
11416       // Treat NULL constant as a special case in OpenCL.
11417       if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
11418         const PointerType *LHSPtr = LHSType->castAs<PointerType>();
11419         if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->castAs<PointerType>())) {
11420           Diag(Loc,
11421                diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
11422               << LHSType << RHSType << 0 /* comparison */
11423               << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11424         }
11425       }
11426       LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
11427       LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
11428       CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
11429                                                : CK_BitCast;
11430       if (LHSIsNull && !RHSIsNull)
11431         LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
11432       else
11433         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
11434     }
11435     return computeResultTy();
11436   }
11437 
11438   if (getLangOpts().CPlusPlus) {
11439     // C++ [expr.eq]p4:
11440     //   Two operands of type std::nullptr_t or one operand of type
11441     //   std::nullptr_t and the other a null pointer constant compare equal.
11442     if (!IsOrdered && LHSIsNull && RHSIsNull) {
11443       if (LHSType->isNullPtrType()) {
11444         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11445         return computeResultTy();
11446       }
11447       if (RHSType->isNullPtrType()) {
11448         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11449         return computeResultTy();
11450       }
11451     }
11452 
11453     // Comparison of Objective-C pointers and block pointers against nullptr_t.
11454     // These aren't covered by the composite pointer type rules.
11455     if (!IsOrdered && RHSType->isNullPtrType() &&
11456         (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
11457       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11458       return computeResultTy();
11459     }
11460     if (!IsOrdered && LHSType->isNullPtrType() &&
11461         (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
11462       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11463       return computeResultTy();
11464     }
11465 
11466     if (IsRelational &&
11467         ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
11468          (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
11469       // HACK: Relational comparison of nullptr_t against a pointer type is
11470       // invalid per DR583, but we allow it within std::less<> and friends,
11471       // since otherwise common uses of it break.
11472       // FIXME: Consider removing this hack once LWG fixes std::less<> and
11473       // friends to have std::nullptr_t overload candidates.
11474       DeclContext *DC = CurContext;
11475       if (isa<FunctionDecl>(DC))
11476         DC = DC->getParent();
11477       if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
11478         if (CTSD->isInStdNamespace() &&
11479             llvm::StringSwitch<bool>(CTSD->getName())
11480                 .Cases("less", "less_equal", "greater", "greater_equal", true)
11481                 .Default(false)) {
11482           if (RHSType->isNullPtrType())
11483             RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11484           else
11485             LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11486           return computeResultTy();
11487         }
11488       }
11489     }
11490 
11491     // C++ [expr.eq]p2:
11492     //   If at least one operand is a pointer to member, [...] bring them to
11493     //   their composite pointer type.
11494     if (!IsOrdered &&
11495         (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
11496       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
11497         return QualType();
11498       else
11499         return computeResultTy();
11500     }
11501   }
11502 
11503   // Handle block pointer types.
11504   if (!IsOrdered && LHSType->isBlockPointerType() &&
11505       RHSType->isBlockPointerType()) {
11506     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
11507     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
11508 
11509     if (!LHSIsNull && !RHSIsNull &&
11510         !Context.typesAreCompatible(lpointee, rpointee)) {
11511       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
11512         << LHSType << RHSType << LHS.get()->getSourceRange()
11513         << RHS.get()->getSourceRange();
11514     }
11515     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
11516     return computeResultTy();
11517   }
11518 
11519   // Allow block pointers to be compared with null pointer constants.
11520   if (!IsOrdered
11521       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
11522           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
11523     if (!LHSIsNull && !RHSIsNull) {
11524       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
11525              ->getPointeeType()->isVoidType())
11526             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
11527                 ->getPointeeType()->isVoidType())))
11528         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
11529           << LHSType << RHSType << LHS.get()->getSourceRange()
11530           << RHS.get()->getSourceRange();
11531     }
11532     if (LHSIsNull && !RHSIsNull)
11533       LHS = ImpCastExprToType(LHS.get(), RHSType,
11534                               RHSType->isPointerType() ? CK_BitCast
11535                                 : CK_AnyPointerToBlockPointerCast);
11536     else
11537       RHS = ImpCastExprToType(RHS.get(), LHSType,
11538                               LHSType->isPointerType() ? CK_BitCast
11539                                 : CK_AnyPointerToBlockPointerCast);
11540     return computeResultTy();
11541   }
11542 
11543   if (LHSType->isObjCObjectPointerType() ||
11544       RHSType->isObjCObjectPointerType()) {
11545     const PointerType *LPT = LHSType->getAs<PointerType>();
11546     const PointerType *RPT = RHSType->getAs<PointerType>();
11547     if (LPT || RPT) {
11548       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
11549       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
11550 
11551       if (!LPtrToVoid && !RPtrToVoid &&
11552           !Context.typesAreCompatible(LHSType, RHSType)) {
11553         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
11554                                           /*isError*/false);
11555       }
11556       // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than
11557       // the RHS, but we have test coverage for this behavior.
11558       // FIXME: Consider using convertPointersToCompositeType in C++.
11559       if (LHSIsNull && !RHSIsNull) {
11560         Expr *E = LHS.get();
11561         if (getLangOpts().ObjCAutoRefCount)
11562           CheckObjCConversion(SourceRange(), RHSType, E,
11563                               CCK_ImplicitConversion);
11564         LHS = ImpCastExprToType(E, RHSType,
11565                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
11566       }
11567       else {
11568         Expr *E = RHS.get();
11569         if (getLangOpts().ObjCAutoRefCount)
11570           CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion,
11571                               /*Diagnose=*/true,
11572                               /*DiagnoseCFAudited=*/false, Opc);
11573         RHS = ImpCastExprToType(E, LHSType,
11574                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
11575       }
11576       return computeResultTy();
11577     }
11578     if (LHSType->isObjCObjectPointerType() &&
11579         RHSType->isObjCObjectPointerType()) {
11580       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
11581         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
11582                                           /*isError*/false);
11583       if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
11584         diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
11585 
11586       if (LHSIsNull && !RHSIsNull)
11587         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
11588       else
11589         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
11590       return computeResultTy();
11591     }
11592 
11593     if (!IsOrdered && LHSType->isBlockPointerType() &&
11594         RHSType->isBlockCompatibleObjCPointerType(Context)) {
11595       LHS = ImpCastExprToType(LHS.get(), RHSType,
11596                               CK_BlockPointerToObjCPointerCast);
11597       return computeResultTy();
11598     } else if (!IsOrdered &&
11599                LHSType->isBlockCompatibleObjCPointerType(Context) &&
11600                RHSType->isBlockPointerType()) {
11601       RHS = ImpCastExprToType(RHS.get(), LHSType,
11602                               CK_BlockPointerToObjCPointerCast);
11603       return computeResultTy();
11604     }
11605   }
11606   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
11607       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
11608     unsigned DiagID = 0;
11609     bool isError = false;
11610     if (LangOpts.DebuggerSupport) {
11611       // Under a debugger, allow the comparison of pointers to integers,
11612       // since users tend to want to compare addresses.
11613     } else if ((LHSIsNull && LHSType->isIntegerType()) ||
11614                (RHSIsNull && RHSType->isIntegerType())) {
11615       if (IsOrdered) {
11616         isError = getLangOpts().CPlusPlus;
11617         DiagID =
11618           isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
11619                   : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
11620       }
11621     } else if (getLangOpts().CPlusPlus) {
11622       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
11623       isError = true;
11624     } else if (IsOrdered)
11625       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
11626     else
11627       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
11628 
11629     if (DiagID) {
11630       Diag(Loc, DiagID)
11631         << LHSType << RHSType << LHS.get()->getSourceRange()
11632         << RHS.get()->getSourceRange();
11633       if (isError)
11634         return QualType();
11635     }
11636 
11637     if (LHSType->isIntegerType())
11638       LHS = ImpCastExprToType(LHS.get(), RHSType,
11639                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
11640     else
11641       RHS = ImpCastExprToType(RHS.get(), LHSType,
11642                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
11643     return computeResultTy();
11644   }
11645 
11646   // Handle block pointers.
11647   if (!IsOrdered && RHSIsNull
11648       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
11649     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11650     return computeResultTy();
11651   }
11652   if (!IsOrdered && LHSIsNull
11653       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
11654     LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11655     return computeResultTy();
11656   }
11657 
11658   if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) {
11659     if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
11660       return computeResultTy();
11661     }
11662 
11663     if (LHSType->isQueueT() && RHSType->isQueueT()) {
11664       return computeResultTy();
11665     }
11666 
11667     if (LHSIsNull && RHSType->isQueueT()) {
11668       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11669       return computeResultTy();
11670     }
11671 
11672     if (LHSType->isQueueT() && RHSIsNull) {
11673       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11674       return computeResultTy();
11675     }
11676   }
11677 
11678   return InvalidOperands(Loc, LHS, RHS);
11679 }
11680 
11681 // Return a signed ext_vector_type that is of identical size and number of
11682 // elements. For floating point vectors, return an integer type of identical
11683 // size and number of elements. In the non ext_vector_type case, search from
11684 // the largest type to the smallest type to avoid cases where long long == long,
11685 // where long gets picked over long long.
11686 QualType Sema::GetSignedVectorType(QualType V) {
11687   const VectorType *VTy = V->castAs<VectorType>();
11688   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
11689 
11690   if (isa<ExtVectorType>(VTy)) {
11691     if (TypeSize == Context.getTypeSize(Context.CharTy))
11692       return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
11693     else if (TypeSize == Context.getTypeSize(Context.ShortTy))
11694       return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
11695     else if (TypeSize == Context.getTypeSize(Context.IntTy))
11696       return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
11697     else if (TypeSize == Context.getTypeSize(Context.LongTy))
11698       return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
11699     assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
11700            "Unhandled vector element size in vector compare");
11701     return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
11702   }
11703 
11704   if (TypeSize == Context.getTypeSize(Context.LongLongTy))
11705     return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
11706                                  VectorType::GenericVector);
11707   else if (TypeSize == Context.getTypeSize(Context.LongTy))
11708     return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
11709                                  VectorType::GenericVector);
11710   else if (TypeSize == Context.getTypeSize(Context.IntTy))
11711     return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
11712                                  VectorType::GenericVector);
11713   else if (TypeSize == Context.getTypeSize(Context.ShortTy))
11714     return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
11715                                  VectorType::GenericVector);
11716   assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
11717          "Unhandled vector element size in vector compare");
11718   return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
11719                                VectorType::GenericVector);
11720 }
11721 
11722 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
11723 /// operates on extended vector types.  Instead of producing an IntTy result,
11724 /// like a scalar comparison, a vector comparison produces a vector of integer
11725 /// types.
11726 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
11727                                           SourceLocation Loc,
11728                                           BinaryOperatorKind Opc) {
11729   if (Opc == BO_Cmp) {
11730     Diag(Loc, diag::err_three_way_vector_comparison);
11731     return QualType();
11732   }
11733 
11734   // Check to make sure we're operating on vectors of the same type and width,
11735   // Allowing one side to be a scalar of element type.
11736   QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
11737                               /*AllowBothBool*/true,
11738                               /*AllowBoolConversions*/getLangOpts().ZVector);
11739   if (vType.isNull())
11740     return vType;
11741 
11742   QualType LHSType = LHS.get()->getType();
11743 
11744   // If AltiVec, the comparison results in a numeric type, i.e.
11745   // bool for C++, int for C
11746   if (getLangOpts().AltiVec &&
11747       vType->castAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
11748     return Context.getLogicalOperationType();
11749 
11750   // For non-floating point types, check for self-comparisons of the form
11751   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
11752   // often indicate logic errors in the program.
11753   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
11754 
11755   // Check for comparisons of floating point operands using != and ==.
11756   if (BinaryOperator::isEqualityOp(Opc) &&
11757       LHSType->hasFloatingRepresentation()) {
11758     assert(RHS.get()->getType()->hasFloatingRepresentation());
11759     CheckFloatComparison(Loc, LHS.get(), RHS.get());
11760   }
11761 
11762   // Return a signed type for the vector.
11763   return GetSignedVectorType(vType);
11764 }
11765 
11766 static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS,
11767                                     const ExprResult &XorRHS,
11768                                     const SourceLocation Loc) {
11769   // Do not diagnose macros.
11770   if (Loc.isMacroID())
11771     return;
11772 
11773   bool Negative = false;
11774   bool ExplicitPlus = false;
11775   const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get());
11776   const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get());
11777 
11778   if (!LHSInt)
11779     return;
11780   if (!RHSInt) {
11781     // Check negative literals.
11782     if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) {
11783       UnaryOperatorKind Opc = UO->getOpcode();
11784       if (Opc != UO_Minus && Opc != UO_Plus)
11785         return;
11786       RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr());
11787       if (!RHSInt)
11788         return;
11789       Negative = (Opc == UO_Minus);
11790       ExplicitPlus = !Negative;
11791     } else {
11792       return;
11793     }
11794   }
11795 
11796   const llvm::APInt &LeftSideValue = LHSInt->getValue();
11797   llvm::APInt RightSideValue = RHSInt->getValue();
11798   if (LeftSideValue != 2 && LeftSideValue != 10)
11799     return;
11800 
11801   if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth())
11802     return;
11803 
11804   CharSourceRange ExprRange = CharSourceRange::getCharRange(
11805       LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation()));
11806   llvm::StringRef ExprStr =
11807       Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts());
11808 
11809   CharSourceRange XorRange =
11810       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
11811   llvm::StringRef XorStr =
11812       Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts());
11813   // Do not diagnose if xor keyword/macro is used.
11814   if (XorStr == "xor")
11815     return;
11816 
11817   std::string LHSStr = std::string(Lexer::getSourceText(
11818       CharSourceRange::getTokenRange(LHSInt->getSourceRange()),
11819       S.getSourceManager(), S.getLangOpts()));
11820   std::string RHSStr = std::string(Lexer::getSourceText(
11821       CharSourceRange::getTokenRange(RHSInt->getSourceRange()),
11822       S.getSourceManager(), S.getLangOpts()));
11823 
11824   if (Negative) {
11825     RightSideValue = -RightSideValue;
11826     RHSStr = "-" + RHSStr;
11827   } else if (ExplicitPlus) {
11828     RHSStr = "+" + RHSStr;
11829   }
11830 
11831   StringRef LHSStrRef = LHSStr;
11832   StringRef RHSStrRef = RHSStr;
11833   // Do not diagnose literals with digit separators, binary, hexadecimal, octal
11834   // literals.
11835   if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") ||
11836       RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") ||
11837       LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") ||
11838       RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") ||
11839       (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) ||
11840       (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) ||
11841       LHSStrRef.find('\'') != StringRef::npos ||
11842       RHSStrRef.find('\'') != StringRef::npos)
11843     return;
11844 
11845   bool SuggestXor = S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor");
11846   const llvm::APInt XorValue = LeftSideValue ^ RightSideValue;
11847   int64_t RightSideIntValue = RightSideValue.getSExtValue();
11848   if (LeftSideValue == 2 && RightSideIntValue >= 0) {
11849     std::string SuggestedExpr = "1 << " + RHSStr;
11850     bool Overflow = false;
11851     llvm::APInt One = (LeftSideValue - 1);
11852     llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow);
11853     if (Overflow) {
11854       if (RightSideIntValue < 64)
11855         S.Diag(Loc, diag::warn_xor_used_as_pow_base)
11856             << ExprStr << XorValue.toString(10, true) << ("1LL << " + RHSStr)
11857             << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr);
11858       else if (RightSideIntValue == 64)
11859         S.Diag(Loc, diag::warn_xor_used_as_pow) << ExprStr << XorValue.toString(10, true);
11860       else
11861         return;
11862     } else {
11863       S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra)
11864           << ExprStr << XorValue.toString(10, true) << SuggestedExpr
11865           << PowValue.toString(10, true)
11866           << FixItHint::CreateReplacement(
11867                  ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr);
11868     }
11869 
11870     S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0x2 ^ " + RHSStr) << SuggestXor;
11871   } else if (LeftSideValue == 10) {
11872     std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue);
11873     S.Diag(Loc, diag::warn_xor_used_as_pow_base)
11874         << ExprStr << XorValue.toString(10, true) << SuggestedValue
11875         << FixItHint::CreateReplacement(ExprRange, SuggestedValue);
11876     S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0xA ^ " + RHSStr) << SuggestXor;
11877   }
11878 }
11879 
11880 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
11881                                           SourceLocation Loc) {
11882   // Ensure that either both operands are of the same vector type, or
11883   // one operand is of a vector type and the other is of its element type.
11884   QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
11885                                        /*AllowBothBool*/true,
11886                                        /*AllowBoolConversions*/false);
11887   if (vType.isNull())
11888     return InvalidOperands(Loc, LHS, RHS);
11889   if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
11890       !getLangOpts().OpenCLCPlusPlus && vType->hasFloatingRepresentation())
11891     return InvalidOperands(Loc, LHS, RHS);
11892   // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
11893   //        usage of the logical operators && and || with vectors in C. This
11894   //        check could be notionally dropped.
11895   if (!getLangOpts().CPlusPlus &&
11896       !(isa<ExtVectorType>(vType->getAs<VectorType>())))
11897     return InvalidLogicalVectorOperands(Loc, LHS, RHS);
11898 
11899   return GetSignedVectorType(LHS.get()->getType());
11900 }
11901 
11902 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
11903                                            SourceLocation Loc,
11904                                            BinaryOperatorKind Opc) {
11905   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11906 
11907   bool IsCompAssign =
11908       Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
11909 
11910   if (LHS.get()->getType()->isVectorType() ||
11911       RHS.get()->getType()->isVectorType()) {
11912     if (LHS.get()->getType()->hasIntegerRepresentation() &&
11913         RHS.get()->getType()->hasIntegerRepresentation())
11914       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
11915                         /*AllowBothBool*/true,
11916                         /*AllowBoolConversions*/getLangOpts().ZVector);
11917     return InvalidOperands(Loc, LHS, RHS);
11918   }
11919 
11920   if (Opc == BO_And)
11921     diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
11922 
11923   if (LHS.get()->getType()->hasFloatingRepresentation() ||
11924       RHS.get()->getType()->hasFloatingRepresentation())
11925     return InvalidOperands(Loc, LHS, RHS);
11926 
11927   ExprResult LHSResult = LHS, RHSResult = RHS;
11928   QualType compType = UsualArithmeticConversions(
11929       LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp);
11930   if (LHSResult.isInvalid() || RHSResult.isInvalid())
11931     return QualType();
11932   LHS = LHSResult.get();
11933   RHS = RHSResult.get();
11934 
11935   if (Opc == BO_Xor)
11936     diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc);
11937 
11938   if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
11939     return compType;
11940   return InvalidOperands(Loc, LHS, RHS);
11941 }
11942 
11943 // C99 6.5.[13,14]
11944 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
11945                                            SourceLocation Loc,
11946                                            BinaryOperatorKind Opc) {
11947   // Check vector operands differently.
11948   if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
11949     return CheckVectorLogicalOperands(LHS, RHS, Loc);
11950 
11951   bool EnumConstantInBoolContext = false;
11952   for (const ExprResult &HS : {LHS, RHS}) {
11953     if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) {
11954       const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl());
11955       if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1)
11956         EnumConstantInBoolContext = true;
11957     }
11958   }
11959 
11960   if (EnumConstantInBoolContext)
11961     Diag(Loc, diag::warn_enum_constant_in_bool_context);
11962 
11963   // Diagnose cases where the user write a logical and/or but probably meant a
11964   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
11965   // is a constant.
11966   if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() &&
11967       !LHS.get()->getType()->isBooleanType() &&
11968       RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
11969       // Don't warn in macros or template instantiations.
11970       !Loc.isMacroID() && !inTemplateInstantiation()) {
11971     // If the RHS can be constant folded, and if it constant folds to something
11972     // that isn't 0 or 1 (which indicate a potential logical operation that
11973     // happened to fold to true/false) then warn.
11974     // Parens on the RHS are ignored.
11975     Expr::EvalResult EVResult;
11976     if (RHS.get()->EvaluateAsInt(EVResult, Context)) {
11977       llvm::APSInt Result = EVResult.Val.getInt();
11978       if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
11979            !RHS.get()->getExprLoc().isMacroID()) ||
11980           (Result != 0 && Result != 1)) {
11981         Diag(Loc, diag::warn_logical_instead_of_bitwise)
11982           << RHS.get()->getSourceRange()
11983           << (Opc == BO_LAnd ? "&&" : "||");
11984         // Suggest replacing the logical operator with the bitwise version
11985         Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
11986             << (Opc == BO_LAnd ? "&" : "|")
11987             << FixItHint::CreateReplacement(SourceRange(
11988                                                  Loc, getLocForEndOfToken(Loc)),
11989                                             Opc == BO_LAnd ? "&" : "|");
11990         if (Opc == BO_LAnd)
11991           // Suggest replacing "Foo() && kNonZero" with "Foo()"
11992           Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
11993               << FixItHint::CreateRemoval(
11994                      SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()),
11995                                  RHS.get()->getEndLoc()));
11996       }
11997     }
11998   }
11999 
12000   if (!Context.getLangOpts().CPlusPlus) {
12001     // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
12002     // not operate on the built-in scalar and vector float types.
12003     if (Context.getLangOpts().OpenCL &&
12004         Context.getLangOpts().OpenCLVersion < 120) {
12005       if (LHS.get()->getType()->isFloatingType() ||
12006           RHS.get()->getType()->isFloatingType())
12007         return InvalidOperands(Loc, LHS, RHS);
12008     }
12009 
12010     LHS = UsualUnaryConversions(LHS.get());
12011     if (LHS.isInvalid())
12012       return QualType();
12013 
12014     RHS = UsualUnaryConversions(RHS.get());
12015     if (RHS.isInvalid())
12016       return QualType();
12017 
12018     if (!LHS.get()->getType()->isScalarType() ||
12019         !RHS.get()->getType()->isScalarType())
12020       return InvalidOperands(Loc, LHS, RHS);
12021 
12022     return Context.IntTy;
12023   }
12024 
12025   // The following is safe because we only use this method for
12026   // non-overloadable operands.
12027 
12028   // C++ [expr.log.and]p1
12029   // C++ [expr.log.or]p1
12030   // The operands are both contextually converted to type bool.
12031   ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
12032   if (LHSRes.isInvalid())
12033     return InvalidOperands(Loc, LHS, RHS);
12034   LHS = LHSRes;
12035 
12036   ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
12037   if (RHSRes.isInvalid())
12038     return InvalidOperands(Loc, LHS, RHS);
12039   RHS = RHSRes;
12040 
12041   // C++ [expr.log.and]p2
12042   // C++ [expr.log.or]p2
12043   // The result is a bool.
12044   return Context.BoolTy;
12045 }
12046 
12047 static bool IsReadonlyMessage(Expr *E, Sema &S) {
12048   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
12049   if (!ME) return false;
12050   if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
12051   ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
12052       ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
12053   if (!Base) return false;
12054   return Base->getMethodDecl() != nullptr;
12055 }
12056 
12057 /// Is the given expression (which must be 'const') a reference to a
12058 /// variable which was originally non-const, but which has become
12059 /// 'const' due to being captured within a block?
12060 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
12061 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
12062   assert(E->isLValue() && E->getType().isConstQualified());
12063   E = E->IgnoreParens();
12064 
12065   // Must be a reference to a declaration from an enclosing scope.
12066   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
12067   if (!DRE) return NCCK_None;
12068   if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
12069 
12070   // The declaration must be a variable which is not declared 'const'.
12071   VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
12072   if (!var) return NCCK_None;
12073   if (var->getType().isConstQualified()) return NCCK_None;
12074   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
12075 
12076   // Decide whether the first capture was for a block or a lambda.
12077   DeclContext *DC = S.CurContext, *Prev = nullptr;
12078   // Decide whether the first capture was for a block or a lambda.
12079   while (DC) {
12080     // For init-capture, it is possible that the variable belongs to the
12081     // template pattern of the current context.
12082     if (auto *FD = dyn_cast<FunctionDecl>(DC))
12083       if (var->isInitCapture() &&
12084           FD->getTemplateInstantiationPattern() == var->getDeclContext())
12085         break;
12086     if (DC == var->getDeclContext())
12087       break;
12088     Prev = DC;
12089     DC = DC->getParent();
12090   }
12091   // Unless we have an init-capture, we've gone one step too far.
12092   if (!var->isInitCapture())
12093     DC = Prev;
12094   return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
12095 }
12096 
12097 static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
12098   Ty = Ty.getNonReferenceType();
12099   if (IsDereference && Ty->isPointerType())
12100     Ty = Ty->getPointeeType();
12101   return !Ty.isConstQualified();
12102 }
12103 
12104 // Update err_typecheck_assign_const and note_typecheck_assign_const
12105 // when this enum is changed.
12106 enum {
12107   ConstFunction,
12108   ConstVariable,
12109   ConstMember,
12110   ConstMethod,
12111   NestedConstMember,
12112   ConstUnknown,  // Keep as last element
12113 };
12114 
12115 /// Emit the "read-only variable not assignable" error and print notes to give
12116 /// more information about why the variable is not assignable, such as pointing
12117 /// to the declaration of a const variable, showing that a method is const, or
12118 /// that the function is returning a const reference.
12119 static void DiagnoseConstAssignment(Sema &S, const Expr *E,
12120                                     SourceLocation Loc) {
12121   SourceRange ExprRange = E->getSourceRange();
12122 
12123   // Only emit one error on the first const found.  All other consts will emit
12124   // a note to the error.
12125   bool DiagnosticEmitted = false;
12126 
12127   // Track if the current expression is the result of a dereference, and if the
12128   // next checked expression is the result of a dereference.
12129   bool IsDereference = false;
12130   bool NextIsDereference = false;
12131 
12132   // Loop to process MemberExpr chains.
12133   while (true) {
12134     IsDereference = NextIsDereference;
12135 
12136     E = E->IgnoreImplicit()->IgnoreParenImpCasts();
12137     if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
12138       NextIsDereference = ME->isArrow();
12139       const ValueDecl *VD = ME->getMemberDecl();
12140       if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
12141         // Mutable fields can be modified even if the class is const.
12142         if (Field->isMutable()) {
12143           assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
12144           break;
12145         }
12146 
12147         if (!IsTypeModifiable(Field->getType(), IsDereference)) {
12148           if (!DiagnosticEmitted) {
12149             S.Diag(Loc, diag::err_typecheck_assign_const)
12150                 << ExprRange << ConstMember << false /*static*/ << Field
12151                 << Field->getType();
12152             DiagnosticEmitted = true;
12153           }
12154           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
12155               << ConstMember << false /*static*/ << Field << Field->getType()
12156               << Field->getSourceRange();
12157         }
12158         E = ME->getBase();
12159         continue;
12160       } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
12161         if (VDecl->getType().isConstQualified()) {
12162           if (!DiagnosticEmitted) {
12163             S.Diag(Loc, diag::err_typecheck_assign_const)
12164                 << ExprRange << ConstMember << true /*static*/ << VDecl
12165                 << VDecl->getType();
12166             DiagnosticEmitted = true;
12167           }
12168           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
12169               << ConstMember << true /*static*/ << VDecl << VDecl->getType()
12170               << VDecl->getSourceRange();
12171         }
12172         // Static fields do not inherit constness from parents.
12173         break;
12174       }
12175       break; // End MemberExpr
12176     } else if (const ArraySubscriptExpr *ASE =
12177                    dyn_cast<ArraySubscriptExpr>(E)) {
12178       E = ASE->getBase()->IgnoreParenImpCasts();
12179       continue;
12180     } else if (const ExtVectorElementExpr *EVE =
12181                    dyn_cast<ExtVectorElementExpr>(E)) {
12182       E = EVE->getBase()->IgnoreParenImpCasts();
12183       continue;
12184     }
12185     break;
12186   }
12187 
12188   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
12189     // Function calls
12190     const FunctionDecl *FD = CE->getDirectCallee();
12191     if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
12192       if (!DiagnosticEmitted) {
12193         S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
12194                                                       << ConstFunction << FD;
12195         DiagnosticEmitted = true;
12196       }
12197       S.Diag(FD->getReturnTypeSourceRange().getBegin(),
12198              diag::note_typecheck_assign_const)
12199           << ConstFunction << FD << FD->getReturnType()
12200           << FD->getReturnTypeSourceRange();
12201     }
12202   } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
12203     // Point to variable declaration.
12204     if (const ValueDecl *VD = DRE->getDecl()) {
12205       if (!IsTypeModifiable(VD->getType(), IsDereference)) {
12206         if (!DiagnosticEmitted) {
12207           S.Diag(Loc, diag::err_typecheck_assign_const)
12208               << ExprRange << ConstVariable << VD << VD->getType();
12209           DiagnosticEmitted = true;
12210         }
12211         S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
12212             << ConstVariable << VD << VD->getType() << VD->getSourceRange();
12213       }
12214     }
12215   } else if (isa<CXXThisExpr>(E)) {
12216     if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
12217       if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
12218         if (MD->isConst()) {
12219           if (!DiagnosticEmitted) {
12220             S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
12221                                                           << ConstMethod << MD;
12222             DiagnosticEmitted = true;
12223           }
12224           S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
12225               << ConstMethod << MD << MD->getSourceRange();
12226         }
12227       }
12228     }
12229   }
12230 
12231   if (DiagnosticEmitted)
12232     return;
12233 
12234   // Can't determine a more specific message, so display the generic error.
12235   S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
12236 }
12237 
12238 enum OriginalExprKind {
12239   OEK_Variable,
12240   OEK_Member,
12241   OEK_LValue
12242 };
12243 
12244 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD,
12245                                          const RecordType *Ty,
12246                                          SourceLocation Loc, SourceRange Range,
12247                                          OriginalExprKind OEK,
12248                                          bool &DiagnosticEmitted) {
12249   std::vector<const RecordType *> RecordTypeList;
12250   RecordTypeList.push_back(Ty);
12251   unsigned NextToCheckIndex = 0;
12252   // We walk the record hierarchy breadth-first to ensure that we print
12253   // diagnostics in field nesting order.
12254   while (RecordTypeList.size() > NextToCheckIndex) {
12255     bool IsNested = NextToCheckIndex > 0;
12256     for (const FieldDecl *Field :
12257          RecordTypeList[NextToCheckIndex]->getDecl()->fields()) {
12258       // First, check every field for constness.
12259       QualType FieldTy = Field->getType();
12260       if (FieldTy.isConstQualified()) {
12261         if (!DiagnosticEmitted) {
12262           S.Diag(Loc, diag::err_typecheck_assign_const)
12263               << Range << NestedConstMember << OEK << VD
12264               << IsNested << Field;
12265           DiagnosticEmitted = true;
12266         }
12267         S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
12268             << NestedConstMember << IsNested << Field
12269             << FieldTy << Field->getSourceRange();
12270       }
12271 
12272       // Then we append it to the list to check next in order.
12273       FieldTy = FieldTy.getCanonicalType();
12274       if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) {
12275         if (llvm::find(RecordTypeList, FieldRecTy) == RecordTypeList.end())
12276           RecordTypeList.push_back(FieldRecTy);
12277       }
12278     }
12279     ++NextToCheckIndex;
12280   }
12281 }
12282 
12283 /// Emit an error for the case where a record we are trying to assign to has a
12284 /// const-qualified field somewhere in its hierarchy.
12285 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
12286                                          SourceLocation Loc) {
12287   QualType Ty = E->getType();
12288   assert(Ty->isRecordType() && "lvalue was not record?");
12289   SourceRange Range = E->getSourceRange();
12290   const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>();
12291   bool DiagEmitted = false;
12292 
12293   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
12294     DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
12295             Range, OEK_Member, DiagEmitted);
12296   else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
12297     DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
12298             Range, OEK_Variable, DiagEmitted);
12299   else
12300     DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
12301             Range, OEK_LValue, DiagEmitted);
12302   if (!DiagEmitted)
12303     DiagnoseConstAssignment(S, E, Loc);
12304 }
12305 
12306 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
12307 /// emit an error and return true.  If so, return false.
12308 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
12309   assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
12310 
12311   S.CheckShadowingDeclModification(E, Loc);
12312 
12313   SourceLocation OrigLoc = Loc;
12314   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
12315                                                               &Loc);
12316   if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
12317     IsLV = Expr::MLV_InvalidMessageExpression;
12318   if (IsLV == Expr::MLV_Valid)
12319     return false;
12320 
12321   unsigned DiagID = 0;
12322   bool NeedType = false;
12323   switch (IsLV) { // C99 6.5.16p2
12324   case Expr::MLV_ConstQualified:
12325     // Use a specialized diagnostic when we're assigning to an object
12326     // from an enclosing function or block.
12327     if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
12328       if (NCCK == NCCK_Block)
12329         DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
12330       else
12331         DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
12332       break;
12333     }
12334 
12335     // In ARC, use some specialized diagnostics for occasions where we
12336     // infer 'const'.  These are always pseudo-strong variables.
12337     if (S.getLangOpts().ObjCAutoRefCount) {
12338       DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
12339       if (declRef && isa<VarDecl>(declRef->getDecl())) {
12340         VarDecl *var = cast<VarDecl>(declRef->getDecl());
12341 
12342         // Use the normal diagnostic if it's pseudo-__strong but the
12343         // user actually wrote 'const'.
12344         if (var->isARCPseudoStrong() &&
12345             (!var->getTypeSourceInfo() ||
12346              !var->getTypeSourceInfo()->getType().isConstQualified())) {
12347           // There are three pseudo-strong cases:
12348           //  - self
12349           ObjCMethodDecl *method = S.getCurMethodDecl();
12350           if (method && var == method->getSelfDecl()) {
12351             DiagID = method->isClassMethod()
12352               ? diag::err_typecheck_arc_assign_self_class_method
12353               : diag::err_typecheck_arc_assign_self;
12354 
12355           //  - Objective-C externally_retained attribute.
12356           } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
12357                      isa<ParmVarDecl>(var)) {
12358             DiagID = diag::err_typecheck_arc_assign_externally_retained;
12359 
12360           //  - fast enumeration variables
12361           } else {
12362             DiagID = diag::err_typecheck_arr_assign_enumeration;
12363           }
12364 
12365           SourceRange Assign;
12366           if (Loc != OrigLoc)
12367             Assign = SourceRange(OrigLoc, OrigLoc);
12368           S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
12369           // We need to preserve the AST regardless, so migration tool
12370           // can do its job.
12371           return false;
12372         }
12373       }
12374     }
12375 
12376     // If none of the special cases above are triggered, then this is a
12377     // simple const assignment.
12378     if (DiagID == 0) {
12379       DiagnoseConstAssignment(S, E, Loc);
12380       return true;
12381     }
12382 
12383     break;
12384   case Expr::MLV_ConstAddrSpace:
12385     DiagnoseConstAssignment(S, E, Loc);
12386     return true;
12387   case Expr::MLV_ConstQualifiedField:
12388     DiagnoseRecursiveConstFields(S, E, Loc);
12389     return true;
12390   case Expr::MLV_ArrayType:
12391   case Expr::MLV_ArrayTemporary:
12392     DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
12393     NeedType = true;
12394     break;
12395   case Expr::MLV_NotObjectType:
12396     DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
12397     NeedType = true;
12398     break;
12399   case Expr::MLV_LValueCast:
12400     DiagID = diag::err_typecheck_lvalue_casts_not_supported;
12401     break;
12402   case Expr::MLV_Valid:
12403     llvm_unreachable("did not take early return for MLV_Valid");
12404   case Expr::MLV_InvalidExpression:
12405   case Expr::MLV_MemberFunction:
12406   case Expr::MLV_ClassTemporary:
12407     DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
12408     break;
12409   case Expr::MLV_IncompleteType:
12410   case Expr::MLV_IncompleteVoidType:
12411     return S.RequireCompleteType(Loc, E->getType(),
12412              diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
12413   case Expr::MLV_DuplicateVectorComponents:
12414     DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
12415     break;
12416   case Expr::MLV_NoSetterProperty:
12417     llvm_unreachable("readonly properties should be processed differently");
12418   case Expr::MLV_InvalidMessageExpression:
12419     DiagID = diag::err_readonly_message_assignment;
12420     break;
12421   case Expr::MLV_SubObjCPropertySetting:
12422     DiagID = diag::err_no_subobject_property_setting;
12423     break;
12424   }
12425 
12426   SourceRange Assign;
12427   if (Loc != OrigLoc)
12428     Assign = SourceRange(OrigLoc, OrigLoc);
12429   if (NeedType)
12430     S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
12431   else
12432     S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
12433   return true;
12434 }
12435 
12436 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
12437                                          SourceLocation Loc,
12438                                          Sema &Sema) {
12439   if (Sema.inTemplateInstantiation())
12440     return;
12441   if (Sema.isUnevaluatedContext())
12442     return;
12443   if (Loc.isInvalid() || Loc.isMacroID())
12444     return;
12445   if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
12446     return;
12447 
12448   // C / C++ fields
12449   MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
12450   MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
12451   if (ML && MR) {
12452     if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
12453       return;
12454     const ValueDecl *LHSDecl =
12455         cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl());
12456     const ValueDecl *RHSDecl =
12457         cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl());
12458     if (LHSDecl != RHSDecl)
12459       return;
12460     if (LHSDecl->getType().isVolatileQualified())
12461       return;
12462     if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
12463       if (RefTy->getPointeeType().isVolatileQualified())
12464         return;
12465 
12466     Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
12467   }
12468 
12469   // Objective-C instance variables
12470   ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
12471   ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
12472   if (OL && OR && OL->getDecl() == OR->getDecl()) {
12473     DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
12474     DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
12475     if (RL && RR && RL->getDecl() == RR->getDecl())
12476       Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
12477   }
12478 }
12479 
12480 // C99 6.5.16.1
12481 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
12482                                        SourceLocation Loc,
12483                                        QualType CompoundType) {
12484   assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
12485 
12486   // Verify that LHS is a modifiable lvalue, and emit error if not.
12487   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
12488     return QualType();
12489 
12490   QualType LHSType = LHSExpr->getType();
12491   QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
12492                                              CompoundType;
12493   // OpenCL v1.2 s6.1.1.1 p2:
12494   // The half data type can only be used to declare a pointer to a buffer that
12495   // contains half values
12496   if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
12497     LHSType->isHalfType()) {
12498     Diag(Loc, diag::err_opencl_half_load_store) << 1
12499         << LHSType.getUnqualifiedType();
12500     return QualType();
12501   }
12502 
12503   AssignConvertType ConvTy;
12504   if (CompoundType.isNull()) {
12505     Expr *RHSCheck = RHS.get();
12506 
12507     CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
12508 
12509     QualType LHSTy(LHSType);
12510     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
12511     if (RHS.isInvalid())
12512       return QualType();
12513     // Special case of NSObject attributes on c-style pointer types.
12514     if (ConvTy == IncompatiblePointer &&
12515         ((Context.isObjCNSObjectType(LHSType) &&
12516           RHSType->isObjCObjectPointerType()) ||
12517          (Context.isObjCNSObjectType(RHSType) &&
12518           LHSType->isObjCObjectPointerType())))
12519       ConvTy = Compatible;
12520 
12521     if (ConvTy == Compatible &&
12522         LHSType->isObjCObjectType())
12523         Diag(Loc, diag::err_objc_object_assignment)
12524           << LHSType;
12525 
12526     // If the RHS is a unary plus or minus, check to see if they = and + are
12527     // right next to each other.  If so, the user may have typo'd "x =+ 4"
12528     // instead of "x += 4".
12529     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
12530       RHSCheck = ICE->getSubExpr();
12531     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
12532       if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
12533           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
12534           // Only if the two operators are exactly adjacent.
12535           Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
12536           // And there is a space or other character before the subexpr of the
12537           // unary +/-.  We don't want to warn on "x=-1".
12538           Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() &&
12539           UO->getSubExpr()->getBeginLoc().isFileID()) {
12540         Diag(Loc, diag::warn_not_compound_assign)
12541           << (UO->getOpcode() == UO_Plus ? "+" : "-")
12542           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
12543       }
12544     }
12545 
12546     if (ConvTy == Compatible) {
12547       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
12548         // Warn about retain cycles where a block captures the LHS, but
12549         // not if the LHS is a simple variable into which the block is
12550         // being stored...unless that variable can be captured by reference!
12551         const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
12552         const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
12553         if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
12554           checkRetainCycles(LHSExpr, RHS.get());
12555       }
12556 
12557       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
12558           LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
12559         // It is safe to assign a weak reference into a strong variable.
12560         // Although this code can still have problems:
12561         //   id x = self.weakProp;
12562         //   id y = self.weakProp;
12563         // we do not warn to warn spuriously when 'x' and 'y' are on separate
12564         // paths through the function. This should be revisited if
12565         // -Wrepeated-use-of-weak is made flow-sensitive.
12566         // For ObjCWeak only, we do not warn if the assign is to a non-weak
12567         // variable, which will be valid for the current autorelease scope.
12568         if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
12569                              RHS.get()->getBeginLoc()))
12570           getCurFunction()->markSafeWeakUse(RHS.get());
12571 
12572       } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
12573         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
12574       }
12575     }
12576   } else {
12577     // Compound assignment "x += y"
12578     ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
12579   }
12580 
12581   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
12582                                RHS.get(), AA_Assigning))
12583     return QualType();
12584 
12585   CheckForNullPointerDereference(*this, LHSExpr);
12586 
12587   if (getLangOpts().CPlusPlus2a && LHSType.isVolatileQualified()) {
12588     if (CompoundType.isNull()) {
12589       // C++2a [expr.ass]p5:
12590       //   A simple-assignment whose left operand is of a volatile-qualified
12591       //   type is deprecated unless the assignment is either a discarded-value
12592       //   expression or an unevaluated operand
12593       ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr);
12594     } else {
12595       // C++2a [expr.ass]p6:
12596       //   [Compound-assignment] expressions are deprecated if E1 has
12597       //   volatile-qualified type
12598       Diag(Loc, diag::warn_deprecated_compound_assign_volatile) << LHSType;
12599     }
12600   }
12601 
12602   // C99 6.5.16p3: The type of an assignment expression is the type of the
12603   // left operand unless the left operand has qualified type, in which case
12604   // it is the unqualified version of the type of the left operand.
12605   // C99 6.5.16.1p2: In simple assignment, the value of the right operand
12606   // is converted to the type of the assignment expression (above).
12607   // C++ 5.17p1: the type of the assignment expression is that of its left
12608   // operand.
12609   return (getLangOpts().CPlusPlus
12610           ? LHSType : LHSType.getUnqualifiedType());
12611 }
12612 
12613 // Only ignore explicit casts to void.
12614 static bool IgnoreCommaOperand(const Expr *E) {
12615   E = E->IgnoreParens();
12616 
12617   if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
12618     if (CE->getCastKind() == CK_ToVoid) {
12619       return true;
12620     }
12621 
12622     // static_cast<void> on a dependent type will not show up as CK_ToVoid.
12623     if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
12624         CE->getSubExpr()->getType()->isDependentType()) {
12625       return true;
12626     }
12627   }
12628 
12629   return false;
12630 }
12631 
12632 // Look for instances where it is likely the comma operator is confused with
12633 // another operator.  There is a whitelist of acceptable expressions for the
12634 // left hand side of the comma operator, otherwise emit a warning.
12635 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
12636   // No warnings in macros
12637   if (Loc.isMacroID())
12638     return;
12639 
12640   // Don't warn in template instantiations.
12641   if (inTemplateInstantiation())
12642     return;
12643 
12644   // Scope isn't fine-grained enough to whitelist the specific cases, so
12645   // instead, skip more than needed, then call back into here with the
12646   // CommaVisitor in SemaStmt.cpp.
12647   // The whitelisted locations are the initialization and increment portions
12648   // of a for loop.  The additional checks are on the condition of
12649   // if statements, do/while loops, and for loops.
12650   // Differences in scope flags for C89 mode requires the extra logic.
12651   const unsigned ForIncrementFlags =
12652       getLangOpts().C99 || getLangOpts().CPlusPlus
12653           ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope
12654           : Scope::ContinueScope | Scope::BreakScope;
12655   const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
12656   const unsigned ScopeFlags = getCurScope()->getFlags();
12657   if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
12658       (ScopeFlags & ForInitFlags) == ForInitFlags)
12659     return;
12660 
12661   // If there are multiple comma operators used together, get the RHS of the
12662   // of the comma operator as the LHS.
12663   while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
12664     if (BO->getOpcode() != BO_Comma)
12665       break;
12666     LHS = BO->getRHS();
12667   }
12668 
12669   // Only allow some expressions on LHS to not warn.
12670   if (IgnoreCommaOperand(LHS))
12671     return;
12672 
12673   Diag(Loc, diag::warn_comma_operator);
12674   Diag(LHS->getBeginLoc(), diag::note_cast_to_void)
12675       << LHS->getSourceRange()
12676       << FixItHint::CreateInsertion(LHS->getBeginLoc(),
12677                                     LangOpts.CPlusPlus ? "static_cast<void>("
12678                                                        : "(void)(")
12679       << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()),
12680                                     ")");
12681 }
12682 
12683 // C99 6.5.17
12684 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
12685                                    SourceLocation Loc) {
12686   LHS = S.CheckPlaceholderExpr(LHS.get());
12687   RHS = S.CheckPlaceholderExpr(RHS.get());
12688   if (LHS.isInvalid() || RHS.isInvalid())
12689     return QualType();
12690 
12691   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
12692   // operands, but not unary promotions.
12693   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
12694 
12695   // So we treat the LHS as a ignored value, and in C++ we allow the
12696   // containing site to determine what should be done with the RHS.
12697   LHS = S.IgnoredValueConversions(LHS.get());
12698   if (LHS.isInvalid())
12699     return QualType();
12700 
12701   S.DiagnoseUnusedExprResult(LHS.get());
12702 
12703   if (!S.getLangOpts().CPlusPlus) {
12704     RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
12705     if (RHS.isInvalid())
12706       return QualType();
12707     if (!RHS.get()->getType()->isVoidType())
12708       S.RequireCompleteType(Loc, RHS.get()->getType(),
12709                             diag::err_incomplete_type);
12710   }
12711 
12712   if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
12713     S.DiagnoseCommaOperator(LHS.get(), Loc);
12714 
12715   return RHS.get()->getType();
12716 }
12717 
12718 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
12719 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
12720 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
12721                                                ExprValueKind &VK,
12722                                                ExprObjectKind &OK,
12723                                                SourceLocation OpLoc,
12724                                                bool IsInc, bool IsPrefix) {
12725   if (Op->isTypeDependent())
12726     return S.Context.DependentTy;
12727 
12728   QualType ResType = Op->getType();
12729   // Atomic types can be used for increment / decrement where the non-atomic
12730   // versions can, so ignore the _Atomic() specifier for the purpose of
12731   // checking.
12732   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
12733     ResType = ResAtomicType->getValueType();
12734 
12735   assert(!ResType.isNull() && "no type for increment/decrement expression");
12736 
12737   if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
12738     // Decrement of bool is not allowed.
12739     if (!IsInc) {
12740       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
12741       return QualType();
12742     }
12743     // Increment of bool sets it to true, but is deprecated.
12744     S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
12745                                               : diag::warn_increment_bool)
12746       << Op->getSourceRange();
12747   } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
12748     // Error on enum increments and decrements in C++ mode
12749     S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
12750     return QualType();
12751   } else if (ResType->isRealType()) {
12752     // OK!
12753   } else if (ResType->isPointerType()) {
12754     // C99 6.5.2.4p2, 6.5.6p2
12755     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
12756       return QualType();
12757   } else if (ResType->isObjCObjectPointerType()) {
12758     // On modern runtimes, ObjC pointer arithmetic is forbidden.
12759     // Otherwise, we just need a complete type.
12760     if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
12761         checkArithmeticOnObjCPointer(S, OpLoc, Op))
12762       return QualType();
12763   } else if (ResType->isAnyComplexType()) {
12764     // C99 does not support ++/-- on complex types, we allow as an extension.
12765     S.Diag(OpLoc, diag::ext_integer_increment_complex)
12766       << ResType << Op->getSourceRange();
12767   } else if (ResType->isPlaceholderType()) {
12768     ExprResult PR = S.CheckPlaceholderExpr(Op);
12769     if (PR.isInvalid()) return QualType();
12770     return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
12771                                           IsInc, IsPrefix);
12772   } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
12773     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
12774   } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
12775              (ResType->castAs<VectorType>()->getVectorKind() !=
12776               VectorType::AltiVecBool)) {
12777     // The z vector extensions allow ++ and -- for non-bool vectors.
12778   } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
12779             ResType->castAs<VectorType>()->getElementType()->isIntegerType()) {
12780     // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
12781   } else {
12782     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
12783       << ResType << int(IsInc) << Op->getSourceRange();
12784     return QualType();
12785   }
12786   // At this point, we know we have a real, complex or pointer type.
12787   // Now make sure the operand is a modifiable lvalue.
12788   if (CheckForModifiableLvalue(Op, OpLoc, S))
12789     return QualType();
12790   if (S.getLangOpts().CPlusPlus2a && ResType.isVolatileQualified()) {
12791     // C++2a [expr.pre.inc]p1, [expr.post.inc]p1:
12792     //   An operand with volatile-qualified type is deprecated
12793     S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile)
12794         << IsInc << ResType;
12795   }
12796   // In C++, a prefix increment is the same type as the operand. Otherwise
12797   // (in C or with postfix), the increment is the unqualified type of the
12798   // operand.
12799   if (IsPrefix && S.getLangOpts().CPlusPlus) {
12800     VK = VK_LValue;
12801     OK = Op->getObjectKind();
12802     return ResType;
12803   } else {
12804     VK = VK_RValue;
12805     return ResType.getUnqualifiedType();
12806   }
12807 }
12808 
12809 
12810 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
12811 /// This routine allows us to typecheck complex/recursive expressions
12812 /// where the declaration is needed for type checking. We only need to
12813 /// handle cases when the expression references a function designator
12814 /// or is an lvalue. Here are some examples:
12815 ///  - &(x) => x
12816 ///  - &*****f => f for f a function designator.
12817 ///  - &s.xx => s
12818 ///  - &s.zz[1].yy -> s, if zz is an array
12819 ///  - *(x + 1) -> x, if x is an array
12820 ///  - &"123"[2] -> 0
12821 ///  - & __real__ x -> x
12822 ///
12823 /// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to
12824 /// members.
12825 static ValueDecl *getPrimaryDecl(Expr *E) {
12826   switch (E->getStmtClass()) {
12827   case Stmt::DeclRefExprClass:
12828     return cast<DeclRefExpr>(E)->getDecl();
12829   case Stmt::MemberExprClass:
12830     // If this is an arrow operator, the address is an offset from
12831     // the base's value, so the object the base refers to is
12832     // irrelevant.
12833     if (cast<MemberExpr>(E)->isArrow())
12834       return nullptr;
12835     // Otherwise, the expression refers to a part of the base
12836     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
12837   case Stmt::ArraySubscriptExprClass: {
12838     // FIXME: This code shouldn't be necessary!  We should catch the implicit
12839     // promotion of register arrays earlier.
12840     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
12841     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
12842       if (ICE->getSubExpr()->getType()->isArrayType())
12843         return getPrimaryDecl(ICE->getSubExpr());
12844     }
12845     return nullptr;
12846   }
12847   case Stmt::UnaryOperatorClass: {
12848     UnaryOperator *UO = cast<UnaryOperator>(E);
12849 
12850     switch(UO->getOpcode()) {
12851     case UO_Real:
12852     case UO_Imag:
12853     case UO_Extension:
12854       return getPrimaryDecl(UO->getSubExpr());
12855     default:
12856       return nullptr;
12857     }
12858   }
12859   case Stmt::ParenExprClass:
12860     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
12861   case Stmt::ImplicitCastExprClass:
12862     // If the result of an implicit cast is an l-value, we care about
12863     // the sub-expression; otherwise, the result here doesn't matter.
12864     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
12865   case Stmt::CXXUuidofExprClass:
12866     return cast<CXXUuidofExpr>(E)->getGuidDecl();
12867   default:
12868     return nullptr;
12869   }
12870 }
12871 
12872 namespace {
12873   enum {
12874     AO_Bit_Field = 0,
12875     AO_Vector_Element = 1,
12876     AO_Property_Expansion = 2,
12877     AO_Register_Variable = 3,
12878     AO_No_Error = 4
12879   };
12880 }
12881 /// Diagnose invalid operand for address of operations.
12882 ///
12883 /// \param Type The type of operand which cannot have its address taken.
12884 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
12885                                          Expr *E, unsigned Type) {
12886   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
12887 }
12888 
12889 /// CheckAddressOfOperand - The operand of & must be either a function
12890 /// designator or an lvalue designating an object. If it is an lvalue, the
12891 /// object cannot be declared with storage class register or be a bit field.
12892 /// Note: The usual conversions are *not* applied to the operand of the &
12893 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
12894 /// In C++, the operand might be an overloaded function name, in which case
12895 /// we allow the '&' but retain the overloaded-function type.
12896 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
12897   if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
12898     if (PTy->getKind() == BuiltinType::Overload) {
12899       Expr *E = OrigOp.get()->IgnoreParens();
12900       if (!isa<OverloadExpr>(E)) {
12901         assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
12902         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
12903           << OrigOp.get()->getSourceRange();
12904         return QualType();
12905       }
12906 
12907       OverloadExpr *Ovl = cast<OverloadExpr>(E);
12908       if (isa<UnresolvedMemberExpr>(Ovl))
12909         if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
12910           Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
12911             << OrigOp.get()->getSourceRange();
12912           return QualType();
12913         }
12914 
12915       return Context.OverloadTy;
12916     }
12917 
12918     if (PTy->getKind() == BuiltinType::UnknownAny)
12919       return Context.UnknownAnyTy;
12920 
12921     if (PTy->getKind() == BuiltinType::BoundMember) {
12922       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
12923         << OrigOp.get()->getSourceRange();
12924       return QualType();
12925     }
12926 
12927     OrigOp = CheckPlaceholderExpr(OrigOp.get());
12928     if (OrigOp.isInvalid()) return QualType();
12929   }
12930 
12931   if (OrigOp.get()->isTypeDependent())
12932     return Context.DependentTy;
12933 
12934   assert(!OrigOp.get()->getType()->isPlaceholderType());
12935 
12936   // Make sure to ignore parentheses in subsequent checks
12937   Expr *op = OrigOp.get()->IgnoreParens();
12938 
12939   // In OpenCL captures for blocks called as lambda functions
12940   // are located in the private address space. Blocks used in
12941   // enqueue_kernel can be located in a different address space
12942   // depending on a vendor implementation. Thus preventing
12943   // taking an address of the capture to avoid invalid AS casts.
12944   if (LangOpts.OpenCL) {
12945     auto* VarRef = dyn_cast<DeclRefExpr>(op);
12946     if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
12947       Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
12948       return QualType();
12949     }
12950   }
12951 
12952   if (getLangOpts().C99) {
12953     // Implement C99-only parts of addressof rules.
12954     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
12955       if (uOp->getOpcode() == UO_Deref)
12956         // Per C99 6.5.3.2, the address of a deref always returns a valid result
12957         // (assuming the deref expression is valid).
12958         return uOp->getSubExpr()->getType();
12959     }
12960     // Technically, there should be a check for array subscript
12961     // expressions here, but the result of one is always an lvalue anyway.
12962   }
12963   ValueDecl *dcl = getPrimaryDecl(op);
12964 
12965   if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
12966     if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
12967                                            op->getBeginLoc()))
12968       return QualType();
12969 
12970   Expr::LValueClassification lval = op->ClassifyLValue(Context);
12971   unsigned AddressOfError = AO_No_Error;
12972 
12973   if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
12974     bool sfinae = (bool)isSFINAEContext();
12975     Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
12976                                   : diag::ext_typecheck_addrof_temporary)
12977       << op->getType() << op->getSourceRange();
12978     if (sfinae)
12979       return QualType();
12980     // Materialize the temporary as an lvalue so that we can take its address.
12981     OrigOp = op =
12982         CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
12983   } else if (isa<ObjCSelectorExpr>(op)) {
12984     return Context.getPointerType(op->getType());
12985   } else if (lval == Expr::LV_MemberFunction) {
12986     // If it's an instance method, make a member pointer.
12987     // The expression must have exactly the form &A::foo.
12988 
12989     // If the underlying expression isn't a decl ref, give up.
12990     if (!isa<DeclRefExpr>(op)) {
12991       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
12992         << OrigOp.get()->getSourceRange();
12993       return QualType();
12994     }
12995     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
12996     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
12997 
12998     // The id-expression was parenthesized.
12999     if (OrigOp.get() != DRE) {
13000       Diag(OpLoc, diag::err_parens_pointer_member_function)
13001         << OrigOp.get()->getSourceRange();
13002 
13003     // The method was named without a qualifier.
13004     } else if (!DRE->getQualifier()) {
13005       if (MD->getParent()->getName().empty())
13006         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
13007           << op->getSourceRange();
13008       else {
13009         SmallString<32> Str;
13010         StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
13011         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
13012           << op->getSourceRange()
13013           << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
13014       }
13015     }
13016 
13017     // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
13018     if (isa<CXXDestructorDecl>(MD))
13019       Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
13020 
13021     QualType MPTy = Context.getMemberPointerType(
13022         op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
13023     // Under the MS ABI, lock down the inheritance model now.
13024     if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13025       (void)isCompleteType(OpLoc, MPTy);
13026     return MPTy;
13027   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
13028     // C99 6.5.3.2p1
13029     // The operand must be either an l-value or a function designator
13030     if (!op->getType()->isFunctionType()) {
13031       // Use a special diagnostic for loads from property references.
13032       if (isa<PseudoObjectExpr>(op)) {
13033         AddressOfError = AO_Property_Expansion;
13034       } else {
13035         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
13036           << op->getType() << op->getSourceRange();
13037         return QualType();
13038       }
13039     }
13040   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
13041     // The operand cannot be a bit-field
13042     AddressOfError = AO_Bit_Field;
13043   } else if (op->getObjectKind() == OK_VectorComponent) {
13044     // The operand cannot be an element of a vector
13045     AddressOfError = AO_Vector_Element;
13046   } else if (dcl) { // C99 6.5.3.2p1
13047     // We have an lvalue with a decl. Make sure the decl is not declared
13048     // with the register storage-class specifier.
13049     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
13050       // in C++ it is not error to take address of a register
13051       // variable (c++03 7.1.1P3)
13052       if (vd->getStorageClass() == SC_Register &&
13053           !getLangOpts().CPlusPlus) {
13054         AddressOfError = AO_Register_Variable;
13055       }
13056     } else if (isa<MSPropertyDecl>(dcl)) {
13057       AddressOfError = AO_Property_Expansion;
13058     } else if (isa<FunctionTemplateDecl>(dcl)) {
13059       return Context.OverloadTy;
13060     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
13061       // Okay: we can take the address of a field.
13062       // Could be a pointer to member, though, if there is an explicit
13063       // scope qualifier for the class.
13064       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
13065         DeclContext *Ctx = dcl->getDeclContext();
13066         if (Ctx && Ctx->isRecord()) {
13067           if (dcl->getType()->isReferenceType()) {
13068             Diag(OpLoc,
13069                  diag::err_cannot_form_pointer_to_member_of_reference_type)
13070               << dcl->getDeclName() << dcl->getType();
13071             return QualType();
13072           }
13073 
13074           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
13075             Ctx = Ctx->getParent();
13076 
13077           QualType MPTy = Context.getMemberPointerType(
13078               op->getType(),
13079               Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
13080           // Under the MS ABI, lock down the inheritance model now.
13081           if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13082             (void)isCompleteType(OpLoc, MPTy);
13083           return MPTy;
13084         }
13085       }
13086     } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) &&
13087                !isa<BindingDecl>(dcl) && !isa<MSGuidDecl>(dcl))
13088       llvm_unreachable("Unknown/unexpected decl type");
13089   }
13090 
13091   if (AddressOfError != AO_No_Error) {
13092     diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
13093     return QualType();
13094   }
13095 
13096   if (lval == Expr::LV_IncompleteVoidType) {
13097     // Taking the address of a void variable is technically illegal, but we
13098     // allow it in cases which are otherwise valid.
13099     // Example: "extern void x; void* y = &x;".
13100     Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
13101   }
13102 
13103   // If the operand has type "type", the result has type "pointer to type".
13104   if (op->getType()->isObjCObjectType())
13105     return Context.getObjCObjectPointerType(op->getType());
13106 
13107   CheckAddressOfPackedMember(op);
13108 
13109   return Context.getPointerType(op->getType());
13110 }
13111 
13112 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
13113   const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
13114   if (!DRE)
13115     return;
13116   const Decl *D = DRE->getDecl();
13117   if (!D)
13118     return;
13119   const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
13120   if (!Param)
13121     return;
13122   if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
13123     if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
13124       return;
13125   if (FunctionScopeInfo *FD = S.getCurFunction())
13126     if (!FD->ModifiedNonNullParams.count(Param))
13127       FD->ModifiedNonNullParams.insert(Param);
13128 }
13129 
13130 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
13131 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
13132                                         SourceLocation OpLoc) {
13133   if (Op->isTypeDependent())
13134     return S.Context.DependentTy;
13135 
13136   ExprResult ConvResult = S.UsualUnaryConversions(Op);
13137   if (ConvResult.isInvalid())
13138     return QualType();
13139   Op = ConvResult.get();
13140   QualType OpTy = Op->getType();
13141   QualType Result;
13142 
13143   if (isa<CXXReinterpretCastExpr>(Op)) {
13144     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
13145     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
13146                                      Op->getSourceRange());
13147   }
13148 
13149   if (const PointerType *PT = OpTy->getAs<PointerType>())
13150   {
13151     Result = PT->getPointeeType();
13152   }
13153   else if (const ObjCObjectPointerType *OPT =
13154              OpTy->getAs<ObjCObjectPointerType>())
13155     Result = OPT->getPointeeType();
13156   else {
13157     ExprResult PR = S.CheckPlaceholderExpr(Op);
13158     if (PR.isInvalid()) return QualType();
13159     if (PR.get() != Op)
13160       return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
13161   }
13162 
13163   if (Result.isNull()) {
13164     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
13165       << OpTy << Op->getSourceRange();
13166     return QualType();
13167   }
13168 
13169   // Note that per both C89 and C99, indirection is always legal, even if Result
13170   // is an incomplete type or void.  It would be possible to warn about
13171   // dereferencing a void pointer, but it's completely well-defined, and such a
13172   // warning is unlikely to catch any mistakes. In C++, indirection is not valid
13173   // for pointers to 'void' but is fine for any other pointer type:
13174   //
13175   // C++ [expr.unary.op]p1:
13176   //   [...] the expression to which [the unary * operator] is applied shall
13177   //   be a pointer to an object type, or a pointer to a function type
13178   if (S.getLangOpts().CPlusPlus && Result->isVoidType())
13179     S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
13180       << OpTy << Op->getSourceRange();
13181 
13182   // Dereferences are usually l-values...
13183   VK = VK_LValue;
13184 
13185   // ...except that certain expressions are never l-values in C.
13186   if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
13187     VK = VK_RValue;
13188 
13189   return Result;
13190 }
13191 
13192 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
13193   BinaryOperatorKind Opc;
13194   switch (Kind) {
13195   default: llvm_unreachable("Unknown binop!");
13196   case tok::periodstar:           Opc = BO_PtrMemD; break;
13197   case tok::arrowstar:            Opc = BO_PtrMemI; break;
13198   case tok::star:                 Opc = BO_Mul; break;
13199   case tok::slash:                Opc = BO_Div; break;
13200   case tok::percent:              Opc = BO_Rem; break;
13201   case tok::plus:                 Opc = BO_Add; break;
13202   case tok::minus:                Opc = BO_Sub; break;
13203   case tok::lessless:             Opc = BO_Shl; break;
13204   case tok::greatergreater:       Opc = BO_Shr; break;
13205   case tok::lessequal:            Opc = BO_LE; break;
13206   case tok::less:                 Opc = BO_LT; break;
13207   case tok::greaterequal:         Opc = BO_GE; break;
13208   case tok::greater:              Opc = BO_GT; break;
13209   case tok::exclaimequal:         Opc = BO_NE; break;
13210   case tok::equalequal:           Opc = BO_EQ; break;
13211   case tok::spaceship:            Opc = BO_Cmp; break;
13212   case tok::amp:                  Opc = BO_And; break;
13213   case tok::caret:                Opc = BO_Xor; break;
13214   case tok::pipe:                 Opc = BO_Or; break;
13215   case tok::ampamp:               Opc = BO_LAnd; break;
13216   case tok::pipepipe:             Opc = BO_LOr; break;
13217   case tok::equal:                Opc = BO_Assign; break;
13218   case tok::starequal:            Opc = BO_MulAssign; break;
13219   case tok::slashequal:           Opc = BO_DivAssign; break;
13220   case tok::percentequal:         Opc = BO_RemAssign; break;
13221   case tok::plusequal:            Opc = BO_AddAssign; break;
13222   case tok::minusequal:           Opc = BO_SubAssign; break;
13223   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
13224   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
13225   case tok::ampequal:             Opc = BO_AndAssign; break;
13226   case tok::caretequal:           Opc = BO_XorAssign; break;
13227   case tok::pipeequal:            Opc = BO_OrAssign; break;
13228   case tok::comma:                Opc = BO_Comma; break;
13229   }
13230   return Opc;
13231 }
13232 
13233 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
13234   tok::TokenKind Kind) {
13235   UnaryOperatorKind Opc;
13236   switch (Kind) {
13237   default: llvm_unreachable("Unknown unary op!");
13238   case tok::plusplus:     Opc = UO_PreInc; break;
13239   case tok::minusminus:   Opc = UO_PreDec; break;
13240   case tok::amp:          Opc = UO_AddrOf; break;
13241   case tok::star:         Opc = UO_Deref; break;
13242   case tok::plus:         Opc = UO_Plus; break;
13243   case tok::minus:        Opc = UO_Minus; break;
13244   case tok::tilde:        Opc = UO_Not; break;
13245   case tok::exclaim:      Opc = UO_LNot; break;
13246   case tok::kw___real:    Opc = UO_Real; break;
13247   case tok::kw___imag:    Opc = UO_Imag; break;
13248   case tok::kw___extension__: Opc = UO_Extension; break;
13249   }
13250   return Opc;
13251 }
13252 
13253 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
13254 /// This warning suppressed in the event of macro expansions.
13255 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
13256                                    SourceLocation OpLoc, bool IsBuiltin) {
13257   if (S.inTemplateInstantiation())
13258     return;
13259   if (S.isUnevaluatedContext())
13260     return;
13261   if (OpLoc.isInvalid() || OpLoc.isMacroID())
13262     return;
13263   LHSExpr = LHSExpr->IgnoreParenImpCasts();
13264   RHSExpr = RHSExpr->IgnoreParenImpCasts();
13265   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
13266   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
13267   if (!LHSDeclRef || !RHSDeclRef ||
13268       LHSDeclRef->getLocation().isMacroID() ||
13269       RHSDeclRef->getLocation().isMacroID())
13270     return;
13271   const ValueDecl *LHSDecl =
13272     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
13273   const ValueDecl *RHSDecl =
13274     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
13275   if (LHSDecl != RHSDecl)
13276     return;
13277   if (LHSDecl->getType().isVolatileQualified())
13278     return;
13279   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
13280     if (RefTy->getPointeeType().isVolatileQualified())
13281       return;
13282 
13283   S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
13284                           : diag::warn_self_assignment_overloaded)
13285       << LHSDeclRef->getType() << LHSExpr->getSourceRange()
13286       << RHSExpr->getSourceRange();
13287 }
13288 
13289 /// Check if a bitwise-& is performed on an Objective-C pointer.  This
13290 /// is usually indicative of introspection within the Objective-C pointer.
13291 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
13292                                           SourceLocation OpLoc) {
13293   if (!S.getLangOpts().ObjC)
13294     return;
13295 
13296   const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
13297   const Expr *LHS = L.get();
13298   const Expr *RHS = R.get();
13299 
13300   if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
13301     ObjCPointerExpr = LHS;
13302     OtherExpr = RHS;
13303   }
13304   else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
13305     ObjCPointerExpr = RHS;
13306     OtherExpr = LHS;
13307   }
13308 
13309   // This warning is deliberately made very specific to reduce false
13310   // positives with logic that uses '&' for hashing.  This logic mainly
13311   // looks for code trying to introspect into tagged pointers, which
13312   // code should generally never do.
13313   if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
13314     unsigned Diag = diag::warn_objc_pointer_masking;
13315     // Determine if we are introspecting the result of performSelectorXXX.
13316     const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
13317     // Special case messages to -performSelector and friends, which
13318     // can return non-pointer values boxed in a pointer value.
13319     // Some clients may wish to silence warnings in this subcase.
13320     if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
13321       Selector S = ME->getSelector();
13322       StringRef SelArg0 = S.getNameForSlot(0);
13323       if (SelArg0.startswith("performSelector"))
13324         Diag = diag::warn_objc_pointer_masking_performSelector;
13325     }
13326 
13327     S.Diag(OpLoc, Diag)
13328       << ObjCPointerExpr->getSourceRange();
13329   }
13330 }
13331 
13332 static NamedDecl *getDeclFromExpr(Expr *E) {
13333   if (!E)
13334     return nullptr;
13335   if (auto *DRE = dyn_cast<DeclRefExpr>(E))
13336     return DRE->getDecl();
13337   if (auto *ME = dyn_cast<MemberExpr>(E))
13338     return ME->getMemberDecl();
13339   if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
13340     return IRE->getDecl();
13341   return nullptr;
13342 }
13343 
13344 // This helper function promotes a binary operator's operands (which are of a
13345 // half vector type) to a vector of floats and then truncates the result to
13346 // a vector of either half or short.
13347 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS,
13348                                       BinaryOperatorKind Opc, QualType ResultTy,
13349                                       ExprValueKind VK, ExprObjectKind OK,
13350                                       bool IsCompAssign, SourceLocation OpLoc,
13351                                       FPOptions FPFeatures) {
13352   auto &Context = S.getASTContext();
13353   assert((isVector(ResultTy, Context.HalfTy) ||
13354           isVector(ResultTy, Context.ShortTy)) &&
13355          "Result must be a vector of half or short");
13356   assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
13357          isVector(RHS.get()->getType(), Context.HalfTy) &&
13358          "both operands expected to be a half vector");
13359 
13360   RHS = convertVector(RHS.get(), Context.FloatTy, S);
13361   QualType BinOpResTy = RHS.get()->getType();
13362 
13363   // If Opc is a comparison, ResultType is a vector of shorts. In that case,
13364   // change BinOpResTy to a vector of ints.
13365   if (isVector(ResultTy, Context.ShortTy))
13366     BinOpResTy = S.GetSignedVectorType(BinOpResTy);
13367 
13368   if (IsCompAssign)
13369     return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc,
13370                                           ResultTy, VK, OK, OpLoc, FPFeatures,
13371                                           BinOpResTy, BinOpResTy);
13372 
13373   LHS = convertVector(LHS.get(), Context.FloatTy, S);
13374   auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc,
13375                                     BinOpResTy, VK, OK, OpLoc, FPFeatures);
13376   return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S);
13377 }
13378 
13379 static std::pair<ExprResult, ExprResult>
13380 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr,
13381                            Expr *RHSExpr) {
13382   ExprResult LHS = LHSExpr, RHS = RHSExpr;
13383   if (!S.getLangOpts().CPlusPlus) {
13384     // C cannot handle TypoExpr nodes on either side of a binop because it
13385     // doesn't handle dependent types properly, so make sure any TypoExprs have
13386     // been dealt with before checking the operands.
13387     LHS = S.CorrectDelayedTyposInExpr(LHS);
13388     RHS = S.CorrectDelayedTyposInExpr(RHS, [Opc, LHS](Expr *E) {
13389       if (Opc != BO_Assign)
13390         return ExprResult(E);
13391       // Avoid correcting the RHS to the same Expr as the LHS.
13392       Decl *D = getDeclFromExpr(E);
13393       return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
13394     });
13395   }
13396   return std::make_pair(LHS, RHS);
13397 }
13398 
13399 /// Returns true if conversion between vectors of halfs and vectors of floats
13400 /// is needed.
13401 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
13402                                      Expr *E0, Expr *E1 = nullptr) {
13403   if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType ||
13404       Ctx.getTargetInfo().useFP16ConversionIntrinsics())
13405     return false;
13406 
13407   auto HasVectorOfHalfType = [&Ctx](Expr *E) {
13408     QualType Ty = E->IgnoreImplicit()->getType();
13409 
13410     // Don't promote half precision neon vectors like float16x4_t in arm_neon.h
13411     // to vectors of floats. Although the element type of the vectors is __fp16,
13412     // the vectors shouldn't be treated as storage-only types. See the
13413     // discussion here: https://reviews.llvm.org/rG825235c140e7
13414     if (const VectorType *VT = Ty->getAs<VectorType>()) {
13415       if (VT->getVectorKind() == VectorType::NeonVector)
13416         return false;
13417       return VT->getElementType().getCanonicalType() == Ctx.HalfTy;
13418     }
13419     return false;
13420   };
13421 
13422   return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1));
13423 }
13424 
13425 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
13426 /// operator @p Opc at location @c TokLoc. This routine only supports
13427 /// built-in operations; ActOnBinOp handles overloaded operators.
13428 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
13429                                     BinaryOperatorKind Opc,
13430                                     Expr *LHSExpr, Expr *RHSExpr) {
13431   if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
13432     // The syntax only allows initializer lists on the RHS of assignment,
13433     // so we don't need to worry about accepting invalid code for
13434     // non-assignment operators.
13435     // C++11 5.17p9:
13436     //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
13437     //   of x = {} is x = T().
13438     InitializationKind Kind = InitializationKind::CreateDirectList(
13439         RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
13440     InitializedEntity Entity =
13441         InitializedEntity::InitializeTemporary(LHSExpr->getType());
13442     InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
13443     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
13444     if (Init.isInvalid())
13445       return Init;
13446     RHSExpr = Init.get();
13447   }
13448 
13449   ExprResult LHS = LHSExpr, RHS = RHSExpr;
13450   QualType ResultTy;     // Result type of the binary operator.
13451   // The following two variables are used for compound assignment operators
13452   QualType CompLHSTy;    // Type of LHS after promotions for computation
13453   QualType CompResultTy; // Type of computation result
13454   ExprValueKind VK = VK_RValue;
13455   ExprObjectKind OK = OK_Ordinary;
13456   bool ConvertHalfVec = false;
13457 
13458   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
13459   if (!LHS.isUsable() || !RHS.isUsable())
13460     return ExprError();
13461 
13462   if (getLangOpts().OpenCL) {
13463     QualType LHSTy = LHSExpr->getType();
13464     QualType RHSTy = RHSExpr->getType();
13465     // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
13466     // the ATOMIC_VAR_INIT macro.
13467     if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
13468       SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
13469       if (BO_Assign == Opc)
13470         Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
13471       else
13472         ResultTy = InvalidOperands(OpLoc, LHS, RHS);
13473       return ExprError();
13474     }
13475 
13476     // OpenCL special types - image, sampler, pipe, and blocks are to be used
13477     // only with a builtin functions and therefore should be disallowed here.
13478     if (LHSTy->isImageType() || RHSTy->isImageType() ||
13479         LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
13480         LHSTy->isPipeType() || RHSTy->isPipeType() ||
13481         LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
13482       ResultTy = InvalidOperands(OpLoc, LHS, RHS);
13483       return ExprError();
13484     }
13485   }
13486 
13487   // Diagnose operations on the unsupported types for OpenMP device compilation.
13488   if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) {
13489     if (Opc != BO_Assign && Opc != BO_Comma) {
13490       checkOpenMPDeviceExpr(LHSExpr);
13491       checkOpenMPDeviceExpr(RHSExpr);
13492     }
13493   }
13494 
13495   switch (Opc) {
13496   case BO_Assign:
13497     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
13498     if (getLangOpts().CPlusPlus &&
13499         LHS.get()->getObjectKind() != OK_ObjCProperty) {
13500       VK = LHS.get()->getValueKind();
13501       OK = LHS.get()->getObjectKind();
13502     }
13503     if (!ResultTy.isNull()) {
13504       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
13505       DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
13506 
13507       // Avoid copying a block to the heap if the block is assigned to a local
13508       // auto variable that is declared in the same scope as the block. This
13509       // optimization is unsafe if the local variable is declared in an outer
13510       // scope. For example:
13511       //
13512       // BlockTy b;
13513       // {
13514       //   b = ^{...};
13515       // }
13516       // // It is unsafe to invoke the block here if it wasn't copied to the
13517       // // heap.
13518       // b();
13519 
13520       if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens()))
13521         if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
13522           if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
13523             if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD))
13524               BE->getBlockDecl()->setCanAvoidCopyToHeap();
13525 
13526       if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion())
13527         checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(),
13528                               NTCUC_Assignment, NTCUK_Copy);
13529     }
13530     RecordModifiableNonNullParam(*this, LHS.get());
13531     break;
13532   case BO_PtrMemD:
13533   case BO_PtrMemI:
13534     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
13535                                             Opc == BO_PtrMemI);
13536     break;
13537   case BO_Mul:
13538   case BO_Div:
13539     ConvertHalfVec = true;
13540     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
13541                                            Opc == BO_Div);
13542     break;
13543   case BO_Rem:
13544     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
13545     break;
13546   case BO_Add:
13547     ConvertHalfVec = true;
13548     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
13549     break;
13550   case BO_Sub:
13551     ConvertHalfVec = true;
13552     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
13553     break;
13554   case BO_Shl:
13555   case BO_Shr:
13556     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
13557     break;
13558   case BO_LE:
13559   case BO_LT:
13560   case BO_GE:
13561   case BO_GT:
13562     ConvertHalfVec = true;
13563     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
13564     break;
13565   case BO_EQ:
13566   case BO_NE:
13567     ConvertHalfVec = true;
13568     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
13569     break;
13570   case BO_Cmp:
13571     ConvertHalfVec = true;
13572     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
13573     assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
13574     break;
13575   case BO_And:
13576     checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
13577     LLVM_FALLTHROUGH;
13578   case BO_Xor:
13579   case BO_Or:
13580     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
13581     break;
13582   case BO_LAnd:
13583   case BO_LOr:
13584     ConvertHalfVec = true;
13585     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
13586     break;
13587   case BO_MulAssign:
13588   case BO_DivAssign:
13589     ConvertHalfVec = true;
13590     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
13591                                                Opc == BO_DivAssign);
13592     CompLHSTy = CompResultTy;
13593     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13594       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13595     break;
13596   case BO_RemAssign:
13597     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
13598     CompLHSTy = CompResultTy;
13599     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13600       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13601     break;
13602   case BO_AddAssign:
13603     ConvertHalfVec = true;
13604     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
13605     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13606       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13607     break;
13608   case BO_SubAssign:
13609     ConvertHalfVec = true;
13610     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
13611     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13612       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13613     break;
13614   case BO_ShlAssign:
13615   case BO_ShrAssign:
13616     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
13617     CompLHSTy = CompResultTy;
13618     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13619       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13620     break;
13621   case BO_AndAssign:
13622   case BO_OrAssign: // fallthrough
13623     DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
13624     LLVM_FALLTHROUGH;
13625   case BO_XorAssign:
13626     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
13627     CompLHSTy = CompResultTy;
13628     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13629       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13630     break;
13631   case BO_Comma:
13632     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
13633     if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
13634       VK = RHS.get()->getValueKind();
13635       OK = RHS.get()->getObjectKind();
13636     }
13637     break;
13638   }
13639   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
13640     return ExprError();
13641 
13642   // The LHS is not converted to the result type for fixed-point compound
13643   // assignment as the common type is computed on demand. Reset the CompLHSTy
13644   // to the LHS type we would have gotten after unary conversions.
13645   if (!CompLHSTy.isNull() &&
13646       (LHS.get()->getType()->isFixedPointType() ||
13647        RHS.get()->getType()->isFixedPointType()))
13648     CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType();
13649 
13650   if (ResultTy->isRealFloatingType() &&
13651       (getLangOpts().getFPRoundingMode() != RoundingMode::NearestTiesToEven ||
13652        getLangOpts().getFPExceptionMode() != LangOptions::FPE_Ignore))
13653     // Mark the current function as usng floating point constrained intrinsics
13654     if (FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
13655       F->setUsesFPIntrin(true);
13656     }
13657 
13658   // Some of the binary operations require promoting operands of half vector to
13659   // float vectors and truncating the result back to half vector. For now, we do
13660   // this only when HalfArgsAndReturn is set (that is, when the target is arm or
13661   // arm64).
13662   assert(isVector(RHS.get()->getType(), Context.HalfTy) ==
13663          isVector(LHS.get()->getType(), Context.HalfTy) &&
13664          "both sides are half vectors or neither sides are");
13665   ConvertHalfVec =
13666       needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get());
13667 
13668   // Check for array bounds violations for both sides of the BinaryOperator
13669   CheckArrayAccess(LHS.get());
13670   CheckArrayAccess(RHS.get());
13671 
13672   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
13673     NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
13674                                                  &Context.Idents.get("object_setClass"),
13675                                                  SourceLocation(), LookupOrdinaryName);
13676     if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
13677       SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc());
13678       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign)
13679           << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(),
13680                                         "object_setClass(")
13681           << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc),
13682                                           ",")
13683           << FixItHint::CreateInsertion(RHSLocEnd, ")");
13684     }
13685     else
13686       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
13687   }
13688   else if (const ObjCIvarRefExpr *OIRE =
13689            dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
13690     DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
13691 
13692   // Opc is not a compound assignment if CompResultTy is null.
13693   if (CompResultTy.isNull()) {
13694     if (ConvertHalfVec)
13695       return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
13696                                  OpLoc, FPFeatures);
13697     return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy,
13698                                   VK, OK, OpLoc, FPFeatures);
13699   }
13700 
13701   // Handle compound assignments.
13702   if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
13703       OK_ObjCProperty) {
13704     VK = VK_LValue;
13705     OK = LHS.get()->getObjectKind();
13706   }
13707 
13708   if (ConvertHalfVec)
13709     return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
13710                                OpLoc, FPFeatures);
13711 
13712   return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc,
13713                                         ResultTy, VK, OK, OpLoc, FPFeatures,
13714                                         CompLHSTy, CompResultTy);
13715 }
13716 
13717 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
13718 /// operators are mixed in a way that suggests that the programmer forgot that
13719 /// comparison operators have higher precedence. The most typical example of
13720 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
13721 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
13722                                       SourceLocation OpLoc, Expr *LHSExpr,
13723                                       Expr *RHSExpr) {
13724   BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
13725   BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
13726 
13727   // Check that one of the sides is a comparison operator and the other isn't.
13728   bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
13729   bool isRightComp = RHSBO && RHSBO->isComparisonOp();
13730   if (isLeftComp == isRightComp)
13731     return;
13732 
13733   // Bitwise operations are sometimes used as eager logical ops.
13734   // Don't diagnose this.
13735   bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
13736   bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
13737   if (isLeftBitwise || isRightBitwise)
13738     return;
13739 
13740   SourceRange DiagRange = isLeftComp
13741                               ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
13742                               : SourceRange(OpLoc, RHSExpr->getEndLoc());
13743   StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
13744   SourceRange ParensRange =
13745       isLeftComp
13746           ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
13747           : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
13748 
13749   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
13750     << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
13751   SuggestParentheses(Self, OpLoc,
13752     Self.PDiag(diag::note_precedence_silence) << OpStr,
13753     (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
13754   SuggestParentheses(Self, OpLoc,
13755     Self.PDiag(diag::note_precedence_bitwise_first)
13756       << BinaryOperator::getOpcodeStr(Opc),
13757     ParensRange);
13758 }
13759 
13760 /// It accepts a '&&' expr that is inside a '||' one.
13761 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
13762 /// in parentheses.
13763 static void
13764 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
13765                                        BinaryOperator *Bop) {
13766   assert(Bop->getOpcode() == BO_LAnd);
13767   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
13768       << Bop->getSourceRange() << OpLoc;
13769   SuggestParentheses(Self, Bop->getOperatorLoc(),
13770     Self.PDiag(diag::note_precedence_silence)
13771       << Bop->getOpcodeStr(),
13772     Bop->getSourceRange());
13773 }
13774 
13775 /// Returns true if the given expression can be evaluated as a constant
13776 /// 'true'.
13777 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
13778   bool Res;
13779   return !E->isValueDependent() &&
13780          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
13781 }
13782 
13783 /// Returns true if the given expression can be evaluated as a constant
13784 /// 'false'.
13785 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
13786   bool Res;
13787   return !E->isValueDependent() &&
13788          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
13789 }
13790 
13791 /// Look for '&&' in the left hand of a '||' expr.
13792 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
13793                                              Expr *LHSExpr, Expr *RHSExpr) {
13794   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
13795     if (Bop->getOpcode() == BO_LAnd) {
13796       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
13797       if (EvaluatesAsFalse(S, RHSExpr))
13798         return;
13799       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
13800       if (!EvaluatesAsTrue(S, Bop->getLHS()))
13801         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
13802     } else if (Bop->getOpcode() == BO_LOr) {
13803       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
13804         // If it's "a || b && 1 || c" we didn't warn earlier for
13805         // "a || b && 1", but warn now.
13806         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
13807           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
13808       }
13809     }
13810   }
13811 }
13812 
13813 /// Look for '&&' in the right hand of a '||' expr.
13814 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
13815                                              Expr *LHSExpr, Expr *RHSExpr) {
13816   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
13817     if (Bop->getOpcode() == BO_LAnd) {
13818       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
13819       if (EvaluatesAsFalse(S, LHSExpr))
13820         return;
13821       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
13822       if (!EvaluatesAsTrue(S, Bop->getRHS()))
13823         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
13824     }
13825   }
13826 }
13827 
13828 /// Look for bitwise op in the left or right hand of a bitwise op with
13829 /// lower precedence and emit a diagnostic together with a fixit hint that wraps
13830 /// the '&' expression in parentheses.
13831 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
13832                                          SourceLocation OpLoc, Expr *SubExpr) {
13833   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
13834     if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
13835       S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
13836         << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
13837         << Bop->getSourceRange() << OpLoc;
13838       SuggestParentheses(S, Bop->getOperatorLoc(),
13839         S.PDiag(diag::note_precedence_silence)
13840           << Bop->getOpcodeStr(),
13841         Bop->getSourceRange());
13842     }
13843   }
13844 }
13845 
13846 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
13847                                     Expr *SubExpr, StringRef Shift) {
13848   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
13849     if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
13850       StringRef Op = Bop->getOpcodeStr();
13851       S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
13852           << Bop->getSourceRange() << OpLoc << Shift << Op;
13853       SuggestParentheses(S, Bop->getOperatorLoc(),
13854           S.PDiag(diag::note_precedence_silence) << Op,
13855           Bop->getSourceRange());
13856     }
13857   }
13858 }
13859 
13860 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
13861                                  Expr *LHSExpr, Expr *RHSExpr) {
13862   CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
13863   if (!OCE)
13864     return;
13865 
13866   FunctionDecl *FD = OCE->getDirectCallee();
13867   if (!FD || !FD->isOverloadedOperator())
13868     return;
13869 
13870   OverloadedOperatorKind Kind = FD->getOverloadedOperator();
13871   if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
13872     return;
13873 
13874   S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
13875       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
13876       << (Kind == OO_LessLess);
13877   SuggestParentheses(S, OCE->getOperatorLoc(),
13878                      S.PDiag(diag::note_precedence_silence)
13879                          << (Kind == OO_LessLess ? "<<" : ">>"),
13880                      OCE->getSourceRange());
13881   SuggestParentheses(
13882       S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first),
13883       SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc()));
13884 }
13885 
13886 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
13887 /// precedence.
13888 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
13889                                     SourceLocation OpLoc, Expr *LHSExpr,
13890                                     Expr *RHSExpr){
13891   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
13892   if (BinaryOperator::isBitwiseOp(Opc))
13893     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
13894 
13895   // Diagnose "arg1 & arg2 | arg3"
13896   if ((Opc == BO_Or || Opc == BO_Xor) &&
13897       !OpLoc.isMacroID()/* Don't warn in macros. */) {
13898     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
13899     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
13900   }
13901 
13902   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
13903   // We don't warn for 'assert(a || b && "bad")' since this is safe.
13904   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
13905     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
13906     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
13907   }
13908 
13909   if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
13910       || Opc == BO_Shr) {
13911     StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
13912     DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
13913     DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
13914   }
13915 
13916   // Warn on overloaded shift operators and comparisons, such as:
13917   // cout << 5 == 4;
13918   if (BinaryOperator::isComparisonOp(Opc))
13919     DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
13920 }
13921 
13922 // Binary Operators.  'Tok' is the token for the operator.
13923 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
13924                             tok::TokenKind Kind,
13925                             Expr *LHSExpr, Expr *RHSExpr) {
13926   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
13927   assert(LHSExpr && "ActOnBinOp(): missing left expression");
13928   assert(RHSExpr && "ActOnBinOp(): missing right expression");
13929 
13930   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
13931   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
13932 
13933   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
13934 }
13935 
13936 /// Build an overloaded binary operator expression in the given scope.
13937 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
13938                                        BinaryOperatorKind Opc,
13939                                        Expr *LHS, Expr *RHS) {
13940   switch (Opc) {
13941   case BO_Assign:
13942   case BO_DivAssign:
13943   case BO_RemAssign:
13944   case BO_SubAssign:
13945   case BO_AndAssign:
13946   case BO_OrAssign:
13947   case BO_XorAssign:
13948     DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
13949     CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
13950     break;
13951   default:
13952     break;
13953   }
13954 
13955   // Find all of the overloaded operators visible from this
13956   // point. We perform both an operator-name lookup from the local
13957   // scope and an argument-dependent lookup based on the types of
13958   // the arguments.
13959   UnresolvedSet<16> Functions;
13960   OverloadedOperatorKind OverOp
13961     = BinaryOperator::getOverloadedOperator(Opc);
13962   if (Sc && OverOp != OO_None && OverOp != OO_Equal)
13963     S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
13964                                    RHS->getType(), Functions);
13965 
13966   // In C++20 onwards, we may have a second operator to look up.
13967   if (S.getLangOpts().CPlusPlus2a) {
13968     if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp))
13969       S.LookupOverloadedOperatorName(ExtraOp, Sc, LHS->getType(),
13970                                      RHS->getType(), Functions);
13971   }
13972 
13973   // Build the (potentially-overloaded, potentially-dependent)
13974   // binary operation.
13975   return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
13976 }
13977 
13978 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
13979                             BinaryOperatorKind Opc,
13980                             Expr *LHSExpr, Expr *RHSExpr) {
13981   ExprResult LHS, RHS;
13982   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
13983   if (!LHS.isUsable() || !RHS.isUsable())
13984     return ExprError();
13985   LHSExpr = LHS.get();
13986   RHSExpr = RHS.get();
13987 
13988   // We want to end up calling one of checkPseudoObjectAssignment
13989   // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
13990   // both expressions are overloadable or either is type-dependent),
13991   // or CreateBuiltinBinOp (in any other case).  We also want to get
13992   // any placeholder types out of the way.
13993 
13994   // Handle pseudo-objects in the LHS.
13995   if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
13996     // Assignments with a pseudo-object l-value need special analysis.
13997     if (pty->getKind() == BuiltinType::PseudoObject &&
13998         BinaryOperator::isAssignmentOp(Opc))
13999       return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
14000 
14001     // Don't resolve overloads if the other type is overloadable.
14002     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
14003       // We can't actually test that if we still have a placeholder,
14004       // though.  Fortunately, none of the exceptions we see in that
14005       // code below are valid when the LHS is an overload set.  Note
14006       // that an overload set can be dependently-typed, but it never
14007       // instantiates to having an overloadable type.
14008       ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
14009       if (resolvedRHS.isInvalid()) return ExprError();
14010       RHSExpr = resolvedRHS.get();
14011 
14012       if (RHSExpr->isTypeDependent() ||
14013           RHSExpr->getType()->isOverloadableType())
14014         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14015     }
14016 
14017     // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
14018     // template, diagnose the missing 'template' keyword instead of diagnosing
14019     // an invalid use of a bound member function.
14020     //
14021     // Note that "A::x < b" might be valid if 'b' has an overloadable type due
14022     // to C++1z [over.over]/1.4, but we already checked for that case above.
14023     if (Opc == BO_LT && inTemplateInstantiation() &&
14024         (pty->getKind() == BuiltinType::BoundMember ||
14025          pty->getKind() == BuiltinType::Overload)) {
14026       auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
14027       if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
14028           std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) {
14029             return isa<FunctionTemplateDecl>(ND);
14030           })) {
14031         Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
14032                                 : OE->getNameLoc(),
14033              diag::err_template_kw_missing)
14034           << OE->getName().getAsString() << "";
14035         return ExprError();
14036       }
14037     }
14038 
14039     ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
14040     if (LHS.isInvalid()) return ExprError();
14041     LHSExpr = LHS.get();
14042   }
14043 
14044   // Handle pseudo-objects in the RHS.
14045   if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
14046     // An overload in the RHS can potentially be resolved by the type
14047     // being assigned to.
14048     if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
14049       if (getLangOpts().CPlusPlus &&
14050           (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
14051            LHSExpr->getType()->isOverloadableType()))
14052         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14053 
14054       return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
14055     }
14056 
14057     // Don't resolve overloads if the other type is overloadable.
14058     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
14059         LHSExpr->getType()->isOverloadableType())
14060       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14061 
14062     ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
14063     if (!resolvedRHS.isUsable()) return ExprError();
14064     RHSExpr = resolvedRHS.get();
14065   }
14066 
14067   if (getLangOpts().CPlusPlus) {
14068     // If either expression is type-dependent, always build an
14069     // overloaded op.
14070     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
14071       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14072 
14073     // Otherwise, build an overloaded op if either expression has an
14074     // overloadable type.
14075     if (LHSExpr->getType()->isOverloadableType() ||
14076         RHSExpr->getType()->isOverloadableType())
14077       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14078   }
14079 
14080   // Build a built-in binary operation.
14081   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
14082 }
14083 
14084 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
14085   if (T.isNull() || T->isDependentType())
14086     return false;
14087 
14088   if (!T->isPromotableIntegerType())
14089     return true;
14090 
14091   return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
14092 }
14093 
14094 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
14095                                       UnaryOperatorKind Opc,
14096                                       Expr *InputExpr) {
14097   ExprResult Input = InputExpr;
14098   ExprValueKind VK = VK_RValue;
14099   ExprObjectKind OK = OK_Ordinary;
14100   QualType resultType;
14101   bool CanOverflow = false;
14102 
14103   bool ConvertHalfVec = false;
14104   if (getLangOpts().OpenCL) {
14105     QualType Ty = InputExpr->getType();
14106     // The only legal unary operation for atomics is '&'.
14107     if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
14108     // OpenCL special types - image, sampler, pipe, and blocks are to be used
14109     // only with a builtin functions and therefore should be disallowed here.
14110         (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
14111         || Ty->isBlockPointerType())) {
14112       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14113                        << InputExpr->getType()
14114                        << Input.get()->getSourceRange());
14115     }
14116   }
14117   // Diagnose operations on the unsupported types for OpenMP device compilation.
14118   if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) {
14119     if (UnaryOperator::isIncrementDecrementOp(Opc) ||
14120         UnaryOperator::isArithmeticOp(Opc))
14121       checkOpenMPDeviceExpr(InputExpr);
14122   }
14123 
14124   switch (Opc) {
14125   case UO_PreInc:
14126   case UO_PreDec:
14127   case UO_PostInc:
14128   case UO_PostDec:
14129     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
14130                                                 OpLoc,
14131                                                 Opc == UO_PreInc ||
14132                                                 Opc == UO_PostInc,
14133                                                 Opc == UO_PreInc ||
14134                                                 Opc == UO_PreDec);
14135     CanOverflow = isOverflowingIntegerType(Context, resultType);
14136     break;
14137   case UO_AddrOf:
14138     resultType = CheckAddressOfOperand(Input, OpLoc);
14139     CheckAddressOfNoDeref(InputExpr);
14140     RecordModifiableNonNullParam(*this, InputExpr);
14141     break;
14142   case UO_Deref: {
14143     Input = DefaultFunctionArrayLvalueConversion(Input.get());
14144     if (Input.isInvalid()) return ExprError();
14145     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
14146     break;
14147   }
14148   case UO_Plus:
14149   case UO_Minus:
14150     CanOverflow = Opc == UO_Minus &&
14151                   isOverflowingIntegerType(Context, Input.get()->getType());
14152     Input = UsualUnaryConversions(Input.get());
14153     if (Input.isInvalid()) return ExprError();
14154     // Unary plus and minus require promoting an operand of half vector to a
14155     // float vector and truncating the result back to a half vector. For now, we
14156     // do this only when HalfArgsAndReturns is set (that is, when the target is
14157     // arm or arm64).
14158     ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get());
14159 
14160     // If the operand is a half vector, promote it to a float vector.
14161     if (ConvertHalfVec)
14162       Input = convertVector(Input.get(), Context.FloatTy, *this);
14163     resultType = Input.get()->getType();
14164     if (resultType->isDependentType())
14165       break;
14166     if (resultType->isArithmeticType()) // C99 6.5.3.3p1
14167       break;
14168     else if (resultType->isVectorType() &&
14169              // The z vector extensions don't allow + or - with bool vectors.
14170              (!Context.getLangOpts().ZVector ||
14171               resultType->castAs<VectorType>()->getVectorKind() !=
14172               VectorType::AltiVecBool))
14173       break;
14174     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
14175              Opc == UO_Plus &&
14176              resultType->isPointerType())
14177       break;
14178 
14179     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14180       << resultType << Input.get()->getSourceRange());
14181 
14182   case UO_Not: // bitwise complement
14183     Input = UsualUnaryConversions(Input.get());
14184     if (Input.isInvalid())
14185       return ExprError();
14186     resultType = Input.get()->getType();
14187     if (resultType->isDependentType())
14188       break;
14189     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
14190     if (resultType->isComplexType() || resultType->isComplexIntegerType())
14191       // C99 does not support '~' for complex conjugation.
14192       Diag(OpLoc, diag::ext_integer_complement_complex)
14193           << resultType << Input.get()->getSourceRange();
14194     else if (resultType->hasIntegerRepresentation())
14195       break;
14196     else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
14197       // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
14198       // on vector float types.
14199       QualType T = resultType->castAs<ExtVectorType>()->getElementType();
14200       if (!T->isIntegerType())
14201         return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14202                           << resultType << Input.get()->getSourceRange());
14203     } else {
14204       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14205                        << resultType << Input.get()->getSourceRange());
14206     }
14207     break;
14208 
14209   case UO_LNot: // logical negation
14210     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
14211     Input = DefaultFunctionArrayLvalueConversion(Input.get());
14212     if (Input.isInvalid()) return ExprError();
14213     resultType = Input.get()->getType();
14214 
14215     // Though we still have to promote half FP to float...
14216     if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
14217       Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
14218       resultType = Context.FloatTy;
14219     }
14220 
14221     if (resultType->isDependentType())
14222       break;
14223     if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
14224       // C99 6.5.3.3p1: ok, fallthrough;
14225       if (Context.getLangOpts().CPlusPlus) {
14226         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
14227         // operand contextually converted to bool.
14228         Input = ImpCastExprToType(Input.get(), Context.BoolTy,
14229                                   ScalarTypeToBooleanCastKind(resultType));
14230       } else if (Context.getLangOpts().OpenCL &&
14231                  Context.getLangOpts().OpenCLVersion < 120) {
14232         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
14233         // operate on scalar float types.
14234         if (!resultType->isIntegerType() && !resultType->isPointerType())
14235           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14236                            << resultType << Input.get()->getSourceRange());
14237       }
14238     } else if (resultType->isExtVectorType()) {
14239       if (Context.getLangOpts().OpenCL &&
14240           Context.getLangOpts().OpenCLVersion < 120 &&
14241           !Context.getLangOpts().OpenCLCPlusPlus) {
14242         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
14243         // operate on vector float types.
14244         QualType T = resultType->castAs<ExtVectorType>()->getElementType();
14245         if (!T->isIntegerType())
14246           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14247                            << resultType << Input.get()->getSourceRange());
14248       }
14249       // Vector logical not returns the signed variant of the operand type.
14250       resultType = GetSignedVectorType(resultType);
14251       break;
14252     } else {
14253       // FIXME: GCC's vector extension permits the usage of '!' with a vector
14254       //        type in C++. We should allow that here too.
14255       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14256         << resultType << Input.get()->getSourceRange());
14257     }
14258 
14259     // LNot always has type int. C99 6.5.3.3p5.
14260     // In C++, it's bool. C++ 5.3.1p8
14261     resultType = Context.getLogicalOperationType();
14262     break;
14263   case UO_Real:
14264   case UO_Imag:
14265     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
14266     // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
14267     // complex l-values to ordinary l-values and all other values to r-values.
14268     if (Input.isInvalid()) return ExprError();
14269     if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
14270       if (Input.get()->getValueKind() != VK_RValue &&
14271           Input.get()->getObjectKind() == OK_Ordinary)
14272         VK = Input.get()->getValueKind();
14273     } else if (!getLangOpts().CPlusPlus) {
14274       // In C, a volatile scalar is read by __imag. In C++, it is not.
14275       Input = DefaultLvalueConversion(Input.get());
14276     }
14277     break;
14278   case UO_Extension:
14279     resultType = Input.get()->getType();
14280     VK = Input.get()->getValueKind();
14281     OK = Input.get()->getObjectKind();
14282     break;
14283   case UO_Coawait:
14284     // It's unnecessary to represent the pass-through operator co_await in the
14285     // AST; just return the input expression instead.
14286     assert(!Input.get()->getType()->isDependentType() &&
14287                    "the co_await expression must be non-dependant before "
14288                    "building operator co_await");
14289     return Input;
14290   }
14291   if (resultType.isNull() || Input.isInvalid())
14292     return ExprError();
14293 
14294   // Check for array bounds violations in the operand of the UnaryOperator,
14295   // except for the '*' and '&' operators that have to be handled specially
14296   // by CheckArrayAccess (as there are special cases like &array[arraysize]
14297   // that are explicitly defined as valid by the standard).
14298   if (Opc != UO_AddrOf && Opc != UO_Deref)
14299     CheckArrayAccess(Input.get());
14300 
14301   auto *UO = new (Context)
14302       UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc, CanOverflow);
14303 
14304   if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) &&
14305       !isa<ArrayType>(UO->getType().getDesugaredType(Context)))
14306     ExprEvalContexts.back().PossibleDerefs.insert(UO);
14307 
14308   // Convert the result back to a half vector.
14309   if (ConvertHalfVec)
14310     return convertVector(UO, Context.HalfTy, *this);
14311   return UO;
14312 }
14313 
14314 /// Determine whether the given expression is a qualified member
14315 /// access expression, of a form that could be turned into a pointer to member
14316 /// with the address-of operator.
14317 bool Sema::isQualifiedMemberAccess(Expr *E) {
14318   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
14319     if (!DRE->getQualifier())
14320       return false;
14321 
14322     ValueDecl *VD = DRE->getDecl();
14323     if (!VD->isCXXClassMember())
14324       return false;
14325 
14326     if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
14327       return true;
14328     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
14329       return Method->isInstance();
14330 
14331     return false;
14332   }
14333 
14334   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
14335     if (!ULE->getQualifier())
14336       return false;
14337 
14338     for (NamedDecl *D : ULE->decls()) {
14339       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
14340         if (Method->isInstance())
14341           return true;
14342       } else {
14343         // Overload set does not contain methods.
14344         break;
14345       }
14346     }
14347 
14348     return false;
14349   }
14350 
14351   return false;
14352 }
14353 
14354 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
14355                               UnaryOperatorKind Opc, Expr *Input) {
14356   // First things first: handle placeholders so that the
14357   // overloaded-operator check considers the right type.
14358   if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
14359     // Increment and decrement of pseudo-object references.
14360     if (pty->getKind() == BuiltinType::PseudoObject &&
14361         UnaryOperator::isIncrementDecrementOp(Opc))
14362       return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
14363 
14364     // extension is always a builtin operator.
14365     if (Opc == UO_Extension)
14366       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
14367 
14368     // & gets special logic for several kinds of placeholder.
14369     // The builtin code knows what to do.
14370     if (Opc == UO_AddrOf &&
14371         (pty->getKind() == BuiltinType::Overload ||
14372          pty->getKind() == BuiltinType::UnknownAny ||
14373          pty->getKind() == BuiltinType::BoundMember))
14374       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
14375 
14376     // Anything else needs to be handled now.
14377     ExprResult Result = CheckPlaceholderExpr(Input);
14378     if (Result.isInvalid()) return ExprError();
14379     Input = Result.get();
14380   }
14381 
14382   if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
14383       UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
14384       !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
14385     // Find all of the overloaded operators visible from this
14386     // point. We perform both an operator-name lookup from the local
14387     // scope and an argument-dependent lookup based on the types of
14388     // the arguments.
14389     UnresolvedSet<16> Functions;
14390     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
14391     if (S && OverOp != OO_None)
14392       LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
14393                                    Functions);
14394 
14395     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
14396   }
14397 
14398   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
14399 }
14400 
14401 // Unary Operators.  'Tok' is the token for the operator.
14402 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
14403                               tok::TokenKind Op, Expr *Input) {
14404   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
14405 }
14406 
14407 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
14408 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
14409                                 LabelDecl *TheDecl) {
14410   TheDecl->markUsed(Context);
14411   // Create the AST node.  The address of a label always has type 'void*'.
14412   return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
14413                                      Context.getPointerType(Context.VoidTy));
14414 }
14415 
14416 void Sema::ActOnStartStmtExpr() {
14417   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
14418 }
14419 
14420 void Sema::ActOnStmtExprError() {
14421   // Note that function is also called by TreeTransform when leaving a
14422   // StmtExpr scope without rebuilding anything.
14423 
14424   DiscardCleanupsInEvaluationContext();
14425   PopExpressionEvaluationContext();
14426 }
14427 
14428 ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt,
14429                                SourceLocation RPLoc) {
14430   return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S));
14431 }
14432 
14433 ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
14434                                SourceLocation RPLoc, unsigned TemplateDepth) {
14435   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
14436   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
14437 
14438   if (hasAnyUnrecoverableErrorsInThisFunction())
14439     DiscardCleanupsInEvaluationContext();
14440   assert(!Cleanup.exprNeedsCleanups() &&
14441          "cleanups within StmtExpr not correctly bound!");
14442   PopExpressionEvaluationContext();
14443 
14444   // FIXME: there are a variety of strange constraints to enforce here, for
14445   // example, it is not possible to goto into a stmt expression apparently.
14446   // More semantic analysis is needed.
14447 
14448   // If there are sub-stmts in the compound stmt, take the type of the last one
14449   // as the type of the stmtexpr.
14450   QualType Ty = Context.VoidTy;
14451   bool StmtExprMayBindToTemp = false;
14452   if (!Compound->body_empty()) {
14453     // For GCC compatibility we get the last Stmt excluding trailing NullStmts.
14454     if (const auto *LastStmt =
14455             dyn_cast<ValueStmt>(Compound->getStmtExprResult())) {
14456       if (const Expr *Value = LastStmt->getExprStmt()) {
14457         StmtExprMayBindToTemp = true;
14458         Ty = Value->getType();
14459       }
14460     }
14461   }
14462 
14463   // FIXME: Check that expression type is complete/non-abstract; statement
14464   // expressions are not lvalues.
14465   Expr *ResStmtExpr =
14466       new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth);
14467   if (StmtExprMayBindToTemp)
14468     return MaybeBindToTemporary(ResStmtExpr);
14469   return ResStmtExpr;
14470 }
14471 
14472 ExprResult Sema::ActOnStmtExprResult(ExprResult ER) {
14473   if (ER.isInvalid())
14474     return ExprError();
14475 
14476   // Do function/array conversion on the last expression, but not
14477   // lvalue-to-rvalue.  However, initialize an unqualified type.
14478   ER = DefaultFunctionArrayConversion(ER.get());
14479   if (ER.isInvalid())
14480     return ExprError();
14481   Expr *E = ER.get();
14482 
14483   if (E->isTypeDependent())
14484     return E;
14485 
14486   // In ARC, if the final expression ends in a consume, splice
14487   // the consume out and bind it later.  In the alternate case
14488   // (when dealing with a retainable type), the result
14489   // initialization will create a produce.  In both cases the
14490   // result will be +1, and we'll need to balance that out with
14491   // a bind.
14492   auto *Cast = dyn_cast<ImplicitCastExpr>(E);
14493   if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
14494     return Cast->getSubExpr();
14495 
14496   // FIXME: Provide a better location for the initialization.
14497   return PerformCopyInitialization(
14498       InitializedEntity::InitializeStmtExprResult(
14499           E->getBeginLoc(), E->getType().getUnqualifiedType()),
14500       SourceLocation(), E);
14501 }
14502 
14503 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
14504                                       TypeSourceInfo *TInfo,
14505                                       ArrayRef<OffsetOfComponent> Components,
14506                                       SourceLocation RParenLoc) {
14507   QualType ArgTy = TInfo->getType();
14508   bool Dependent = ArgTy->isDependentType();
14509   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
14510 
14511   // We must have at least one component that refers to the type, and the first
14512   // one is known to be a field designator.  Verify that the ArgTy represents
14513   // a struct/union/class.
14514   if (!Dependent && !ArgTy->isRecordType())
14515     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
14516                        << ArgTy << TypeRange);
14517 
14518   // Type must be complete per C99 7.17p3 because a declaring a variable
14519   // with an incomplete type would be ill-formed.
14520   if (!Dependent
14521       && RequireCompleteType(BuiltinLoc, ArgTy,
14522                              diag::err_offsetof_incomplete_type, TypeRange))
14523     return ExprError();
14524 
14525   bool DidWarnAboutNonPOD = false;
14526   QualType CurrentType = ArgTy;
14527   SmallVector<OffsetOfNode, 4> Comps;
14528   SmallVector<Expr*, 4> Exprs;
14529   for (const OffsetOfComponent &OC : Components) {
14530     if (OC.isBrackets) {
14531       // Offset of an array sub-field.  TODO: Should we allow vector elements?
14532       if (!CurrentType->isDependentType()) {
14533         const ArrayType *AT = Context.getAsArrayType(CurrentType);
14534         if(!AT)
14535           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
14536                            << CurrentType);
14537         CurrentType = AT->getElementType();
14538       } else
14539         CurrentType = Context.DependentTy;
14540 
14541       ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
14542       if (IdxRval.isInvalid())
14543         return ExprError();
14544       Expr *Idx = IdxRval.get();
14545 
14546       // The expression must be an integral expression.
14547       // FIXME: An integral constant expression?
14548       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
14549           !Idx->getType()->isIntegerType())
14550         return ExprError(
14551             Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer)
14552             << Idx->getSourceRange());
14553 
14554       // Record this array index.
14555       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
14556       Exprs.push_back(Idx);
14557       continue;
14558     }
14559 
14560     // Offset of a field.
14561     if (CurrentType->isDependentType()) {
14562       // We have the offset of a field, but we can't look into the dependent
14563       // type. Just record the identifier of the field.
14564       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
14565       CurrentType = Context.DependentTy;
14566       continue;
14567     }
14568 
14569     // We need to have a complete type to look into.
14570     if (RequireCompleteType(OC.LocStart, CurrentType,
14571                             diag::err_offsetof_incomplete_type))
14572       return ExprError();
14573 
14574     // Look for the designated field.
14575     const RecordType *RC = CurrentType->getAs<RecordType>();
14576     if (!RC)
14577       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
14578                        << CurrentType);
14579     RecordDecl *RD = RC->getDecl();
14580 
14581     // C++ [lib.support.types]p5:
14582     //   The macro offsetof accepts a restricted set of type arguments in this
14583     //   International Standard. type shall be a POD structure or a POD union
14584     //   (clause 9).
14585     // C++11 [support.types]p4:
14586     //   If type is not a standard-layout class (Clause 9), the results are
14587     //   undefined.
14588     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
14589       bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
14590       unsigned DiagID =
14591         LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
14592                             : diag::ext_offsetof_non_pod_type;
14593 
14594       if (!IsSafe && !DidWarnAboutNonPOD &&
14595           DiagRuntimeBehavior(BuiltinLoc, nullptr,
14596                               PDiag(DiagID)
14597                               << SourceRange(Components[0].LocStart, OC.LocEnd)
14598                               << CurrentType))
14599         DidWarnAboutNonPOD = true;
14600     }
14601 
14602     // Look for the field.
14603     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
14604     LookupQualifiedName(R, RD);
14605     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
14606     IndirectFieldDecl *IndirectMemberDecl = nullptr;
14607     if (!MemberDecl) {
14608       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
14609         MemberDecl = IndirectMemberDecl->getAnonField();
14610     }
14611 
14612     if (!MemberDecl)
14613       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
14614                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
14615                                                               OC.LocEnd));
14616 
14617     // C99 7.17p3:
14618     //   (If the specified member is a bit-field, the behavior is undefined.)
14619     //
14620     // We diagnose this as an error.
14621     if (MemberDecl->isBitField()) {
14622       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
14623         << MemberDecl->getDeclName()
14624         << SourceRange(BuiltinLoc, RParenLoc);
14625       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
14626       return ExprError();
14627     }
14628 
14629     RecordDecl *Parent = MemberDecl->getParent();
14630     if (IndirectMemberDecl)
14631       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
14632 
14633     // If the member was found in a base class, introduce OffsetOfNodes for
14634     // the base class indirections.
14635     CXXBasePaths Paths;
14636     if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
14637                       Paths)) {
14638       if (Paths.getDetectedVirtual()) {
14639         Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
14640           << MemberDecl->getDeclName()
14641           << SourceRange(BuiltinLoc, RParenLoc);
14642         return ExprError();
14643       }
14644 
14645       CXXBasePath &Path = Paths.front();
14646       for (const CXXBasePathElement &B : Path)
14647         Comps.push_back(OffsetOfNode(B.Base));
14648     }
14649 
14650     if (IndirectMemberDecl) {
14651       for (auto *FI : IndirectMemberDecl->chain()) {
14652         assert(isa<FieldDecl>(FI));
14653         Comps.push_back(OffsetOfNode(OC.LocStart,
14654                                      cast<FieldDecl>(FI), OC.LocEnd));
14655       }
14656     } else
14657       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
14658 
14659     CurrentType = MemberDecl->getType().getNonReferenceType();
14660   }
14661 
14662   return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
14663                               Comps, Exprs, RParenLoc);
14664 }
14665 
14666 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
14667                                       SourceLocation BuiltinLoc,
14668                                       SourceLocation TypeLoc,
14669                                       ParsedType ParsedArgTy,
14670                                       ArrayRef<OffsetOfComponent> Components,
14671                                       SourceLocation RParenLoc) {
14672 
14673   TypeSourceInfo *ArgTInfo;
14674   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
14675   if (ArgTy.isNull())
14676     return ExprError();
14677 
14678   if (!ArgTInfo)
14679     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
14680 
14681   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
14682 }
14683 
14684 
14685 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
14686                                  Expr *CondExpr,
14687                                  Expr *LHSExpr, Expr *RHSExpr,
14688                                  SourceLocation RPLoc) {
14689   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
14690 
14691   ExprValueKind VK = VK_RValue;
14692   ExprObjectKind OK = OK_Ordinary;
14693   QualType resType;
14694   bool CondIsTrue = false;
14695   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
14696     resType = Context.DependentTy;
14697   } else {
14698     // The conditional expression is required to be a constant expression.
14699     llvm::APSInt condEval(32);
14700     ExprResult CondICE
14701       = VerifyIntegerConstantExpression(CondExpr, &condEval,
14702           diag::err_typecheck_choose_expr_requires_constant, false);
14703     if (CondICE.isInvalid())
14704       return ExprError();
14705     CondExpr = CondICE.get();
14706     CondIsTrue = condEval.getZExtValue();
14707 
14708     // If the condition is > zero, then the AST type is the same as the LHSExpr.
14709     Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
14710 
14711     resType = ActiveExpr->getType();
14712     VK = ActiveExpr->getValueKind();
14713     OK = ActiveExpr->getObjectKind();
14714   }
14715 
14716   return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
14717                                   resType, VK, OK, RPLoc, CondIsTrue);
14718 }
14719 
14720 //===----------------------------------------------------------------------===//
14721 // Clang Extensions.
14722 //===----------------------------------------------------------------------===//
14723 
14724 /// ActOnBlockStart - This callback is invoked when a block literal is started.
14725 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
14726   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
14727 
14728   if (LangOpts.CPlusPlus) {
14729     MangleNumberingContext *MCtx;
14730     Decl *ManglingContextDecl;
14731     std::tie(MCtx, ManglingContextDecl) =
14732         getCurrentMangleNumberContext(Block->getDeclContext());
14733     if (MCtx) {
14734       unsigned ManglingNumber = MCtx->getManglingNumber(Block);
14735       Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
14736     }
14737   }
14738 
14739   PushBlockScope(CurScope, Block);
14740   CurContext->addDecl(Block);
14741   if (CurScope)
14742     PushDeclContext(CurScope, Block);
14743   else
14744     CurContext = Block;
14745 
14746   getCurBlock()->HasImplicitReturnType = true;
14747 
14748   // Enter a new evaluation context to insulate the block from any
14749   // cleanups from the enclosing full-expression.
14750   PushExpressionEvaluationContext(
14751       ExpressionEvaluationContext::PotentiallyEvaluated);
14752 }
14753 
14754 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
14755                                Scope *CurScope) {
14756   assert(ParamInfo.getIdentifier() == nullptr &&
14757          "block-id should have no identifier!");
14758   assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteralContext);
14759   BlockScopeInfo *CurBlock = getCurBlock();
14760 
14761   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
14762   QualType T = Sig->getType();
14763 
14764   // FIXME: We should allow unexpanded parameter packs here, but that would,
14765   // in turn, make the block expression contain unexpanded parameter packs.
14766   if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
14767     // Drop the parameters.
14768     FunctionProtoType::ExtProtoInfo EPI;
14769     EPI.HasTrailingReturn = false;
14770     EPI.TypeQuals.addConst();
14771     T = Context.getFunctionType(Context.DependentTy, None, EPI);
14772     Sig = Context.getTrivialTypeSourceInfo(T);
14773   }
14774 
14775   // GetTypeForDeclarator always produces a function type for a block
14776   // literal signature.  Furthermore, it is always a FunctionProtoType
14777   // unless the function was written with a typedef.
14778   assert(T->isFunctionType() &&
14779          "GetTypeForDeclarator made a non-function block signature");
14780 
14781   // Look for an explicit signature in that function type.
14782   FunctionProtoTypeLoc ExplicitSignature;
14783 
14784   if ((ExplicitSignature = Sig->getTypeLoc()
14785                                .getAsAdjusted<FunctionProtoTypeLoc>())) {
14786 
14787     // Check whether that explicit signature was synthesized by
14788     // GetTypeForDeclarator.  If so, don't save that as part of the
14789     // written signature.
14790     if (ExplicitSignature.getLocalRangeBegin() ==
14791         ExplicitSignature.getLocalRangeEnd()) {
14792       // This would be much cheaper if we stored TypeLocs instead of
14793       // TypeSourceInfos.
14794       TypeLoc Result = ExplicitSignature.getReturnLoc();
14795       unsigned Size = Result.getFullDataSize();
14796       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
14797       Sig->getTypeLoc().initializeFullCopy(Result, Size);
14798 
14799       ExplicitSignature = FunctionProtoTypeLoc();
14800     }
14801   }
14802 
14803   CurBlock->TheDecl->setSignatureAsWritten(Sig);
14804   CurBlock->FunctionType = T;
14805 
14806   const FunctionType *Fn = T->getAs<FunctionType>();
14807   QualType RetTy = Fn->getReturnType();
14808   bool isVariadic =
14809     (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
14810 
14811   CurBlock->TheDecl->setIsVariadic(isVariadic);
14812 
14813   // Context.DependentTy is used as a placeholder for a missing block
14814   // return type.  TODO:  what should we do with declarators like:
14815   //   ^ * { ... }
14816   // If the answer is "apply template argument deduction"....
14817   if (RetTy != Context.DependentTy) {
14818     CurBlock->ReturnType = RetTy;
14819     CurBlock->TheDecl->setBlockMissingReturnType(false);
14820     CurBlock->HasImplicitReturnType = false;
14821   }
14822 
14823   // Push block parameters from the declarator if we had them.
14824   SmallVector<ParmVarDecl*, 8> Params;
14825   if (ExplicitSignature) {
14826     for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
14827       ParmVarDecl *Param = ExplicitSignature.getParam(I);
14828       if (Param->getIdentifier() == nullptr && !Param->isImplicit() &&
14829           !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) {
14830         // Diagnose this as an extension in C17 and earlier.
14831         if (!getLangOpts().C2x)
14832           Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x);
14833       }
14834       Params.push_back(Param);
14835     }
14836 
14837   // Fake up parameter variables if we have a typedef, like
14838   //   ^ fntype { ... }
14839   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
14840     for (const auto &I : Fn->param_types()) {
14841       ParmVarDecl *Param = BuildParmVarDeclForTypedef(
14842           CurBlock->TheDecl, ParamInfo.getBeginLoc(), I);
14843       Params.push_back(Param);
14844     }
14845   }
14846 
14847   // Set the parameters on the block decl.
14848   if (!Params.empty()) {
14849     CurBlock->TheDecl->setParams(Params);
14850     CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
14851                              /*CheckParameterNames=*/false);
14852   }
14853 
14854   // Finally we can process decl attributes.
14855   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
14856 
14857   // Put the parameter variables in scope.
14858   for (auto AI : CurBlock->TheDecl->parameters()) {
14859     AI->setOwningFunction(CurBlock->TheDecl);
14860 
14861     // If this has an identifier, add it to the scope stack.
14862     if (AI->getIdentifier()) {
14863       CheckShadow(CurBlock->TheScope, AI);
14864 
14865       PushOnScopeChains(AI, CurBlock->TheScope);
14866     }
14867   }
14868 }
14869 
14870 /// ActOnBlockError - If there is an error parsing a block, this callback
14871 /// is invoked to pop the information about the block from the action impl.
14872 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
14873   // Leave the expression-evaluation context.
14874   DiscardCleanupsInEvaluationContext();
14875   PopExpressionEvaluationContext();
14876 
14877   // Pop off CurBlock, handle nested blocks.
14878   PopDeclContext();
14879   PopFunctionScopeInfo();
14880 }
14881 
14882 /// ActOnBlockStmtExpr - This is called when the body of a block statement
14883 /// literal was successfully completed.  ^(int x){...}
14884 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
14885                                     Stmt *Body, Scope *CurScope) {
14886   // If blocks are disabled, emit an error.
14887   if (!LangOpts.Blocks)
14888     Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
14889 
14890   // Leave the expression-evaluation context.
14891   if (hasAnyUnrecoverableErrorsInThisFunction())
14892     DiscardCleanupsInEvaluationContext();
14893   assert(!Cleanup.exprNeedsCleanups() &&
14894          "cleanups within block not correctly bound!");
14895   PopExpressionEvaluationContext();
14896 
14897   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
14898   BlockDecl *BD = BSI->TheDecl;
14899 
14900   if (BSI->HasImplicitReturnType)
14901     deduceClosureReturnType(*BSI);
14902 
14903   QualType RetTy = Context.VoidTy;
14904   if (!BSI->ReturnType.isNull())
14905     RetTy = BSI->ReturnType;
14906 
14907   bool NoReturn = BD->hasAttr<NoReturnAttr>();
14908   QualType BlockTy;
14909 
14910   // If the user wrote a function type in some form, try to use that.
14911   if (!BSI->FunctionType.isNull()) {
14912     const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>();
14913 
14914     FunctionType::ExtInfo Ext = FTy->getExtInfo();
14915     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
14916 
14917     // Turn protoless block types into nullary block types.
14918     if (isa<FunctionNoProtoType>(FTy)) {
14919       FunctionProtoType::ExtProtoInfo EPI;
14920       EPI.ExtInfo = Ext;
14921       BlockTy = Context.getFunctionType(RetTy, None, EPI);
14922 
14923     // Otherwise, if we don't need to change anything about the function type,
14924     // preserve its sugar structure.
14925     } else if (FTy->getReturnType() == RetTy &&
14926                (!NoReturn || FTy->getNoReturnAttr())) {
14927       BlockTy = BSI->FunctionType;
14928 
14929     // Otherwise, make the minimal modifications to the function type.
14930     } else {
14931       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
14932       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
14933       EPI.TypeQuals = Qualifiers();
14934       EPI.ExtInfo = Ext;
14935       BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
14936     }
14937 
14938   // If we don't have a function type, just build one from nothing.
14939   } else {
14940     FunctionProtoType::ExtProtoInfo EPI;
14941     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
14942     BlockTy = Context.getFunctionType(RetTy, None, EPI);
14943   }
14944 
14945   DiagnoseUnusedParameters(BD->parameters());
14946   BlockTy = Context.getBlockPointerType(BlockTy);
14947 
14948   // If needed, diagnose invalid gotos and switches in the block.
14949   if (getCurFunction()->NeedsScopeChecking() &&
14950       !PP.isCodeCompletionEnabled())
14951     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
14952 
14953   BD->setBody(cast<CompoundStmt>(Body));
14954 
14955   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
14956     DiagnoseUnguardedAvailabilityViolations(BD);
14957 
14958   // Try to apply the named return value optimization. We have to check again
14959   // if we can do this, though, because blocks keep return statements around
14960   // to deduce an implicit return type.
14961   if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
14962       !BD->isDependentContext())
14963     computeNRVO(Body, BSI);
14964 
14965   if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() ||
14966       RetTy.hasNonTrivialToPrimitiveCopyCUnion())
14967     checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn,
14968                           NTCUK_Destruct|NTCUK_Copy);
14969 
14970   PopDeclContext();
14971 
14972   // Pop the block scope now but keep it alive to the end of this function.
14973   AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
14974   PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy);
14975 
14976   // Set the captured variables on the block.
14977   SmallVector<BlockDecl::Capture, 4> Captures;
14978   for (Capture &Cap : BSI->Captures) {
14979     if (Cap.isInvalid() || Cap.isThisCapture())
14980       continue;
14981 
14982     VarDecl *Var = Cap.getVariable();
14983     Expr *CopyExpr = nullptr;
14984     if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) {
14985       if (const RecordType *Record =
14986               Cap.getCaptureType()->getAs<RecordType>()) {
14987         // The capture logic needs the destructor, so make sure we mark it.
14988         // Usually this is unnecessary because most local variables have
14989         // their destructors marked at declaration time, but parameters are
14990         // an exception because it's technically only the call site that
14991         // actually requires the destructor.
14992         if (isa<ParmVarDecl>(Var))
14993           FinalizeVarWithDestructor(Var, Record);
14994 
14995         // Enter a separate potentially-evaluated context while building block
14996         // initializers to isolate their cleanups from those of the block
14997         // itself.
14998         // FIXME: Is this appropriate even when the block itself occurs in an
14999         // unevaluated operand?
15000         EnterExpressionEvaluationContext EvalContext(
15001             *this, ExpressionEvaluationContext::PotentiallyEvaluated);
15002 
15003         SourceLocation Loc = Cap.getLocation();
15004 
15005         ExprResult Result = BuildDeclarationNameExpr(
15006             CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
15007 
15008         // According to the blocks spec, the capture of a variable from
15009         // the stack requires a const copy constructor.  This is not true
15010         // of the copy/move done to move a __block variable to the heap.
15011         if (!Result.isInvalid() &&
15012             !Result.get()->getType().isConstQualified()) {
15013           Result = ImpCastExprToType(Result.get(),
15014                                      Result.get()->getType().withConst(),
15015                                      CK_NoOp, VK_LValue);
15016         }
15017 
15018         if (!Result.isInvalid()) {
15019           Result = PerformCopyInitialization(
15020               InitializedEntity::InitializeBlock(Var->getLocation(),
15021                                                  Cap.getCaptureType(), false),
15022               Loc, Result.get());
15023         }
15024 
15025         // Build a full-expression copy expression if initialization
15026         // succeeded and used a non-trivial constructor.  Recover from
15027         // errors by pretending that the copy isn't necessary.
15028         if (!Result.isInvalid() &&
15029             !cast<CXXConstructExpr>(Result.get())->getConstructor()
15030                 ->isTrivial()) {
15031           Result = MaybeCreateExprWithCleanups(Result);
15032           CopyExpr = Result.get();
15033         }
15034       }
15035     }
15036 
15037     BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(),
15038                               CopyExpr);
15039     Captures.push_back(NewCap);
15040   }
15041   BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
15042 
15043   BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy);
15044 
15045   // If the block isn't obviously global, i.e. it captures anything at
15046   // all, then we need to do a few things in the surrounding context:
15047   if (Result->getBlockDecl()->hasCaptures()) {
15048     // First, this expression has a new cleanup object.
15049     ExprCleanupObjects.push_back(Result->getBlockDecl());
15050     Cleanup.setExprNeedsCleanups(true);
15051 
15052     // It also gets a branch-protected scope if any of the captured
15053     // variables needs destruction.
15054     for (const auto &CI : Result->getBlockDecl()->captures()) {
15055       const VarDecl *var = CI.getVariable();
15056       if (var->getType().isDestructedType() != QualType::DK_none) {
15057         setFunctionHasBranchProtectedScope();
15058         break;
15059       }
15060     }
15061   }
15062 
15063   if (getCurFunction())
15064     getCurFunction()->addBlock(BD);
15065 
15066   return Result;
15067 }
15068 
15069 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
15070                             SourceLocation RPLoc) {
15071   TypeSourceInfo *TInfo;
15072   GetTypeFromParser(Ty, &TInfo);
15073   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
15074 }
15075 
15076 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
15077                                 Expr *E, TypeSourceInfo *TInfo,
15078                                 SourceLocation RPLoc) {
15079   Expr *OrigExpr = E;
15080   bool IsMS = false;
15081 
15082   // CUDA device code does not support varargs.
15083   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
15084     if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
15085       CUDAFunctionTarget T = IdentifyCUDATarget(F);
15086       if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
15087         return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device));
15088     }
15089   }
15090 
15091   // NVPTX does not support va_arg expression.
15092   if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
15093       Context.getTargetInfo().getTriple().isNVPTX())
15094     targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device);
15095 
15096   // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
15097   // as Microsoft ABI on an actual Microsoft platform, where
15098   // __builtin_ms_va_list and __builtin_va_list are the same.)
15099   if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
15100       Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
15101     QualType MSVaListType = Context.getBuiltinMSVaListType();
15102     if (Context.hasSameType(MSVaListType, E->getType())) {
15103       if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
15104         return ExprError();
15105       IsMS = true;
15106     }
15107   }
15108 
15109   // Get the va_list type
15110   QualType VaListType = Context.getBuiltinVaListType();
15111   if (!IsMS) {
15112     if (VaListType->isArrayType()) {
15113       // Deal with implicit array decay; for example, on x86-64,
15114       // va_list is an array, but it's supposed to decay to
15115       // a pointer for va_arg.
15116       VaListType = Context.getArrayDecayedType(VaListType);
15117       // Make sure the input expression also decays appropriately.
15118       ExprResult Result = UsualUnaryConversions(E);
15119       if (Result.isInvalid())
15120         return ExprError();
15121       E = Result.get();
15122     } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
15123       // If va_list is a record type and we are compiling in C++ mode,
15124       // check the argument using reference binding.
15125       InitializedEntity Entity = InitializedEntity::InitializeParameter(
15126           Context, Context.getLValueReferenceType(VaListType), false);
15127       ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
15128       if (Init.isInvalid())
15129         return ExprError();
15130       E = Init.getAs<Expr>();
15131     } else {
15132       // Otherwise, the va_list argument must be an l-value because
15133       // it is modified by va_arg.
15134       if (!E->isTypeDependent() &&
15135           CheckForModifiableLvalue(E, BuiltinLoc, *this))
15136         return ExprError();
15137     }
15138   }
15139 
15140   if (!IsMS && !E->isTypeDependent() &&
15141       !Context.hasSameType(VaListType, E->getType()))
15142     return ExprError(
15143         Diag(E->getBeginLoc(),
15144              diag::err_first_argument_to_va_arg_not_of_type_va_list)
15145         << OrigExpr->getType() << E->getSourceRange());
15146 
15147   if (!TInfo->getType()->isDependentType()) {
15148     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
15149                             diag::err_second_parameter_to_va_arg_incomplete,
15150                             TInfo->getTypeLoc()))
15151       return ExprError();
15152 
15153     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
15154                                TInfo->getType(),
15155                                diag::err_second_parameter_to_va_arg_abstract,
15156                                TInfo->getTypeLoc()))
15157       return ExprError();
15158 
15159     if (!TInfo->getType().isPODType(Context)) {
15160       Diag(TInfo->getTypeLoc().getBeginLoc(),
15161            TInfo->getType()->isObjCLifetimeType()
15162              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
15163              : diag::warn_second_parameter_to_va_arg_not_pod)
15164         << TInfo->getType()
15165         << TInfo->getTypeLoc().getSourceRange();
15166     }
15167 
15168     // Check for va_arg where arguments of the given type will be promoted
15169     // (i.e. this va_arg is guaranteed to have undefined behavior).
15170     QualType PromoteType;
15171     if (TInfo->getType()->isPromotableIntegerType()) {
15172       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
15173       if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
15174         PromoteType = QualType();
15175     }
15176     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
15177       PromoteType = Context.DoubleTy;
15178     if (!PromoteType.isNull())
15179       DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
15180                   PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
15181                           << TInfo->getType()
15182                           << PromoteType
15183                           << TInfo->getTypeLoc().getSourceRange());
15184   }
15185 
15186   QualType T = TInfo->getType().getNonLValueExprType(Context);
15187   return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
15188 }
15189 
15190 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
15191   // The type of __null will be int or long, depending on the size of
15192   // pointers on the target.
15193   QualType Ty;
15194   unsigned pw = Context.getTargetInfo().getPointerWidth(0);
15195   if (pw == Context.getTargetInfo().getIntWidth())
15196     Ty = Context.IntTy;
15197   else if (pw == Context.getTargetInfo().getLongWidth())
15198     Ty = Context.LongTy;
15199   else if (pw == Context.getTargetInfo().getLongLongWidth())
15200     Ty = Context.LongLongTy;
15201   else {
15202     llvm_unreachable("I don't know size of pointer!");
15203   }
15204 
15205   return new (Context) GNUNullExpr(Ty, TokenLoc);
15206 }
15207 
15208 ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind,
15209                                     SourceLocation BuiltinLoc,
15210                                     SourceLocation RPLoc) {
15211   return BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, CurContext);
15212 }
15213 
15214 ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind,
15215                                     SourceLocation BuiltinLoc,
15216                                     SourceLocation RPLoc,
15217                                     DeclContext *ParentContext) {
15218   return new (Context)
15219       SourceLocExpr(Context, Kind, BuiltinLoc, RPLoc, ParentContext);
15220 }
15221 
15222 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp,
15223                                               bool Diagnose) {
15224   if (!getLangOpts().ObjC)
15225     return false;
15226 
15227   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
15228   if (!PT)
15229     return false;
15230 
15231   if (!PT->isObjCIdType()) {
15232     // Check if the destination is the 'NSString' interface.
15233     const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
15234     if (!ID || !ID->getIdentifier()->isStr("NSString"))
15235       return false;
15236   }
15237 
15238   // Ignore any parens, implicit casts (should only be
15239   // array-to-pointer decays), and not-so-opaque values.  The last is
15240   // important for making this trigger for property assignments.
15241   Expr *SrcExpr = Exp->IgnoreParenImpCasts();
15242   if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
15243     if (OV->getSourceExpr())
15244       SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
15245 
15246   StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
15247   if (!SL || !SL->isAscii())
15248     return false;
15249   if (Diagnose) {
15250     Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix)
15251         << FixItHint::CreateInsertion(SL->getBeginLoc(), "@");
15252     Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get();
15253   }
15254   return true;
15255 }
15256 
15257 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
15258                                               const Expr *SrcExpr) {
15259   if (!DstType->isFunctionPointerType() ||
15260       !SrcExpr->getType()->isFunctionType())
15261     return false;
15262 
15263   auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
15264   if (!DRE)
15265     return false;
15266 
15267   auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
15268   if (!FD)
15269     return false;
15270 
15271   return !S.checkAddressOfFunctionIsAvailable(FD,
15272                                               /*Complain=*/true,
15273                                               SrcExpr->getBeginLoc());
15274 }
15275 
15276 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
15277                                     SourceLocation Loc,
15278                                     QualType DstType, QualType SrcType,
15279                                     Expr *SrcExpr, AssignmentAction Action,
15280                                     bool *Complained) {
15281   if (Complained)
15282     *Complained = false;
15283 
15284   // Decode the result (notice that AST's are still created for extensions).
15285   bool CheckInferredResultType = false;
15286   bool isInvalid = false;
15287   unsigned DiagKind = 0;
15288   FixItHint Hint;
15289   ConversionFixItGenerator ConvHints;
15290   bool MayHaveConvFixit = false;
15291   bool MayHaveFunctionDiff = false;
15292   const ObjCInterfaceDecl *IFace = nullptr;
15293   const ObjCProtocolDecl *PDecl = nullptr;
15294 
15295   switch (ConvTy) {
15296   case Compatible:
15297       DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
15298       return false;
15299 
15300   case PointerToInt:
15301     if (getLangOpts().CPlusPlus) {
15302       DiagKind = diag::err_typecheck_convert_pointer_int;
15303       isInvalid = true;
15304     } else {
15305       DiagKind = diag::ext_typecheck_convert_pointer_int;
15306     }
15307     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15308     MayHaveConvFixit = true;
15309     break;
15310   case IntToPointer:
15311     if (getLangOpts().CPlusPlus) {
15312       DiagKind = diag::err_typecheck_convert_int_pointer;
15313       isInvalid = true;
15314     } else {
15315       DiagKind = diag::ext_typecheck_convert_int_pointer;
15316     }
15317     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15318     MayHaveConvFixit = true;
15319     break;
15320   case IncompatibleFunctionPointer:
15321     if (getLangOpts().CPlusPlus) {
15322       DiagKind = diag::err_typecheck_convert_incompatible_function_pointer;
15323       isInvalid = true;
15324     } else {
15325       DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
15326     }
15327     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15328     MayHaveConvFixit = true;
15329     break;
15330   case IncompatiblePointer:
15331     if (Action == AA_Passing_CFAudited) {
15332       DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
15333     } else if (getLangOpts().CPlusPlus) {
15334       DiagKind = diag::err_typecheck_convert_incompatible_pointer;
15335       isInvalid = true;
15336     } else {
15337       DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
15338     }
15339     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
15340       SrcType->isObjCObjectPointerType();
15341     if (Hint.isNull() && !CheckInferredResultType) {
15342       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15343     }
15344     else if (CheckInferredResultType) {
15345       SrcType = SrcType.getUnqualifiedType();
15346       DstType = DstType.getUnqualifiedType();
15347     }
15348     MayHaveConvFixit = true;
15349     break;
15350   case IncompatiblePointerSign:
15351     if (getLangOpts().CPlusPlus) {
15352       DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign;
15353       isInvalid = true;
15354     } else {
15355       DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
15356     }
15357     break;
15358   case FunctionVoidPointer:
15359     if (getLangOpts().CPlusPlus) {
15360       DiagKind = diag::err_typecheck_convert_pointer_void_func;
15361       isInvalid = true;
15362     } else {
15363       DiagKind = diag::ext_typecheck_convert_pointer_void_func;
15364     }
15365     break;
15366   case IncompatiblePointerDiscardsQualifiers: {
15367     // Perform array-to-pointer decay if necessary.
15368     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
15369 
15370     isInvalid = true;
15371 
15372     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
15373     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
15374     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
15375       DiagKind = diag::err_typecheck_incompatible_address_space;
15376       break;
15377 
15378     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
15379       DiagKind = diag::err_typecheck_incompatible_ownership;
15380       break;
15381     }
15382 
15383     llvm_unreachable("unknown error case for discarding qualifiers!");
15384     // fallthrough
15385   }
15386   case CompatiblePointerDiscardsQualifiers:
15387     // If the qualifiers lost were because we were applying the
15388     // (deprecated) C++ conversion from a string literal to a char*
15389     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
15390     // Ideally, this check would be performed in
15391     // checkPointerTypesForAssignment. However, that would require a
15392     // bit of refactoring (so that the second argument is an
15393     // expression, rather than a type), which should be done as part
15394     // of a larger effort to fix checkPointerTypesForAssignment for
15395     // C++ semantics.
15396     if (getLangOpts().CPlusPlus &&
15397         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
15398       return false;
15399     if (getLangOpts().CPlusPlus) {
15400       DiagKind =  diag::err_typecheck_convert_discards_qualifiers;
15401       isInvalid = true;
15402     } else {
15403       DiagKind =  diag::ext_typecheck_convert_discards_qualifiers;
15404     }
15405 
15406     break;
15407   case IncompatibleNestedPointerQualifiers:
15408     if (getLangOpts().CPlusPlus) {
15409       isInvalid = true;
15410       DiagKind = diag::err_nested_pointer_qualifier_mismatch;
15411     } else {
15412       DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
15413     }
15414     break;
15415   case IncompatibleNestedPointerAddressSpaceMismatch:
15416     DiagKind = diag::err_typecheck_incompatible_nested_address_space;
15417     isInvalid = true;
15418     break;
15419   case IntToBlockPointer:
15420     DiagKind = diag::err_int_to_block_pointer;
15421     isInvalid = true;
15422     break;
15423   case IncompatibleBlockPointer:
15424     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
15425     isInvalid = true;
15426     break;
15427   case IncompatibleObjCQualifiedId: {
15428     if (SrcType->isObjCQualifiedIdType()) {
15429       const ObjCObjectPointerType *srcOPT =
15430                 SrcType->castAs<ObjCObjectPointerType>();
15431       for (auto *srcProto : srcOPT->quals()) {
15432         PDecl = srcProto;
15433         break;
15434       }
15435       if (const ObjCInterfaceType *IFaceT =
15436             DstType->castAs<ObjCObjectPointerType>()->getInterfaceType())
15437         IFace = IFaceT->getDecl();
15438     }
15439     else if (DstType->isObjCQualifiedIdType()) {
15440       const ObjCObjectPointerType *dstOPT =
15441         DstType->castAs<ObjCObjectPointerType>();
15442       for (auto *dstProto : dstOPT->quals()) {
15443         PDecl = dstProto;
15444         break;
15445       }
15446       if (const ObjCInterfaceType *IFaceT =
15447             SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType())
15448         IFace = IFaceT->getDecl();
15449     }
15450     if (getLangOpts().CPlusPlus) {
15451       DiagKind = diag::err_incompatible_qualified_id;
15452       isInvalid = true;
15453     } else {
15454       DiagKind = diag::warn_incompatible_qualified_id;
15455     }
15456     break;
15457   }
15458   case IncompatibleVectors:
15459     if (getLangOpts().CPlusPlus) {
15460       DiagKind = diag::err_incompatible_vectors;
15461       isInvalid = true;
15462     } else {
15463       DiagKind = diag::warn_incompatible_vectors;
15464     }
15465     break;
15466   case IncompatibleObjCWeakRef:
15467     DiagKind = diag::err_arc_weak_unavailable_assign;
15468     isInvalid = true;
15469     break;
15470   case Incompatible:
15471     if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
15472       if (Complained)
15473         *Complained = true;
15474       return true;
15475     }
15476 
15477     DiagKind = diag::err_typecheck_convert_incompatible;
15478     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15479     MayHaveConvFixit = true;
15480     isInvalid = true;
15481     MayHaveFunctionDiff = true;
15482     break;
15483   }
15484 
15485   QualType FirstType, SecondType;
15486   switch (Action) {
15487   case AA_Assigning:
15488   case AA_Initializing:
15489     // The destination type comes first.
15490     FirstType = DstType;
15491     SecondType = SrcType;
15492     break;
15493 
15494   case AA_Returning:
15495   case AA_Passing:
15496   case AA_Passing_CFAudited:
15497   case AA_Converting:
15498   case AA_Sending:
15499   case AA_Casting:
15500     // The source type comes first.
15501     FirstType = SrcType;
15502     SecondType = DstType;
15503     break;
15504   }
15505 
15506   PartialDiagnostic FDiag = PDiag(DiagKind);
15507   if (Action == AA_Passing_CFAudited)
15508     FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
15509   else
15510     FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
15511 
15512   // If we can fix the conversion, suggest the FixIts.
15513   assert(ConvHints.isNull() || Hint.isNull());
15514   if (!ConvHints.isNull()) {
15515     for (FixItHint &H : ConvHints.Hints)
15516       FDiag << H;
15517   } else {
15518     FDiag << Hint;
15519   }
15520   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
15521 
15522   if (MayHaveFunctionDiff)
15523     HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
15524 
15525   Diag(Loc, FDiag);
15526   if ((DiagKind == diag::warn_incompatible_qualified_id ||
15527        DiagKind == diag::err_incompatible_qualified_id) &&
15528       PDecl && IFace && !IFace->hasDefinition())
15529     Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
15530         << IFace << PDecl;
15531 
15532   if (SecondType == Context.OverloadTy)
15533     NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
15534                               FirstType, /*TakingAddress=*/true);
15535 
15536   if (CheckInferredResultType)
15537     EmitRelatedResultTypeNote(SrcExpr);
15538 
15539   if (Action == AA_Returning && ConvTy == IncompatiblePointer)
15540     EmitRelatedResultTypeNoteForReturn(DstType);
15541 
15542   if (Complained)
15543     *Complained = true;
15544   return isInvalid;
15545 }
15546 
15547 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
15548                                                  llvm::APSInt *Result) {
15549   class SimpleICEDiagnoser : public VerifyICEDiagnoser {
15550   public:
15551     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
15552       S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
15553     }
15554   } Diagnoser;
15555 
15556   return VerifyIntegerConstantExpression(E, Result, Diagnoser);
15557 }
15558 
15559 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
15560                                                  llvm::APSInt *Result,
15561                                                  unsigned DiagID,
15562                                                  bool AllowFold) {
15563   class IDDiagnoser : public VerifyICEDiagnoser {
15564     unsigned DiagID;
15565 
15566   public:
15567     IDDiagnoser(unsigned DiagID)
15568       : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
15569 
15570     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
15571       S.Diag(Loc, DiagID) << SR;
15572     }
15573   } Diagnoser(DiagID);
15574 
15575   return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
15576 }
15577 
15578 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
15579                                             SourceRange SR) {
15580   S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
15581 }
15582 
15583 ExprResult
15584 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
15585                                       VerifyICEDiagnoser &Diagnoser,
15586                                       bool AllowFold) {
15587   SourceLocation DiagLoc = E->getBeginLoc();
15588 
15589   if (getLangOpts().CPlusPlus11) {
15590     // C++11 [expr.const]p5:
15591     //   If an expression of literal class type is used in a context where an
15592     //   integral constant expression is required, then that class type shall
15593     //   have a single non-explicit conversion function to an integral or
15594     //   unscoped enumeration type
15595     ExprResult Converted;
15596     class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
15597     public:
15598       CXX11ConvertDiagnoser(bool Silent)
15599           : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
15600                                 Silent, true) {}
15601 
15602       SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
15603                                            QualType T) override {
15604         return S.Diag(Loc, diag::err_ice_not_integral) << T;
15605       }
15606 
15607       SemaDiagnosticBuilder diagnoseIncomplete(
15608           Sema &S, SourceLocation Loc, QualType T) override {
15609         return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
15610       }
15611 
15612       SemaDiagnosticBuilder diagnoseExplicitConv(
15613           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
15614         return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
15615       }
15616 
15617       SemaDiagnosticBuilder noteExplicitConv(
15618           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
15619         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
15620                  << ConvTy->isEnumeralType() << ConvTy;
15621       }
15622 
15623       SemaDiagnosticBuilder diagnoseAmbiguous(
15624           Sema &S, SourceLocation Loc, QualType T) override {
15625         return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
15626       }
15627 
15628       SemaDiagnosticBuilder noteAmbiguous(
15629           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
15630         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
15631                  << ConvTy->isEnumeralType() << ConvTy;
15632       }
15633 
15634       SemaDiagnosticBuilder diagnoseConversion(
15635           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
15636         llvm_unreachable("conversion functions are permitted");
15637       }
15638     } ConvertDiagnoser(Diagnoser.Suppress);
15639 
15640     Converted = PerformContextualImplicitConversion(DiagLoc, E,
15641                                                     ConvertDiagnoser);
15642     if (Converted.isInvalid())
15643       return Converted;
15644     E = Converted.get();
15645     if (!E->getType()->isIntegralOrUnscopedEnumerationType())
15646       return ExprError();
15647   } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
15648     // An ICE must be of integral or unscoped enumeration type.
15649     if (!Diagnoser.Suppress)
15650       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
15651     return ExprError();
15652   }
15653 
15654   ExprResult RValueExpr = DefaultLvalueConversion(E);
15655   if (RValueExpr.isInvalid())
15656     return ExprError();
15657 
15658   E = RValueExpr.get();
15659 
15660   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
15661   // in the non-ICE case.
15662   if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
15663     if (Result)
15664       *Result = E->EvaluateKnownConstIntCheckOverflow(Context);
15665     if (!isa<ConstantExpr>(E))
15666       E = ConstantExpr::Create(Context, E);
15667     return E;
15668   }
15669 
15670   Expr::EvalResult EvalResult;
15671   SmallVector<PartialDiagnosticAt, 8> Notes;
15672   EvalResult.Diag = &Notes;
15673 
15674   // Try to evaluate the expression, and produce diagnostics explaining why it's
15675   // not a constant expression as a side-effect.
15676   bool Folded =
15677       E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) &&
15678       EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
15679 
15680   if (!isa<ConstantExpr>(E))
15681     E = ConstantExpr::Create(Context, E, EvalResult.Val);
15682 
15683   // In C++11, we can rely on diagnostics being produced for any expression
15684   // which is not a constant expression. If no diagnostics were produced, then
15685   // this is a constant expression.
15686   if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
15687     if (Result)
15688       *Result = EvalResult.Val.getInt();
15689     return E;
15690   }
15691 
15692   // If our only note is the usual "invalid subexpression" note, just point
15693   // the caret at its location rather than producing an essentially
15694   // redundant note.
15695   if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
15696         diag::note_invalid_subexpr_in_const_expr) {
15697     DiagLoc = Notes[0].first;
15698     Notes.clear();
15699   }
15700 
15701   if (!Folded || !AllowFold) {
15702     if (!Diagnoser.Suppress) {
15703       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
15704       for (const PartialDiagnosticAt &Note : Notes)
15705         Diag(Note.first, Note.second);
15706     }
15707 
15708     return ExprError();
15709   }
15710 
15711   Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
15712   for (const PartialDiagnosticAt &Note : Notes)
15713     Diag(Note.first, Note.second);
15714 
15715   if (Result)
15716     *Result = EvalResult.Val.getInt();
15717   return E;
15718 }
15719 
15720 namespace {
15721   // Handle the case where we conclude a expression which we speculatively
15722   // considered to be unevaluated is actually evaluated.
15723   class TransformToPE : public TreeTransform<TransformToPE> {
15724     typedef TreeTransform<TransformToPE> BaseTransform;
15725 
15726   public:
15727     TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
15728 
15729     // Make sure we redo semantic analysis
15730     bool AlwaysRebuild() { return true; }
15731     bool ReplacingOriginal() { return true; }
15732 
15733     // We need to special-case DeclRefExprs referring to FieldDecls which
15734     // are not part of a member pointer formation; normal TreeTransforming
15735     // doesn't catch this case because of the way we represent them in the AST.
15736     // FIXME: This is a bit ugly; is it really the best way to handle this
15737     // case?
15738     //
15739     // Error on DeclRefExprs referring to FieldDecls.
15740     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
15741       if (isa<FieldDecl>(E->getDecl()) &&
15742           !SemaRef.isUnevaluatedContext())
15743         return SemaRef.Diag(E->getLocation(),
15744                             diag::err_invalid_non_static_member_use)
15745             << E->getDecl() << E->getSourceRange();
15746 
15747       return BaseTransform::TransformDeclRefExpr(E);
15748     }
15749 
15750     // Exception: filter out member pointer formation
15751     ExprResult TransformUnaryOperator(UnaryOperator *E) {
15752       if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
15753         return E;
15754 
15755       return BaseTransform::TransformUnaryOperator(E);
15756     }
15757 
15758     // The body of a lambda-expression is in a separate expression evaluation
15759     // context so never needs to be transformed.
15760     // FIXME: Ideally we wouldn't transform the closure type either, and would
15761     // just recreate the capture expressions and lambda expression.
15762     StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
15763       return SkipLambdaBody(E, Body);
15764     }
15765   };
15766 }
15767 
15768 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
15769   assert(isUnevaluatedContext() &&
15770          "Should only transform unevaluated expressions");
15771   ExprEvalContexts.back().Context =
15772       ExprEvalContexts[ExprEvalContexts.size()-2].Context;
15773   if (isUnevaluatedContext())
15774     return E;
15775   return TransformToPE(*this).TransformExpr(E);
15776 }
15777 
15778 void
15779 Sema::PushExpressionEvaluationContext(
15780     ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
15781     ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
15782   ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
15783                                 LambdaContextDecl, ExprContext);
15784   Cleanup.reset();
15785   if (!MaybeODRUseExprs.empty())
15786     std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
15787 }
15788 
15789 void
15790 Sema::PushExpressionEvaluationContext(
15791     ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
15792     ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
15793   Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
15794   PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);
15795 }
15796 
15797 namespace {
15798 
15799 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
15800   PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
15801   if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) {
15802     if (E->getOpcode() == UO_Deref)
15803       return CheckPossibleDeref(S, E->getSubExpr());
15804   } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) {
15805     return CheckPossibleDeref(S, E->getBase());
15806   } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) {
15807     return CheckPossibleDeref(S, E->getBase());
15808   } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) {
15809     QualType Inner;
15810     QualType Ty = E->getType();
15811     if (const auto *Ptr = Ty->getAs<PointerType>())
15812       Inner = Ptr->getPointeeType();
15813     else if (const auto *Arr = S.Context.getAsArrayType(Ty))
15814       Inner = Arr->getElementType();
15815     else
15816       return nullptr;
15817 
15818     if (Inner->hasAttr(attr::NoDeref))
15819       return E;
15820   }
15821   return nullptr;
15822 }
15823 
15824 } // namespace
15825 
15826 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) {
15827   for (const Expr *E : Rec.PossibleDerefs) {
15828     const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E);
15829     if (DeclRef) {
15830       const ValueDecl *Decl = DeclRef->getDecl();
15831       Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type)
15832           << Decl->getName() << E->getSourceRange();
15833       Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName();
15834     } else {
15835       Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl)
15836           << E->getSourceRange();
15837     }
15838   }
15839   Rec.PossibleDerefs.clear();
15840 }
15841 
15842 /// Check whether E, which is either a discarded-value expression or an
15843 /// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue,
15844 /// and if so, remove it from the list of volatile-qualified assignments that
15845 /// we are going to warn are deprecated.
15846 void Sema::CheckUnusedVolatileAssignment(Expr *E) {
15847   if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus2a)
15848     return;
15849 
15850   // Note: ignoring parens here is not justified by the standard rules, but
15851   // ignoring parentheses seems like a more reasonable approach, and this only
15852   // drives a deprecation warning so doesn't affect conformance.
15853   if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) {
15854     if (BO->getOpcode() == BO_Assign) {
15855       auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs;
15856       LHSs.erase(std::remove(LHSs.begin(), LHSs.end(), BO->getLHS()),
15857                  LHSs.end());
15858     }
15859   }
15860 }
15861 
15862 ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) {
15863   if (!E.isUsable() || !Decl || !Decl->isConsteval() || isConstantEvaluated() ||
15864       RebuildingImmediateInvocation)
15865     return E;
15866 
15867   /// Opportunistically remove the callee from ReferencesToConsteval if we can.
15868   /// It's OK if this fails; we'll also remove this in
15869   /// HandleImmediateInvocations, but catching it here allows us to avoid
15870   /// walking the AST looking for it in simple cases.
15871   if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit()))
15872     if (auto *DeclRef =
15873             dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()))
15874       ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef);
15875 
15876   E = MaybeCreateExprWithCleanups(E);
15877 
15878   ConstantExpr *Res = ConstantExpr::Create(
15879       getASTContext(), E.get(),
15880       ConstantExpr::getStorageKind(E.get()->getType().getTypePtr(),
15881                                    getASTContext()),
15882       /*IsImmediateInvocation*/ true);
15883   ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0);
15884   return Res;
15885 }
15886 
15887 static void EvaluateAndDiagnoseImmediateInvocation(
15888     Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) {
15889   llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
15890   Expr::EvalResult Eval;
15891   Eval.Diag = &Notes;
15892   ConstantExpr *CE = Candidate.getPointer();
15893   bool Result = CE->EvaluateAsConstantExpr(Eval, Expr::EvaluateForCodeGen,
15894                                            SemaRef.getASTContext(), true);
15895   if (!Result || !Notes.empty()) {
15896     Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit();
15897     if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr))
15898       InnerExpr = FunctionalCast->getSubExpr();
15899     FunctionDecl *FD = nullptr;
15900     if (auto *Call = dyn_cast<CallExpr>(InnerExpr))
15901       FD = cast<FunctionDecl>(Call->getCalleeDecl());
15902     else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr))
15903       FD = Call->getConstructor();
15904     else
15905       llvm_unreachable("unhandled decl kind");
15906     assert(FD->isConsteval());
15907     SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call) << FD;
15908     for (auto &Note : Notes)
15909       SemaRef.Diag(Note.first, Note.second);
15910     return;
15911   }
15912   CE->MoveIntoResult(Eval.Val, SemaRef.getASTContext());
15913 }
15914 
15915 static void RemoveNestedImmediateInvocation(
15916     Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec,
15917     SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) {
15918   struct ComplexRemove : TreeTransform<ComplexRemove> {
15919     using Base = TreeTransform<ComplexRemove>;
15920     llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
15921     SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet;
15922     SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator
15923         CurrentII;
15924     ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR,
15925                   SmallVector<Sema::ImmediateInvocationCandidate, 4> &II,
15926                   SmallVector<Sema::ImmediateInvocationCandidate,
15927                               4>::reverse_iterator Current)
15928         : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {}
15929     void RemoveImmediateInvocation(ConstantExpr* E) {
15930       auto It = std::find_if(CurrentII, IISet.rend(),
15931                              [E](Sema::ImmediateInvocationCandidate Elem) {
15932                                return Elem.getPointer() == E;
15933                              });
15934       assert(It != IISet.rend() &&
15935              "ConstantExpr marked IsImmediateInvocation should "
15936              "be present");
15937       It->setInt(1); // Mark as deleted
15938     }
15939     ExprResult TransformConstantExpr(ConstantExpr *E) {
15940       if (!E->isImmediateInvocation())
15941         return Base::TransformConstantExpr(E);
15942       RemoveImmediateInvocation(E);
15943       return Base::TransformExpr(E->getSubExpr());
15944     }
15945     /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so
15946     /// we need to remove its DeclRefExpr from the DRSet.
15947     ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
15948       DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit()));
15949       return Base::TransformCXXOperatorCallExpr(E);
15950     }
15951     /// Base::TransformInitializer skip ConstantExpr so we need to visit them
15952     /// here.
15953     ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) {
15954       if (!Init)
15955         return Init;
15956       /// ConstantExpr are the first layer of implicit node to be removed so if
15957       /// Init isn't a ConstantExpr, no ConstantExpr will be skipped.
15958       if (auto *CE = dyn_cast<ConstantExpr>(Init))
15959         if (CE->isImmediateInvocation())
15960           RemoveImmediateInvocation(CE);
15961       return Base::TransformInitializer(Init, NotCopyInit);
15962     }
15963     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
15964       DRSet.erase(E);
15965       return E;
15966     }
15967     bool AlwaysRebuild() { return false; }
15968     bool ReplacingOriginal() { return true; }
15969     bool AllowSkippingCXXConstructExpr() {
15970       bool Res = AllowSkippingFirstCXXConstructExpr;
15971       AllowSkippingFirstCXXConstructExpr = true;
15972       return Res;
15973     }
15974     bool AllowSkippingFirstCXXConstructExpr = true;
15975   } Transformer(SemaRef, Rec.ReferenceToConsteval,
15976                 Rec.ImmediateInvocationCandidates, It);
15977 
15978   /// CXXConstructExpr with a single argument are getting skipped by
15979   /// TreeTransform in some situtation because they could be implicit. This
15980   /// can only occur for the top-level CXXConstructExpr because it is used
15981   /// nowhere in the expression being transformed therefore will not be rebuilt.
15982   /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from
15983   /// skipping the first CXXConstructExpr.
15984   if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit()))
15985     Transformer.AllowSkippingFirstCXXConstructExpr = false;
15986 
15987   ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr());
15988   assert(Res.isUsable());
15989   Res = SemaRef.MaybeCreateExprWithCleanups(Res);
15990   It->getPointer()->setSubExpr(Res.get());
15991 }
15992 
15993 static void
15994 HandleImmediateInvocations(Sema &SemaRef,
15995                            Sema::ExpressionEvaluationContextRecord &Rec) {
15996   if ((Rec.ImmediateInvocationCandidates.size() == 0 &&
15997        Rec.ReferenceToConsteval.size() == 0) ||
15998       SemaRef.RebuildingImmediateInvocation)
15999     return;
16000 
16001   /// When we have more then 1 ImmediateInvocationCandidates we need to check
16002   /// for nested ImmediateInvocationCandidates. when we have only 1 we only
16003   /// need to remove ReferenceToConsteval in the immediate invocation.
16004   if (Rec.ImmediateInvocationCandidates.size() > 1) {
16005 
16006     /// Prevent sema calls during the tree transform from adding pointers that
16007     /// are already in the sets.
16008     llvm::SaveAndRestore<bool> DisableIITracking(
16009         SemaRef.RebuildingImmediateInvocation, true);
16010 
16011     /// Prevent diagnostic during tree transfrom as they are duplicates
16012     Sema::TentativeAnalysisScope DisableDiag(SemaRef);
16013 
16014     for (auto It = Rec.ImmediateInvocationCandidates.rbegin();
16015          It != Rec.ImmediateInvocationCandidates.rend(); It++)
16016       if (!It->getInt())
16017         RemoveNestedImmediateInvocation(SemaRef, Rec, It);
16018   } else if (Rec.ImmediateInvocationCandidates.size() == 1 &&
16019              Rec.ReferenceToConsteval.size()) {
16020     struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> {
16021       llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
16022       SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {}
16023       bool VisitDeclRefExpr(DeclRefExpr *E) {
16024         DRSet.erase(E);
16025         return DRSet.size();
16026       }
16027     } Visitor(Rec.ReferenceToConsteval);
16028     Visitor.TraverseStmt(
16029         Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr());
16030   }
16031   for (auto CE : Rec.ImmediateInvocationCandidates)
16032     if (!CE.getInt())
16033       EvaluateAndDiagnoseImmediateInvocation(SemaRef, CE);
16034   for (auto DR : Rec.ReferenceToConsteval) {
16035     auto *FD = cast<FunctionDecl>(DR->getDecl());
16036     SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address)
16037         << FD;
16038     SemaRef.Diag(FD->getLocation(), diag::note_declared_at);
16039   }
16040 }
16041 
16042 void Sema::PopExpressionEvaluationContext() {
16043   ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
16044   unsigned NumTypos = Rec.NumTypos;
16045 
16046   if (!Rec.Lambdas.empty()) {
16047     using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind;
16048     if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || Rec.isUnevaluated() ||
16049         (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17)) {
16050       unsigned D;
16051       if (Rec.isUnevaluated()) {
16052         // C++11 [expr.prim.lambda]p2:
16053         //   A lambda-expression shall not appear in an unevaluated operand
16054         //   (Clause 5).
16055         D = diag::err_lambda_unevaluated_operand;
16056       } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
16057         // C++1y [expr.const]p2:
16058         //   A conditional-expression e is a core constant expression unless the
16059         //   evaluation of e, following the rules of the abstract machine, would
16060         //   evaluate [...] a lambda-expression.
16061         D = diag::err_lambda_in_constant_expression;
16062       } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
16063         // C++17 [expr.prim.lamda]p2:
16064         // A lambda-expression shall not appear [...] in a template-argument.
16065         D = diag::err_lambda_in_invalid_context;
16066       } else
16067         llvm_unreachable("Couldn't infer lambda error message.");
16068 
16069       for (const auto *L : Rec.Lambdas)
16070         Diag(L->getBeginLoc(), D);
16071     }
16072   }
16073 
16074   WarnOnPendingNoDerefs(Rec);
16075   HandleImmediateInvocations(*this, Rec);
16076 
16077   // Warn on any volatile-qualified simple-assignments that are not discarded-
16078   // value expressions nor unevaluated operands (those cases get removed from
16079   // this list by CheckUnusedVolatileAssignment).
16080   for (auto *BO : Rec.VolatileAssignmentLHSs)
16081     Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile)
16082         << BO->getType();
16083 
16084   // When are coming out of an unevaluated context, clear out any
16085   // temporaries that we may have created as part of the evaluation of
16086   // the expression in that context: they aren't relevant because they
16087   // will never be constructed.
16088   if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
16089     ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
16090                              ExprCleanupObjects.end());
16091     Cleanup = Rec.ParentCleanup;
16092     CleanupVarDeclMarking();
16093     std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
16094   // Otherwise, merge the contexts together.
16095   } else {
16096     Cleanup.mergeFrom(Rec.ParentCleanup);
16097     MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
16098                             Rec.SavedMaybeODRUseExprs.end());
16099   }
16100 
16101   // Pop the current expression evaluation context off the stack.
16102   ExprEvalContexts.pop_back();
16103 
16104   // The global expression evaluation context record is never popped.
16105   ExprEvalContexts.back().NumTypos += NumTypos;
16106 }
16107 
16108 void Sema::DiscardCleanupsInEvaluationContext() {
16109   ExprCleanupObjects.erase(
16110          ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
16111          ExprCleanupObjects.end());
16112   Cleanup.reset();
16113   MaybeODRUseExprs.clear();
16114 }
16115 
16116 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
16117   ExprResult Result = CheckPlaceholderExpr(E);
16118   if (Result.isInvalid())
16119     return ExprError();
16120   E = Result.get();
16121   if (!E->getType()->isVariablyModifiedType())
16122     return E;
16123   return TransformToPotentiallyEvaluated(E);
16124 }
16125 
16126 /// Are we in a context that is potentially constant evaluated per C++20
16127 /// [expr.const]p12?
16128 static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) {
16129   /// C++2a [expr.const]p12:
16130   //   An expression or conversion is potentially constant evaluated if it is
16131   switch (SemaRef.ExprEvalContexts.back().Context) {
16132     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
16133       // -- a manifestly constant-evaluated expression,
16134     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
16135     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
16136     case Sema::ExpressionEvaluationContext::DiscardedStatement:
16137       // -- a potentially-evaluated expression,
16138     case Sema::ExpressionEvaluationContext::UnevaluatedList:
16139       // -- an immediate subexpression of a braced-init-list,
16140 
16141       // -- [FIXME] an expression of the form & cast-expression that occurs
16142       //    within a templated entity
16143       // -- a subexpression of one of the above that is not a subexpression of
16144       // a nested unevaluated operand.
16145       return true;
16146 
16147     case Sema::ExpressionEvaluationContext::Unevaluated:
16148     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
16149       // Expressions in this context are never evaluated.
16150       return false;
16151   }
16152   llvm_unreachable("Invalid context");
16153 }
16154 
16155 /// Return true if this function has a calling convention that requires mangling
16156 /// in the size of the parameter pack.
16157 static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) {
16158   // These manglings don't do anything on non-Windows or non-x86 platforms, so
16159   // we don't need parameter type sizes.
16160   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
16161   if (!TT.isOSWindows() || !TT.isX86())
16162     return false;
16163 
16164   // If this is C++ and this isn't an extern "C" function, parameters do not
16165   // need to be complete. In this case, C++ mangling will apply, which doesn't
16166   // use the size of the parameters.
16167   if (S.getLangOpts().CPlusPlus && !FD->isExternC())
16168     return false;
16169 
16170   // Stdcall, fastcall, and vectorcall need this special treatment.
16171   CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
16172   switch (CC) {
16173   case CC_X86StdCall:
16174   case CC_X86FastCall:
16175   case CC_X86VectorCall:
16176     return true;
16177   default:
16178     break;
16179   }
16180   return false;
16181 }
16182 
16183 /// Require that all of the parameter types of function be complete. Normally,
16184 /// parameter types are only required to be complete when a function is called
16185 /// or defined, but to mangle functions with certain calling conventions, the
16186 /// mangler needs to know the size of the parameter list. In this situation,
16187 /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles
16188 /// the function as _foo@0, i.e. zero bytes of parameters, which will usually
16189 /// result in a linker error. Clang doesn't implement this behavior, and instead
16190 /// attempts to error at compile time.
16191 static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD,
16192                                                   SourceLocation Loc) {
16193   class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser {
16194     FunctionDecl *FD;
16195     ParmVarDecl *Param;
16196 
16197   public:
16198     ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param)
16199         : FD(FD), Param(Param) {}
16200 
16201     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
16202       CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
16203       StringRef CCName;
16204       switch (CC) {
16205       case CC_X86StdCall:
16206         CCName = "stdcall";
16207         break;
16208       case CC_X86FastCall:
16209         CCName = "fastcall";
16210         break;
16211       case CC_X86VectorCall:
16212         CCName = "vectorcall";
16213         break;
16214       default:
16215         llvm_unreachable("CC does not need mangling");
16216       }
16217 
16218       S.Diag(Loc, diag::err_cconv_incomplete_param_type)
16219           << Param->getDeclName() << FD->getDeclName() << CCName;
16220     }
16221   };
16222 
16223   for (ParmVarDecl *Param : FD->parameters()) {
16224     ParamIncompleteTypeDiagnoser Diagnoser(FD, Param);
16225     S.RequireCompleteType(Loc, Param->getType(), Diagnoser);
16226   }
16227 }
16228 
16229 namespace {
16230 enum class OdrUseContext {
16231   /// Declarations in this context are not odr-used.
16232   None,
16233   /// Declarations in this context are formally odr-used, but this is a
16234   /// dependent context.
16235   Dependent,
16236   /// Declarations in this context are odr-used but not actually used (yet).
16237   FormallyOdrUsed,
16238   /// Declarations in this context are used.
16239   Used
16240 };
16241 }
16242 
16243 /// Are we within a context in which references to resolved functions or to
16244 /// variables result in odr-use?
16245 static OdrUseContext isOdrUseContext(Sema &SemaRef) {
16246   OdrUseContext Result;
16247 
16248   switch (SemaRef.ExprEvalContexts.back().Context) {
16249     case Sema::ExpressionEvaluationContext::Unevaluated:
16250     case Sema::ExpressionEvaluationContext::UnevaluatedList:
16251     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
16252       return OdrUseContext::None;
16253 
16254     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
16255     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
16256       Result = OdrUseContext::Used;
16257       break;
16258 
16259     case Sema::ExpressionEvaluationContext::DiscardedStatement:
16260       Result = OdrUseContext::FormallyOdrUsed;
16261       break;
16262 
16263     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
16264       // A default argument formally results in odr-use, but doesn't actually
16265       // result in a use in any real sense until it itself is used.
16266       Result = OdrUseContext::FormallyOdrUsed;
16267       break;
16268   }
16269 
16270   if (SemaRef.CurContext->isDependentContext())
16271     return OdrUseContext::Dependent;
16272 
16273   return Result;
16274 }
16275 
16276 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
16277   return Func->isConstexpr() &&
16278          (Func->isImplicitlyInstantiable() || !Func->isUserProvided());
16279 }
16280 
16281 /// Mark a function referenced, and check whether it is odr-used
16282 /// (C++ [basic.def.odr]p2, C99 6.9p3)
16283 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
16284                                   bool MightBeOdrUse) {
16285   assert(Func && "No function?");
16286 
16287   Func->setReferenced();
16288 
16289   // Recursive functions aren't really used until they're used from some other
16290   // context.
16291   bool IsRecursiveCall = CurContext == Func;
16292 
16293   // C++11 [basic.def.odr]p3:
16294   //   A function whose name appears as a potentially-evaluated expression is
16295   //   odr-used if it is the unique lookup result or the selected member of a
16296   //   set of overloaded functions [...].
16297   //
16298   // We (incorrectly) mark overload resolution as an unevaluated context, so we
16299   // can just check that here.
16300   OdrUseContext OdrUse =
16301       MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None;
16302   if (IsRecursiveCall && OdrUse == OdrUseContext::Used)
16303     OdrUse = OdrUseContext::FormallyOdrUsed;
16304 
16305   // Trivial default constructors and destructors are never actually used.
16306   // FIXME: What about other special members?
16307   if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() &&
16308       OdrUse == OdrUseContext::Used) {
16309     if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func))
16310       if (Constructor->isDefaultConstructor())
16311         OdrUse = OdrUseContext::FormallyOdrUsed;
16312     if (isa<CXXDestructorDecl>(Func))
16313       OdrUse = OdrUseContext::FormallyOdrUsed;
16314   }
16315 
16316   // C++20 [expr.const]p12:
16317   //   A function [...] is needed for constant evaluation if it is [...] a
16318   //   constexpr function that is named by an expression that is potentially
16319   //   constant evaluated
16320   bool NeededForConstantEvaluation =
16321       isPotentiallyConstantEvaluatedContext(*this) &&
16322       isImplicitlyDefinableConstexprFunction(Func);
16323 
16324   // Determine whether we require a function definition to exist, per
16325   // C++11 [temp.inst]p3:
16326   //   Unless a function template specialization has been explicitly
16327   //   instantiated or explicitly specialized, the function template
16328   //   specialization is implicitly instantiated when the specialization is
16329   //   referenced in a context that requires a function definition to exist.
16330   // C++20 [temp.inst]p7:
16331   //   The existence of a definition of a [...] function is considered to
16332   //   affect the semantics of the program if the [...] function is needed for
16333   //   constant evaluation by an expression
16334   // C++20 [basic.def.odr]p10:
16335   //   Every program shall contain exactly one definition of every non-inline
16336   //   function or variable that is odr-used in that program outside of a
16337   //   discarded statement
16338   // C++20 [special]p1:
16339   //   The implementation will implicitly define [defaulted special members]
16340   //   if they are odr-used or needed for constant evaluation.
16341   //
16342   // Note that we skip the implicit instantiation of templates that are only
16343   // used in unused default arguments or by recursive calls to themselves.
16344   // This is formally non-conforming, but seems reasonable in practice.
16345   bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used ||
16346                                              NeededForConstantEvaluation);
16347 
16348   // C++14 [temp.expl.spec]p6:
16349   //   If a template [...] is explicitly specialized then that specialization
16350   //   shall be declared before the first use of that specialization that would
16351   //   cause an implicit instantiation to take place, in every translation unit
16352   //   in which such a use occurs
16353   if (NeedDefinition &&
16354       (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
16355        Func->getMemberSpecializationInfo()))
16356     checkSpecializationVisibility(Loc, Func);
16357 
16358   if (getLangOpts().CUDA)
16359     CheckCUDACall(Loc, Func);
16360 
16361   // If we need a definition, try to create one.
16362   if (NeedDefinition && !Func->getBody()) {
16363     runWithSufficientStackSpace(Loc, [&] {
16364       if (CXXConstructorDecl *Constructor =
16365               dyn_cast<CXXConstructorDecl>(Func)) {
16366         Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
16367         if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
16368           if (Constructor->isDefaultConstructor()) {
16369             if (Constructor->isTrivial() &&
16370                 !Constructor->hasAttr<DLLExportAttr>())
16371               return;
16372             DefineImplicitDefaultConstructor(Loc, Constructor);
16373           } else if (Constructor->isCopyConstructor()) {
16374             DefineImplicitCopyConstructor(Loc, Constructor);
16375           } else if (Constructor->isMoveConstructor()) {
16376             DefineImplicitMoveConstructor(Loc, Constructor);
16377           }
16378         } else if (Constructor->getInheritedConstructor()) {
16379           DefineInheritingConstructor(Loc, Constructor);
16380         }
16381       } else if (CXXDestructorDecl *Destructor =
16382                      dyn_cast<CXXDestructorDecl>(Func)) {
16383         Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
16384         if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
16385           if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
16386             return;
16387           DefineImplicitDestructor(Loc, Destructor);
16388         }
16389         if (Destructor->isVirtual() && getLangOpts().AppleKext)
16390           MarkVTableUsed(Loc, Destructor->getParent());
16391       } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
16392         if (MethodDecl->isOverloadedOperator() &&
16393             MethodDecl->getOverloadedOperator() == OO_Equal) {
16394           MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
16395           if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
16396             if (MethodDecl->isCopyAssignmentOperator())
16397               DefineImplicitCopyAssignment(Loc, MethodDecl);
16398             else if (MethodDecl->isMoveAssignmentOperator())
16399               DefineImplicitMoveAssignment(Loc, MethodDecl);
16400           }
16401         } else if (isa<CXXConversionDecl>(MethodDecl) &&
16402                    MethodDecl->getParent()->isLambda()) {
16403           CXXConversionDecl *Conversion =
16404               cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
16405           if (Conversion->isLambdaToBlockPointerConversion())
16406             DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
16407           else
16408             DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
16409         } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
16410           MarkVTableUsed(Loc, MethodDecl->getParent());
16411       }
16412 
16413       if (Func->isDefaulted() && !Func->isDeleted()) {
16414         DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func);
16415         if (DCK != DefaultedComparisonKind::None)
16416           DefineDefaultedComparison(Loc, Func, DCK);
16417       }
16418 
16419       // Implicit instantiation of function templates and member functions of
16420       // class templates.
16421       if (Func->isImplicitlyInstantiable()) {
16422         TemplateSpecializationKind TSK =
16423             Func->getTemplateSpecializationKindForInstantiation();
16424         SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
16425         bool FirstInstantiation = PointOfInstantiation.isInvalid();
16426         if (FirstInstantiation) {
16427           PointOfInstantiation = Loc;
16428           Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
16429         } else if (TSK != TSK_ImplicitInstantiation) {
16430           // Use the point of use as the point of instantiation, instead of the
16431           // point of explicit instantiation (which we track as the actual point
16432           // of instantiation). This gives better backtraces in diagnostics.
16433           PointOfInstantiation = Loc;
16434         }
16435 
16436         if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
16437             Func->isConstexpr()) {
16438           if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
16439               cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
16440               CodeSynthesisContexts.size())
16441             PendingLocalImplicitInstantiations.push_back(
16442                 std::make_pair(Func, PointOfInstantiation));
16443           else if (Func->isConstexpr())
16444             // Do not defer instantiations of constexpr functions, to avoid the
16445             // expression evaluator needing to call back into Sema if it sees a
16446             // call to such a function.
16447             InstantiateFunctionDefinition(PointOfInstantiation, Func);
16448           else {
16449             Func->setInstantiationIsPending(true);
16450             PendingInstantiations.push_back(
16451                 std::make_pair(Func, PointOfInstantiation));
16452             // Notify the consumer that a function was implicitly instantiated.
16453             Consumer.HandleCXXImplicitFunctionInstantiation(Func);
16454           }
16455         }
16456       } else {
16457         // Walk redefinitions, as some of them may be instantiable.
16458         for (auto i : Func->redecls()) {
16459           if (!i->isUsed(false) && i->isImplicitlyInstantiable())
16460             MarkFunctionReferenced(Loc, i, MightBeOdrUse);
16461         }
16462       }
16463     });
16464   }
16465 
16466   // C++14 [except.spec]p17:
16467   //   An exception-specification is considered to be needed when:
16468   //   - the function is odr-used or, if it appears in an unevaluated operand,
16469   //     would be odr-used if the expression were potentially-evaluated;
16470   //
16471   // Note, we do this even if MightBeOdrUse is false. That indicates that the
16472   // function is a pure virtual function we're calling, and in that case the
16473   // function was selected by overload resolution and we need to resolve its
16474   // exception specification for a different reason.
16475   const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
16476   if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
16477     ResolveExceptionSpec(Loc, FPT);
16478 
16479   // If this is the first "real" use, act on that.
16480   if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) {
16481     // Keep track of used but undefined functions.
16482     if (!Func->isDefined()) {
16483       if (mightHaveNonExternalLinkage(Func))
16484         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
16485       else if (Func->getMostRecentDecl()->isInlined() &&
16486                !LangOpts.GNUInline &&
16487                !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
16488         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
16489       else if (isExternalWithNoLinkageType(Func))
16490         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
16491     }
16492 
16493     // Some x86 Windows calling conventions mangle the size of the parameter
16494     // pack into the name. Computing the size of the parameters requires the
16495     // parameter types to be complete. Check that now.
16496     if (funcHasParameterSizeMangling(*this, Func))
16497       CheckCompleteParameterTypesForMangler(*this, Func, Loc);
16498 
16499     // In the MS C++ ABI, the compiler emits destructor variants where they are
16500     // used. If the destructor is used here but defined elsewhere, mark the
16501     // virtual base destructors referenced. If those virtual base destructors
16502     // are inline, this will ensure they are defined when emitting the complete
16503     // destructor variant. This checking may be redundant if the destructor is
16504     // provided later in this TU.
16505     if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
16506       if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) {
16507         CXXRecordDecl *Parent = Dtor->getParent();
16508         if (Parent->getNumVBases() > 0 && !Dtor->getBody())
16509           CheckCompleteDestructorVariant(Loc, Dtor);
16510       }
16511     }
16512 
16513     Func->markUsed(Context);
16514   }
16515 }
16516 
16517 /// Directly mark a variable odr-used. Given a choice, prefer to use
16518 /// MarkVariableReferenced since it does additional checks and then
16519 /// calls MarkVarDeclODRUsed.
16520 /// If the variable must be captured:
16521 ///  - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
16522 ///  - else capture it in the DeclContext that maps to the
16523 ///    *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
16524 static void
16525 MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef,
16526                    const unsigned *const FunctionScopeIndexToStopAt = nullptr) {
16527   // Keep track of used but undefined variables.
16528   // FIXME: We shouldn't suppress this warning for static data members.
16529   if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
16530       (!Var->isExternallyVisible() || Var->isInline() ||
16531        SemaRef.isExternalWithNoLinkageType(Var)) &&
16532       !(Var->isStaticDataMember() && Var->hasInit())) {
16533     SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()];
16534     if (old.isInvalid())
16535       old = Loc;
16536   }
16537   QualType CaptureType, DeclRefType;
16538   if (SemaRef.LangOpts.OpenMP)
16539     SemaRef.tryCaptureOpenMPLambdas(Var);
16540   SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit,
16541     /*EllipsisLoc*/ SourceLocation(),
16542     /*BuildAndDiagnose*/ true,
16543     CaptureType, DeclRefType,
16544     FunctionScopeIndexToStopAt);
16545 
16546   Var->markUsed(SemaRef.Context);
16547 }
16548 
16549 void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture,
16550                                              SourceLocation Loc,
16551                                              unsigned CapturingScopeIndex) {
16552   MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex);
16553 }
16554 
16555 static void
16556 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
16557                                    ValueDecl *var, DeclContext *DC) {
16558   DeclContext *VarDC = var->getDeclContext();
16559 
16560   //  If the parameter still belongs to the translation unit, then
16561   //  we're actually just using one parameter in the declaration of
16562   //  the next.
16563   if (isa<ParmVarDecl>(var) &&
16564       isa<TranslationUnitDecl>(VarDC))
16565     return;
16566 
16567   // For C code, don't diagnose about capture if we're not actually in code
16568   // right now; it's impossible to write a non-constant expression outside of
16569   // function context, so we'll get other (more useful) diagnostics later.
16570   //
16571   // For C++, things get a bit more nasty... it would be nice to suppress this
16572   // diagnostic for certain cases like using a local variable in an array bound
16573   // for a member of a local class, but the correct predicate is not obvious.
16574   if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
16575     return;
16576 
16577   unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
16578   unsigned ContextKind = 3; // unknown
16579   if (isa<CXXMethodDecl>(VarDC) &&
16580       cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
16581     ContextKind = 2;
16582   } else if (isa<FunctionDecl>(VarDC)) {
16583     ContextKind = 0;
16584   } else if (isa<BlockDecl>(VarDC)) {
16585     ContextKind = 1;
16586   }
16587 
16588   S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
16589     << var << ValueKind << ContextKind << VarDC;
16590   S.Diag(var->getLocation(), diag::note_entity_declared_at)
16591       << var;
16592 
16593   // FIXME: Add additional diagnostic info about class etc. which prevents
16594   // capture.
16595 }
16596 
16597 
16598 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
16599                                       bool &SubCapturesAreNested,
16600                                       QualType &CaptureType,
16601                                       QualType &DeclRefType) {
16602    // Check whether we've already captured it.
16603   if (CSI->CaptureMap.count(Var)) {
16604     // If we found a capture, any subcaptures are nested.
16605     SubCapturesAreNested = true;
16606 
16607     // Retrieve the capture type for this variable.
16608     CaptureType = CSI->getCapture(Var).getCaptureType();
16609 
16610     // Compute the type of an expression that refers to this variable.
16611     DeclRefType = CaptureType.getNonReferenceType();
16612 
16613     // Similarly to mutable captures in lambda, all the OpenMP captures by copy
16614     // are mutable in the sense that user can change their value - they are
16615     // private instances of the captured declarations.
16616     const Capture &Cap = CSI->getCapture(Var);
16617     if (Cap.isCopyCapture() &&
16618         !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
16619         !(isa<CapturedRegionScopeInfo>(CSI) &&
16620           cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
16621       DeclRefType.addConst();
16622     return true;
16623   }
16624   return false;
16625 }
16626 
16627 // Only block literals, captured statements, and lambda expressions can
16628 // capture; other scopes don't work.
16629 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
16630                                  SourceLocation Loc,
16631                                  const bool Diagnose, Sema &S) {
16632   if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
16633     return getLambdaAwareParentOfDeclContext(DC);
16634   else if (Var->hasLocalStorage()) {
16635     if (Diagnose)
16636        diagnoseUncapturableValueReference(S, Loc, Var, DC);
16637   }
16638   return nullptr;
16639 }
16640 
16641 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
16642 // certain types of variables (unnamed, variably modified types etc.)
16643 // so check for eligibility.
16644 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
16645                                  SourceLocation Loc,
16646                                  const bool Diagnose, Sema &S) {
16647 
16648   bool IsBlock = isa<BlockScopeInfo>(CSI);
16649   bool IsLambda = isa<LambdaScopeInfo>(CSI);
16650 
16651   // Lambdas are not allowed to capture unnamed variables
16652   // (e.g. anonymous unions).
16653   // FIXME: The C++11 rule don't actually state this explicitly, but I'm
16654   // assuming that's the intent.
16655   if (IsLambda && !Var->getDeclName()) {
16656     if (Diagnose) {
16657       S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
16658       S.Diag(Var->getLocation(), diag::note_declared_at);
16659     }
16660     return false;
16661   }
16662 
16663   // Prohibit variably-modified types in blocks; they're difficult to deal with.
16664   if (Var->getType()->isVariablyModifiedType() && IsBlock) {
16665     if (Diagnose) {
16666       S.Diag(Loc, diag::err_ref_vm_type);
16667       S.Diag(Var->getLocation(), diag::note_previous_decl)
16668         << Var->getDeclName();
16669     }
16670     return false;
16671   }
16672   // Prohibit structs with flexible array members too.
16673   // We cannot capture what is in the tail end of the struct.
16674   if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
16675     if (VTTy->getDecl()->hasFlexibleArrayMember()) {
16676       if (Diagnose) {
16677         if (IsBlock)
16678           S.Diag(Loc, diag::err_ref_flexarray_type);
16679         else
16680           S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
16681             << Var->getDeclName();
16682         S.Diag(Var->getLocation(), diag::note_previous_decl)
16683           << Var->getDeclName();
16684       }
16685       return false;
16686     }
16687   }
16688   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
16689   // Lambdas and captured statements are not allowed to capture __block
16690   // variables; they don't support the expected semantics.
16691   if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
16692     if (Diagnose) {
16693       S.Diag(Loc, diag::err_capture_block_variable)
16694         << Var->getDeclName() << !IsLambda;
16695       S.Diag(Var->getLocation(), diag::note_previous_decl)
16696         << Var->getDeclName();
16697     }
16698     return false;
16699   }
16700   // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
16701   if (S.getLangOpts().OpenCL && IsBlock &&
16702       Var->getType()->isBlockPointerType()) {
16703     if (Diagnose)
16704       S.Diag(Loc, diag::err_opencl_block_ref_block);
16705     return false;
16706   }
16707 
16708   return true;
16709 }
16710 
16711 // Returns true if the capture by block was successful.
16712 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
16713                                  SourceLocation Loc,
16714                                  const bool BuildAndDiagnose,
16715                                  QualType &CaptureType,
16716                                  QualType &DeclRefType,
16717                                  const bool Nested,
16718                                  Sema &S, bool Invalid) {
16719   bool ByRef = false;
16720 
16721   // Blocks are not allowed to capture arrays, excepting OpenCL.
16722   // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
16723   // (decayed to pointers).
16724   if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
16725     if (BuildAndDiagnose) {
16726       S.Diag(Loc, diag::err_ref_array_type);
16727       S.Diag(Var->getLocation(), diag::note_previous_decl)
16728       << Var->getDeclName();
16729       Invalid = true;
16730     } else {
16731       return false;
16732     }
16733   }
16734 
16735   // Forbid the block-capture of autoreleasing variables.
16736   if (!Invalid &&
16737       CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
16738     if (BuildAndDiagnose) {
16739       S.Diag(Loc, diag::err_arc_autoreleasing_capture)
16740         << /*block*/ 0;
16741       S.Diag(Var->getLocation(), diag::note_previous_decl)
16742         << Var->getDeclName();
16743       Invalid = true;
16744     } else {
16745       return false;
16746     }
16747   }
16748 
16749   // Warn about implicitly autoreleasing indirect parameters captured by blocks.
16750   if (const auto *PT = CaptureType->getAs<PointerType>()) {
16751     QualType PointeeTy = PT->getPointeeType();
16752 
16753     if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() &&
16754         PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
16755         !S.Context.hasDirectOwnershipQualifier(PointeeTy)) {
16756       if (BuildAndDiagnose) {
16757         SourceLocation VarLoc = Var->getLocation();
16758         S.Diag(Loc, diag::warn_block_capture_autoreleasing);
16759         S.Diag(VarLoc, diag::note_declare_parameter_strong);
16760       }
16761     }
16762   }
16763 
16764   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
16765   if (HasBlocksAttr || CaptureType->isReferenceType() ||
16766       (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) {
16767     // Block capture by reference does not change the capture or
16768     // declaration reference types.
16769     ByRef = true;
16770   } else {
16771     // Block capture by copy introduces 'const'.
16772     CaptureType = CaptureType.getNonReferenceType().withConst();
16773     DeclRefType = CaptureType;
16774   }
16775 
16776   // Actually capture the variable.
16777   if (BuildAndDiagnose)
16778     BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(),
16779                     CaptureType, Invalid);
16780 
16781   return !Invalid;
16782 }
16783 
16784 
16785 /// Capture the given variable in the captured region.
16786 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
16787                                     VarDecl *Var,
16788                                     SourceLocation Loc,
16789                                     const bool BuildAndDiagnose,
16790                                     QualType &CaptureType,
16791                                     QualType &DeclRefType,
16792                                     const bool RefersToCapturedVariable,
16793                                     Sema &S, bool Invalid) {
16794   // By default, capture variables by reference.
16795   bool ByRef = true;
16796   // Using an LValue reference type is consistent with Lambdas (see below).
16797   if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
16798     if (S.isOpenMPCapturedDecl(Var)) {
16799       bool HasConst = DeclRefType.isConstQualified();
16800       DeclRefType = DeclRefType.getUnqualifiedType();
16801       // Don't lose diagnostics about assignments to const.
16802       if (HasConst)
16803         DeclRefType.addConst();
16804     }
16805     // Do not capture firstprivates in tasks.
16806     if (S.isOpenMPPrivateDecl(Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel) !=
16807         OMPC_unknown)
16808       return true;
16809     ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel,
16810                                     RSI->OpenMPCaptureLevel);
16811   }
16812 
16813   if (ByRef)
16814     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
16815   else
16816     CaptureType = DeclRefType;
16817 
16818   // Actually capture the variable.
16819   if (BuildAndDiagnose)
16820     RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable,
16821                     Loc, SourceLocation(), CaptureType, Invalid);
16822 
16823   return !Invalid;
16824 }
16825 
16826 /// Capture the given variable in the lambda.
16827 static bool captureInLambda(LambdaScopeInfo *LSI,
16828                             VarDecl *Var,
16829                             SourceLocation Loc,
16830                             const bool BuildAndDiagnose,
16831                             QualType &CaptureType,
16832                             QualType &DeclRefType,
16833                             const bool RefersToCapturedVariable,
16834                             const Sema::TryCaptureKind Kind,
16835                             SourceLocation EllipsisLoc,
16836                             const bool IsTopScope,
16837                             Sema &S, bool Invalid) {
16838   // Determine whether we are capturing by reference or by value.
16839   bool ByRef = false;
16840   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
16841     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
16842   } else {
16843     ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
16844   }
16845 
16846   // Compute the type of the field that will capture this variable.
16847   if (ByRef) {
16848     // C++11 [expr.prim.lambda]p15:
16849     //   An entity is captured by reference if it is implicitly or
16850     //   explicitly captured but not captured by copy. It is
16851     //   unspecified whether additional unnamed non-static data
16852     //   members are declared in the closure type for entities
16853     //   captured by reference.
16854     //
16855     // FIXME: It is not clear whether we want to build an lvalue reference
16856     // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
16857     // to do the former, while EDG does the latter. Core issue 1249 will
16858     // clarify, but for now we follow GCC because it's a more permissive and
16859     // easily defensible position.
16860     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
16861   } else {
16862     // C++11 [expr.prim.lambda]p14:
16863     //   For each entity captured by copy, an unnamed non-static
16864     //   data member is declared in the closure type. The
16865     //   declaration order of these members is unspecified. The type
16866     //   of such a data member is the type of the corresponding
16867     //   captured entity if the entity is not a reference to an
16868     //   object, or the referenced type otherwise. [Note: If the
16869     //   captured entity is a reference to a function, the
16870     //   corresponding data member is also a reference to a
16871     //   function. - end note ]
16872     if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
16873       if (!RefType->getPointeeType()->isFunctionType())
16874         CaptureType = RefType->getPointeeType();
16875     }
16876 
16877     // Forbid the lambda copy-capture of autoreleasing variables.
16878     if (!Invalid &&
16879         CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
16880       if (BuildAndDiagnose) {
16881         S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
16882         S.Diag(Var->getLocation(), diag::note_previous_decl)
16883           << Var->getDeclName();
16884         Invalid = true;
16885       } else {
16886         return false;
16887       }
16888     }
16889 
16890     // Make sure that by-copy captures are of a complete and non-abstract type.
16891     if (!Invalid && BuildAndDiagnose) {
16892       if (!CaptureType->isDependentType() &&
16893           S.RequireCompleteSizedType(
16894               Loc, CaptureType,
16895               diag::err_capture_of_incomplete_or_sizeless_type,
16896               Var->getDeclName()))
16897         Invalid = true;
16898       else if (S.RequireNonAbstractType(Loc, CaptureType,
16899                                         diag::err_capture_of_abstract_type))
16900         Invalid = true;
16901     }
16902   }
16903 
16904   // Compute the type of a reference to this captured variable.
16905   if (ByRef)
16906     DeclRefType = CaptureType.getNonReferenceType();
16907   else {
16908     // C++ [expr.prim.lambda]p5:
16909     //   The closure type for a lambda-expression has a public inline
16910     //   function call operator [...]. This function call operator is
16911     //   declared const (9.3.1) if and only if the lambda-expression's
16912     //   parameter-declaration-clause is not followed by mutable.
16913     DeclRefType = CaptureType.getNonReferenceType();
16914     if (!LSI->Mutable && !CaptureType->isReferenceType())
16915       DeclRefType.addConst();
16916   }
16917 
16918   // Add the capture.
16919   if (BuildAndDiagnose)
16920     LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable,
16921                     Loc, EllipsisLoc, CaptureType, Invalid);
16922 
16923   return !Invalid;
16924 }
16925 
16926 bool Sema::tryCaptureVariable(
16927     VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
16928     SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
16929     QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
16930   // An init-capture is notionally from the context surrounding its
16931   // declaration, but its parent DC is the lambda class.
16932   DeclContext *VarDC = Var->getDeclContext();
16933   if (Var->isInitCapture())
16934     VarDC = VarDC->getParent();
16935 
16936   DeclContext *DC = CurContext;
16937   const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
16938       ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
16939   // We need to sync up the Declaration Context with the
16940   // FunctionScopeIndexToStopAt
16941   if (FunctionScopeIndexToStopAt) {
16942     unsigned FSIndex = FunctionScopes.size() - 1;
16943     while (FSIndex != MaxFunctionScopesIndex) {
16944       DC = getLambdaAwareParentOfDeclContext(DC);
16945       --FSIndex;
16946     }
16947   }
16948 
16949 
16950   // If the variable is declared in the current context, there is no need to
16951   // capture it.
16952   if (VarDC == DC) return true;
16953 
16954   // Capture global variables if it is required to use private copy of this
16955   // variable.
16956   bool IsGlobal = !Var->hasLocalStorage();
16957   if (IsGlobal &&
16958       !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true,
16959                                                 MaxFunctionScopesIndex)))
16960     return true;
16961   Var = Var->getCanonicalDecl();
16962 
16963   // Walk up the stack to determine whether we can capture the variable,
16964   // performing the "simple" checks that don't depend on type. We stop when
16965   // we've either hit the declared scope of the variable or find an existing
16966   // capture of that variable.  We start from the innermost capturing-entity
16967   // (the DC) and ensure that all intervening capturing-entities
16968   // (blocks/lambdas etc.) between the innermost capturer and the variable`s
16969   // declcontext can either capture the variable or have already captured
16970   // the variable.
16971   CaptureType = Var->getType();
16972   DeclRefType = CaptureType.getNonReferenceType();
16973   bool Nested = false;
16974   bool Explicit = (Kind != TryCapture_Implicit);
16975   unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
16976   do {
16977     // Only block literals, captured statements, and lambda expressions can
16978     // capture; other scopes don't work.
16979     DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
16980                                                               ExprLoc,
16981                                                               BuildAndDiagnose,
16982                                                               *this);
16983     // We need to check for the parent *first* because, if we *have*
16984     // private-captured a global variable, we need to recursively capture it in
16985     // intermediate blocks, lambdas, etc.
16986     if (!ParentDC) {
16987       if (IsGlobal) {
16988         FunctionScopesIndex = MaxFunctionScopesIndex - 1;
16989         break;
16990       }
16991       return true;
16992     }
16993 
16994     FunctionScopeInfo  *FSI = FunctionScopes[FunctionScopesIndex];
16995     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
16996 
16997 
16998     // Check whether we've already captured it.
16999     if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
17000                                              DeclRefType)) {
17001       CSI->getCapture(Var).markUsed(BuildAndDiagnose);
17002       break;
17003     }
17004     // If we are instantiating a generic lambda call operator body,
17005     // we do not want to capture new variables.  What was captured
17006     // during either a lambdas transformation or initial parsing
17007     // should be used.
17008     if (isGenericLambdaCallOperatorSpecialization(DC)) {
17009       if (BuildAndDiagnose) {
17010         LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
17011         if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
17012           Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
17013           Diag(Var->getLocation(), diag::note_previous_decl)
17014              << Var->getDeclName();
17015           Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
17016         } else
17017           diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
17018       }
17019       return true;
17020     }
17021 
17022     // Try to capture variable-length arrays types.
17023     if (Var->getType()->isVariablyModifiedType()) {
17024       // We're going to walk down into the type and look for VLA
17025       // expressions.
17026       QualType QTy = Var->getType();
17027       if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
17028         QTy = PVD->getOriginalType();
17029       captureVariablyModifiedType(Context, QTy, CSI);
17030     }
17031 
17032     if (getLangOpts().OpenMP) {
17033       if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
17034         // OpenMP private variables should not be captured in outer scope, so
17035         // just break here. Similarly, global variables that are captured in a
17036         // target region should not be captured outside the scope of the region.
17037         if (RSI->CapRegionKind == CR_OpenMP) {
17038           OpenMPClauseKind IsOpenMPPrivateDecl = isOpenMPPrivateDecl(
17039               Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel);
17040           // If the variable is private (i.e. not captured) and has variably
17041           // modified type, we still need to capture the type for correct
17042           // codegen in all regions, associated with the construct. Currently,
17043           // it is captured in the innermost captured region only.
17044           if (IsOpenMPPrivateDecl != OMPC_unknown &&
17045               Var->getType()->isVariablyModifiedType()) {
17046             QualType QTy = Var->getType();
17047             if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
17048               QTy = PVD->getOriginalType();
17049             for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel);
17050                  I < E; ++I) {
17051               auto *OuterRSI = cast<CapturedRegionScopeInfo>(
17052                   FunctionScopes[FunctionScopesIndex - I]);
17053               assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel &&
17054                      "Wrong number of captured regions associated with the "
17055                      "OpenMP construct.");
17056               captureVariablyModifiedType(Context, QTy, OuterRSI);
17057             }
17058           }
17059           bool IsTargetCap =
17060               IsOpenMPPrivateDecl != OMPC_private &&
17061               isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel,
17062                                          RSI->OpenMPCaptureLevel);
17063           // Do not capture global if it is not privatized in outer regions.
17064           bool IsGlobalCap =
17065               IsGlobal && isOpenMPGlobalCapturedDecl(Var, RSI->OpenMPLevel,
17066                                                      RSI->OpenMPCaptureLevel);
17067 
17068           // When we detect target captures we are looking from inside the
17069           // target region, therefore we need to propagate the capture from the
17070           // enclosing region. Therefore, the capture is not initially nested.
17071           if (IsTargetCap)
17072             adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel);
17073 
17074           if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private ||
17075               (IsGlobal && !IsGlobalCap)) {
17076             Nested = !IsTargetCap;
17077             DeclRefType = DeclRefType.getUnqualifiedType();
17078             CaptureType = Context.getLValueReferenceType(DeclRefType);
17079             break;
17080           }
17081         }
17082       }
17083     }
17084     if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
17085       // No capture-default, and this is not an explicit capture
17086       // so cannot capture this variable.
17087       if (BuildAndDiagnose) {
17088         Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
17089         Diag(Var->getLocation(), diag::note_previous_decl)
17090           << Var->getDeclName();
17091         if (cast<LambdaScopeInfo>(CSI)->Lambda)
17092           Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getBeginLoc(),
17093                diag::note_lambda_decl);
17094         // FIXME: If we error out because an outer lambda can not implicitly
17095         // capture a variable that an inner lambda explicitly captures, we
17096         // should have the inner lambda do the explicit capture - because
17097         // it makes for cleaner diagnostics later.  This would purely be done
17098         // so that the diagnostic does not misleadingly claim that a variable
17099         // can not be captured by a lambda implicitly even though it is captured
17100         // explicitly.  Suggestion:
17101         //  - create const bool VariableCaptureWasInitiallyExplicit = Explicit
17102         //    at the function head
17103         //  - cache the StartingDeclContext - this must be a lambda
17104         //  - captureInLambda in the innermost lambda the variable.
17105       }
17106       return true;
17107     }
17108 
17109     FunctionScopesIndex--;
17110     DC = ParentDC;
17111     Explicit = false;
17112   } while (!VarDC->Equals(DC));
17113 
17114   // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
17115   // computing the type of the capture at each step, checking type-specific
17116   // requirements, and adding captures if requested.
17117   // If the variable had already been captured previously, we start capturing
17118   // at the lambda nested within that one.
17119   bool Invalid = false;
17120   for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
17121        ++I) {
17122     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
17123 
17124     // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
17125     // certain types of variables (unnamed, variably modified types etc.)
17126     // so check for eligibility.
17127     if (!Invalid)
17128       Invalid =
17129           !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this);
17130 
17131     // After encountering an error, if we're actually supposed to capture, keep
17132     // capturing in nested contexts to suppress any follow-on diagnostics.
17133     if (Invalid && !BuildAndDiagnose)
17134       return true;
17135 
17136     if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
17137       Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
17138                                DeclRefType, Nested, *this, Invalid);
17139       Nested = true;
17140     } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
17141       Invalid = !captureInCapturedRegion(RSI, Var, ExprLoc, BuildAndDiagnose,
17142                                          CaptureType, DeclRefType, Nested,
17143                                          *this, Invalid);
17144       Nested = true;
17145     } else {
17146       LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
17147       Invalid =
17148           !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
17149                            DeclRefType, Nested, Kind, EllipsisLoc,
17150                            /*IsTopScope*/ I == N - 1, *this, Invalid);
17151       Nested = true;
17152     }
17153 
17154     if (Invalid && !BuildAndDiagnose)
17155       return true;
17156   }
17157   return Invalid;
17158 }
17159 
17160 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
17161                               TryCaptureKind Kind, SourceLocation EllipsisLoc) {
17162   QualType CaptureType;
17163   QualType DeclRefType;
17164   return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
17165                             /*BuildAndDiagnose=*/true, CaptureType,
17166                             DeclRefType, nullptr);
17167 }
17168 
17169 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
17170   QualType CaptureType;
17171   QualType DeclRefType;
17172   return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
17173                              /*BuildAndDiagnose=*/false, CaptureType,
17174                              DeclRefType, nullptr);
17175 }
17176 
17177 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
17178   QualType CaptureType;
17179   QualType DeclRefType;
17180 
17181   // Determine whether we can capture this variable.
17182   if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
17183                          /*BuildAndDiagnose=*/false, CaptureType,
17184                          DeclRefType, nullptr))
17185     return QualType();
17186 
17187   return DeclRefType;
17188 }
17189 
17190 namespace {
17191 // Helper to copy the template arguments from a DeclRefExpr or MemberExpr.
17192 // The produced TemplateArgumentListInfo* points to data stored within this
17193 // object, so should only be used in contexts where the pointer will not be
17194 // used after the CopiedTemplateArgs object is destroyed.
17195 class CopiedTemplateArgs {
17196   bool HasArgs;
17197   TemplateArgumentListInfo TemplateArgStorage;
17198 public:
17199   template<typename RefExpr>
17200   CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) {
17201     if (HasArgs)
17202       E->copyTemplateArgumentsInto(TemplateArgStorage);
17203   }
17204   operator TemplateArgumentListInfo*()
17205 #ifdef __has_cpp_attribute
17206 #if __has_cpp_attribute(clang::lifetimebound)
17207   [[clang::lifetimebound]]
17208 #endif
17209 #endif
17210   {
17211     return HasArgs ? &TemplateArgStorage : nullptr;
17212   }
17213 };
17214 }
17215 
17216 /// Walk the set of potential results of an expression and mark them all as
17217 /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason.
17218 ///
17219 /// \return A new expression if we found any potential results, ExprEmpty() if
17220 ///         not, and ExprError() if we diagnosed an error.
17221 static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E,
17222                                                       NonOdrUseReason NOUR) {
17223   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
17224   // an object that satisfies the requirements for appearing in a
17225   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
17226   // is immediately applied."  This function handles the lvalue-to-rvalue
17227   // conversion part.
17228   //
17229   // If we encounter a node that claims to be an odr-use but shouldn't be, we
17230   // transform it into the relevant kind of non-odr-use node and rebuild the
17231   // tree of nodes leading to it.
17232   //
17233   // This is a mini-TreeTransform that only transforms a restricted subset of
17234   // nodes (and only certain operands of them).
17235 
17236   // Rebuild a subexpression.
17237   auto Rebuild = [&](Expr *Sub) {
17238     return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR);
17239   };
17240 
17241   // Check whether a potential result satisfies the requirements of NOUR.
17242   auto IsPotentialResultOdrUsed = [&](NamedDecl *D) {
17243     // Any entity other than a VarDecl is always odr-used whenever it's named
17244     // in a potentially-evaluated expression.
17245     auto *VD = dyn_cast<VarDecl>(D);
17246     if (!VD)
17247       return true;
17248 
17249     // C++2a [basic.def.odr]p4:
17250     //   A variable x whose name appears as a potentially-evalauted expression
17251     //   e is odr-used by e unless
17252     //   -- x is a reference that is usable in constant expressions, or
17253     //   -- x is a variable of non-reference type that is usable in constant
17254     //      expressions and has no mutable subobjects, and e is an element of
17255     //      the set of potential results of an expression of
17256     //      non-volatile-qualified non-class type to which the lvalue-to-rvalue
17257     //      conversion is applied, or
17258     //   -- x is a variable of non-reference type, and e is an element of the
17259     //      set of potential results of a discarded-value expression to which
17260     //      the lvalue-to-rvalue conversion is not applied
17261     //
17262     // We check the first bullet and the "potentially-evaluated" condition in
17263     // BuildDeclRefExpr. We check the type requirements in the second bullet
17264     // in CheckLValueToRValueConversionOperand below.
17265     switch (NOUR) {
17266     case NOUR_None:
17267     case NOUR_Unevaluated:
17268       llvm_unreachable("unexpected non-odr-use-reason");
17269 
17270     case NOUR_Constant:
17271       // Constant references were handled when they were built.
17272       if (VD->getType()->isReferenceType())
17273         return true;
17274       if (auto *RD = VD->getType()->getAsCXXRecordDecl())
17275         if (RD->hasMutableFields())
17276           return true;
17277       if (!VD->isUsableInConstantExpressions(S.Context))
17278         return true;
17279       break;
17280 
17281     case NOUR_Discarded:
17282       if (VD->getType()->isReferenceType())
17283         return true;
17284       break;
17285     }
17286     return false;
17287   };
17288 
17289   // Mark that this expression does not constitute an odr-use.
17290   auto MarkNotOdrUsed = [&] {
17291     S.MaybeODRUseExprs.erase(E);
17292     if (LambdaScopeInfo *LSI = S.getCurLambda())
17293       LSI->markVariableExprAsNonODRUsed(E);
17294   };
17295 
17296   // C++2a [basic.def.odr]p2:
17297   //   The set of potential results of an expression e is defined as follows:
17298   switch (E->getStmtClass()) {
17299   //   -- If e is an id-expression, ...
17300   case Expr::DeclRefExprClass: {
17301     auto *DRE = cast<DeclRefExpr>(E);
17302     if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl()))
17303       break;
17304 
17305     // Rebuild as a non-odr-use DeclRefExpr.
17306     MarkNotOdrUsed();
17307     return DeclRefExpr::Create(
17308         S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(),
17309         DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(),
17310         DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(),
17311         DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR);
17312   }
17313 
17314   case Expr::FunctionParmPackExprClass: {
17315     auto *FPPE = cast<FunctionParmPackExpr>(E);
17316     // If any of the declarations in the pack is odr-used, then the expression
17317     // as a whole constitutes an odr-use.
17318     for (VarDecl *D : *FPPE)
17319       if (IsPotentialResultOdrUsed(D))
17320         return ExprEmpty();
17321 
17322     // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice,
17323     // nothing cares about whether we marked this as an odr-use, but it might
17324     // be useful for non-compiler tools.
17325     MarkNotOdrUsed();
17326     break;
17327   }
17328 
17329   //   -- If e is a subscripting operation with an array operand...
17330   case Expr::ArraySubscriptExprClass: {
17331     auto *ASE = cast<ArraySubscriptExpr>(E);
17332     Expr *OldBase = ASE->getBase()->IgnoreImplicit();
17333     if (!OldBase->getType()->isArrayType())
17334       break;
17335     ExprResult Base = Rebuild(OldBase);
17336     if (!Base.isUsable())
17337       return Base;
17338     Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS();
17339     Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS();
17340     SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored.
17341     return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS,
17342                                      ASE->getRBracketLoc());
17343   }
17344 
17345   case Expr::MemberExprClass: {
17346     auto *ME = cast<MemberExpr>(E);
17347     // -- If e is a class member access expression [...] naming a non-static
17348     //    data member...
17349     if (isa<FieldDecl>(ME->getMemberDecl())) {
17350       ExprResult Base = Rebuild(ME->getBase());
17351       if (!Base.isUsable())
17352         return Base;
17353       return MemberExpr::Create(
17354           S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(),
17355           ME->getQualifierLoc(), ME->getTemplateKeywordLoc(),
17356           ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(),
17357           CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(),
17358           ME->getObjectKind(), ME->isNonOdrUse());
17359     }
17360 
17361     if (ME->getMemberDecl()->isCXXInstanceMember())
17362       break;
17363 
17364     // -- If e is a class member access expression naming a static data member,
17365     //    ...
17366     if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl()))
17367       break;
17368 
17369     // Rebuild as a non-odr-use MemberExpr.
17370     MarkNotOdrUsed();
17371     return MemberExpr::Create(
17372         S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(),
17373         ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(),
17374         ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME),
17375         ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR);
17376     return ExprEmpty();
17377   }
17378 
17379   case Expr::BinaryOperatorClass: {
17380     auto *BO = cast<BinaryOperator>(E);
17381     Expr *LHS = BO->getLHS();
17382     Expr *RHS = BO->getRHS();
17383     // -- If e is a pointer-to-member expression of the form e1 .* e2 ...
17384     if (BO->getOpcode() == BO_PtrMemD) {
17385       ExprResult Sub = Rebuild(LHS);
17386       if (!Sub.isUsable())
17387         return Sub;
17388       LHS = Sub.get();
17389     //   -- If e is a comma expression, ...
17390     } else if (BO->getOpcode() == BO_Comma) {
17391       ExprResult Sub = Rebuild(RHS);
17392       if (!Sub.isUsable())
17393         return Sub;
17394       RHS = Sub.get();
17395     } else {
17396       break;
17397     }
17398     return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(),
17399                         LHS, RHS);
17400   }
17401 
17402   //   -- If e has the form (e1)...
17403   case Expr::ParenExprClass: {
17404     auto *PE = cast<ParenExpr>(E);
17405     ExprResult Sub = Rebuild(PE->getSubExpr());
17406     if (!Sub.isUsable())
17407       return Sub;
17408     return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get());
17409   }
17410 
17411   //   -- If e is a glvalue conditional expression, ...
17412   // We don't apply this to a binary conditional operator. FIXME: Should we?
17413   case Expr::ConditionalOperatorClass: {
17414     auto *CO = cast<ConditionalOperator>(E);
17415     ExprResult LHS = Rebuild(CO->getLHS());
17416     if (LHS.isInvalid())
17417       return ExprError();
17418     ExprResult RHS = Rebuild(CO->getRHS());
17419     if (RHS.isInvalid())
17420       return ExprError();
17421     if (!LHS.isUsable() && !RHS.isUsable())
17422       return ExprEmpty();
17423     if (!LHS.isUsable())
17424       LHS = CO->getLHS();
17425     if (!RHS.isUsable())
17426       RHS = CO->getRHS();
17427     return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(),
17428                                 CO->getCond(), LHS.get(), RHS.get());
17429   }
17430 
17431   // [Clang extension]
17432   //   -- If e has the form __extension__ e1...
17433   case Expr::UnaryOperatorClass: {
17434     auto *UO = cast<UnaryOperator>(E);
17435     if (UO->getOpcode() != UO_Extension)
17436       break;
17437     ExprResult Sub = Rebuild(UO->getSubExpr());
17438     if (!Sub.isUsable())
17439       return Sub;
17440     return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension,
17441                           Sub.get());
17442   }
17443 
17444   // [Clang extension]
17445   //   -- If e has the form _Generic(...), the set of potential results is the
17446   //      union of the sets of potential results of the associated expressions.
17447   case Expr::GenericSelectionExprClass: {
17448     auto *GSE = cast<GenericSelectionExpr>(E);
17449 
17450     SmallVector<Expr *, 4> AssocExprs;
17451     bool AnyChanged = false;
17452     for (Expr *OrigAssocExpr : GSE->getAssocExprs()) {
17453       ExprResult AssocExpr = Rebuild(OrigAssocExpr);
17454       if (AssocExpr.isInvalid())
17455         return ExprError();
17456       if (AssocExpr.isUsable()) {
17457         AssocExprs.push_back(AssocExpr.get());
17458         AnyChanged = true;
17459       } else {
17460         AssocExprs.push_back(OrigAssocExpr);
17461       }
17462     }
17463 
17464     return AnyChanged ? S.CreateGenericSelectionExpr(
17465                             GSE->getGenericLoc(), GSE->getDefaultLoc(),
17466                             GSE->getRParenLoc(), GSE->getControllingExpr(),
17467                             GSE->getAssocTypeSourceInfos(), AssocExprs)
17468                       : ExprEmpty();
17469   }
17470 
17471   // [Clang extension]
17472   //   -- If e has the form __builtin_choose_expr(...), the set of potential
17473   //      results is the union of the sets of potential results of the
17474   //      second and third subexpressions.
17475   case Expr::ChooseExprClass: {
17476     auto *CE = cast<ChooseExpr>(E);
17477 
17478     ExprResult LHS = Rebuild(CE->getLHS());
17479     if (LHS.isInvalid())
17480       return ExprError();
17481 
17482     ExprResult RHS = Rebuild(CE->getLHS());
17483     if (RHS.isInvalid())
17484       return ExprError();
17485 
17486     if (!LHS.get() && !RHS.get())
17487       return ExprEmpty();
17488     if (!LHS.isUsable())
17489       LHS = CE->getLHS();
17490     if (!RHS.isUsable())
17491       RHS = CE->getRHS();
17492 
17493     return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(),
17494                              RHS.get(), CE->getRParenLoc());
17495   }
17496 
17497   // Step through non-syntactic nodes.
17498   case Expr::ConstantExprClass: {
17499     auto *CE = cast<ConstantExpr>(E);
17500     ExprResult Sub = Rebuild(CE->getSubExpr());
17501     if (!Sub.isUsable())
17502       return Sub;
17503     return ConstantExpr::Create(S.Context, Sub.get());
17504   }
17505 
17506   // We could mostly rely on the recursive rebuilding to rebuild implicit
17507   // casts, but not at the top level, so rebuild them here.
17508   case Expr::ImplicitCastExprClass: {
17509     auto *ICE = cast<ImplicitCastExpr>(E);
17510     // Only step through the narrow set of cast kinds we expect to encounter.
17511     // Anything else suggests we've left the region in which potential results
17512     // can be found.
17513     switch (ICE->getCastKind()) {
17514     case CK_NoOp:
17515     case CK_DerivedToBase:
17516     case CK_UncheckedDerivedToBase: {
17517       ExprResult Sub = Rebuild(ICE->getSubExpr());
17518       if (!Sub.isUsable())
17519         return Sub;
17520       CXXCastPath Path(ICE->path());
17521       return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(),
17522                                  ICE->getValueKind(), &Path);
17523     }
17524 
17525     default:
17526       break;
17527     }
17528     break;
17529   }
17530 
17531   default:
17532     break;
17533   }
17534 
17535   // Can't traverse through this node. Nothing to do.
17536   return ExprEmpty();
17537 }
17538 
17539 ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) {
17540   // Check whether the operand is or contains an object of non-trivial C union
17541   // type.
17542   if (E->getType().isVolatileQualified() &&
17543       (E->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
17544        E->getType().hasNonTrivialToPrimitiveCopyCUnion()))
17545     checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
17546                           Sema::NTCUC_LValueToRValueVolatile,
17547                           NTCUK_Destruct|NTCUK_Copy);
17548 
17549   // C++2a [basic.def.odr]p4:
17550   //   [...] an expression of non-volatile-qualified non-class type to which
17551   //   the lvalue-to-rvalue conversion is applied [...]
17552   if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>())
17553     return E;
17554 
17555   ExprResult Result =
17556       rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant);
17557   if (Result.isInvalid())
17558     return ExprError();
17559   return Result.get() ? Result : E;
17560 }
17561 
17562 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
17563   Res = CorrectDelayedTyposInExpr(Res);
17564 
17565   if (!Res.isUsable())
17566     return Res;
17567 
17568   // If a constant-expression is a reference to a variable where we delay
17569   // deciding whether it is an odr-use, just assume we will apply the
17570   // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
17571   // (a non-type template argument), we have special handling anyway.
17572   return CheckLValueToRValueConversionOperand(Res.get());
17573 }
17574 
17575 void Sema::CleanupVarDeclMarking() {
17576   // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
17577   // call.
17578   MaybeODRUseExprSet LocalMaybeODRUseExprs;
17579   std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs);
17580 
17581   for (Expr *E : LocalMaybeODRUseExprs) {
17582     if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
17583       MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()),
17584                          DRE->getLocation(), *this);
17585     } else if (auto *ME = dyn_cast<MemberExpr>(E)) {
17586       MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(),
17587                          *this);
17588     } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) {
17589       for (VarDecl *VD : *FP)
17590         MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this);
17591     } else {
17592       llvm_unreachable("Unexpected expression");
17593     }
17594   }
17595 
17596   assert(MaybeODRUseExprs.empty() &&
17597          "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?");
17598 }
17599 
17600 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
17601                                     VarDecl *Var, Expr *E) {
17602   assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||
17603           isa<FunctionParmPackExpr>(E)) &&
17604          "Invalid Expr argument to DoMarkVarDeclReferenced");
17605   Var->setReferenced();
17606 
17607   if (Var->isInvalidDecl())
17608     return;
17609 
17610   auto *MSI = Var->getMemberSpecializationInfo();
17611   TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind()
17612                                        : Var->getTemplateSpecializationKind();
17613 
17614   OdrUseContext OdrUse = isOdrUseContext(SemaRef);
17615   bool UsableInConstantExpr =
17616       Var->mightBeUsableInConstantExpressions(SemaRef.Context);
17617 
17618   // C++20 [expr.const]p12:
17619   //   A variable [...] is needed for constant evaluation if it is [...] a
17620   //   variable whose name appears as a potentially constant evaluated
17621   //   expression that is either a contexpr variable or is of non-volatile
17622   //   const-qualified integral type or of reference type
17623   bool NeededForConstantEvaluation =
17624       isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr;
17625 
17626   bool NeedDefinition =
17627       OdrUse == OdrUseContext::Used || NeededForConstantEvaluation;
17628 
17629   VarTemplateSpecializationDecl *VarSpec =
17630       dyn_cast<VarTemplateSpecializationDecl>(Var);
17631   assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
17632          "Can't instantiate a partial template specialization.");
17633 
17634   // If this might be a member specialization of a static data member, check
17635   // the specialization is visible. We already did the checks for variable
17636   // template specializations when we created them.
17637   if (NeedDefinition && TSK != TSK_Undeclared &&
17638       !isa<VarTemplateSpecializationDecl>(Var))
17639     SemaRef.checkSpecializationVisibility(Loc, Var);
17640 
17641   // Perform implicit instantiation of static data members, static data member
17642   // templates of class templates, and variable template specializations. Delay
17643   // instantiations of variable templates, except for those that could be used
17644   // in a constant expression.
17645   if (NeedDefinition && isTemplateInstantiation(TSK)) {
17646     // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
17647     // instantiation declaration if a variable is usable in a constant
17648     // expression (among other cases).
17649     bool TryInstantiating =
17650         TSK == TSK_ImplicitInstantiation ||
17651         (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
17652 
17653     if (TryInstantiating) {
17654       SourceLocation PointOfInstantiation =
17655           MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation();
17656       bool FirstInstantiation = PointOfInstantiation.isInvalid();
17657       if (FirstInstantiation) {
17658         PointOfInstantiation = Loc;
17659         if (MSI)
17660           MSI->setPointOfInstantiation(PointOfInstantiation);
17661         else
17662           Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
17663       }
17664 
17665       bool InstantiationDependent = false;
17666       bool IsNonDependent =
17667           VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
17668                         VarSpec->getTemplateArgsInfo(), InstantiationDependent)
17669                   : true;
17670 
17671       // Do not instantiate specializations that are still type-dependent.
17672       if (IsNonDependent) {
17673         if (UsableInConstantExpr) {
17674           // Do not defer instantiations of variables that could be used in a
17675           // constant expression.
17676           SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] {
17677             SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
17678           });
17679         } else if (FirstInstantiation ||
17680                    isa<VarTemplateSpecializationDecl>(Var)) {
17681           // FIXME: For a specialization of a variable template, we don't
17682           // distinguish between "declaration and type implicitly instantiated"
17683           // and "implicit instantiation of definition requested", so we have
17684           // no direct way to avoid enqueueing the pending instantiation
17685           // multiple times.
17686           SemaRef.PendingInstantiations
17687               .push_back(std::make_pair(Var, PointOfInstantiation));
17688         }
17689       }
17690     }
17691   }
17692 
17693   // C++2a [basic.def.odr]p4:
17694   //   A variable x whose name appears as a potentially-evaluated expression e
17695   //   is odr-used by e unless
17696   //   -- x is a reference that is usable in constant expressions
17697   //   -- x is a variable of non-reference type that is usable in constant
17698   //      expressions and has no mutable subobjects [FIXME], and e is an
17699   //      element of the set of potential results of an expression of
17700   //      non-volatile-qualified non-class type to which the lvalue-to-rvalue
17701   //      conversion is applied
17702   //   -- x is a variable of non-reference type, and e is an element of the set
17703   //      of potential results of a discarded-value expression to which the
17704   //      lvalue-to-rvalue conversion is not applied [FIXME]
17705   //
17706   // We check the first part of the second bullet here, and
17707   // Sema::CheckLValueToRValueConversionOperand deals with the second part.
17708   // FIXME: To get the third bullet right, we need to delay this even for
17709   // variables that are not usable in constant expressions.
17710 
17711   // If we already know this isn't an odr-use, there's nothing more to do.
17712   if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E))
17713     if (DRE->isNonOdrUse())
17714       return;
17715   if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E))
17716     if (ME->isNonOdrUse())
17717       return;
17718 
17719   switch (OdrUse) {
17720   case OdrUseContext::None:
17721     assert((!E || isa<FunctionParmPackExpr>(E)) &&
17722            "missing non-odr-use marking for unevaluated decl ref");
17723     break;
17724 
17725   case OdrUseContext::FormallyOdrUsed:
17726     // FIXME: Ignoring formal odr-uses results in incorrect lambda capture
17727     // behavior.
17728     break;
17729 
17730   case OdrUseContext::Used:
17731     // If we might later find that this expression isn't actually an odr-use,
17732     // delay the marking.
17733     if (E && Var->isUsableInConstantExpressions(SemaRef.Context))
17734       SemaRef.MaybeODRUseExprs.insert(E);
17735     else
17736       MarkVarDeclODRUsed(Var, Loc, SemaRef);
17737     break;
17738 
17739   case OdrUseContext::Dependent:
17740     // If this is a dependent context, we don't need to mark variables as
17741     // odr-used, but we may still need to track them for lambda capture.
17742     // FIXME: Do we also need to do this inside dependent typeid expressions
17743     // (which are modeled as unevaluated at this point)?
17744     const bool RefersToEnclosingScope =
17745         (SemaRef.CurContext != Var->getDeclContext() &&
17746          Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
17747     if (RefersToEnclosingScope) {
17748       LambdaScopeInfo *const LSI =
17749           SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
17750       if (LSI && (!LSI->CallOperator ||
17751                   !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
17752         // If a variable could potentially be odr-used, defer marking it so
17753         // until we finish analyzing the full expression for any
17754         // lvalue-to-rvalue
17755         // or discarded value conversions that would obviate odr-use.
17756         // Add it to the list of potential captures that will be analyzed
17757         // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
17758         // unless the variable is a reference that was initialized by a constant
17759         // expression (this will never need to be captured or odr-used).
17760         //
17761         // FIXME: We can simplify this a lot after implementing P0588R1.
17762         assert(E && "Capture variable should be used in an expression.");
17763         if (!Var->getType()->isReferenceType() ||
17764             !Var->isUsableInConstantExpressions(SemaRef.Context))
17765           LSI->addPotentialCapture(E->IgnoreParens());
17766       }
17767     }
17768     break;
17769   }
17770 }
17771 
17772 /// Mark a variable referenced, and check whether it is odr-used
17773 /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
17774 /// used directly for normal expressions referring to VarDecl.
17775 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
17776   DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
17777 }
17778 
17779 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
17780                                Decl *D, Expr *E, bool MightBeOdrUse) {
17781   if (SemaRef.isInOpenMPDeclareTargetContext())
17782     SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
17783 
17784   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
17785     DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
17786     return;
17787   }
17788 
17789   SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
17790 
17791   // If this is a call to a method via a cast, also mark the method in the
17792   // derived class used in case codegen can devirtualize the call.
17793   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
17794   if (!ME)
17795     return;
17796   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
17797   if (!MD)
17798     return;
17799   // Only attempt to devirtualize if this is truly a virtual call.
17800   bool IsVirtualCall = MD->isVirtual() &&
17801                           ME->performsVirtualDispatch(SemaRef.getLangOpts());
17802   if (!IsVirtualCall)
17803     return;
17804 
17805   // If it's possible to devirtualize the call, mark the called function
17806   // referenced.
17807   CXXMethodDecl *DM = MD->getDevirtualizedMethod(
17808       ME->getBase(), SemaRef.getLangOpts().AppleKext);
17809   if (DM)
17810     SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
17811 }
17812 
17813 /// Perform reference-marking and odr-use handling for a DeclRefExpr.
17814 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) {
17815   // TODO: update this with DR# once a defect report is filed.
17816   // C++11 defect. The address of a pure member should not be an ODR use, even
17817   // if it's a qualified reference.
17818   bool OdrUse = true;
17819   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
17820     if (Method->isVirtual() &&
17821         !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
17822       OdrUse = false;
17823 
17824   if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl()))
17825     if (!isConstantEvaluated() && FD->isConsteval() &&
17826         !RebuildingImmediateInvocation)
17827       ExprEvalContexts.back().ReferenceToConsteval.insert(E);
17828   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
17829 }
17830 
17831 /// Perform reference-marking and odr-use handling for a MemberExpr.
17832 void Sema::MarkMemberReferenced(MemberExpr *E) {
17833   // C++11 [basic.def.odr]p2:
17834   //   A non-overloaded function whose name appears as a potentially-evaluated
17835   //   expression or a member of a set of candidate functions, if selected by
17836   //   overload resolution when referred to from a potentially-evaluated
17837   //   expression, is odr-used, unless it is a pure virtual function and its
17838   //   name is not explicitly qualified.
17839   bool MightBeOdrUse = true;
17840   if (E->performsVirtualDispatch(getLangOpts())) {
17841     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
17842       if (Method->isPure())
17843         MightBeOdrUse = false;
17844   }
17845   SourceLocation Loc =
17846       E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
17847   MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse);
17848 }
17849 
17850 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr.
17851 void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) {
17852   for (VarDecl *VD : *E)
17853     MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true);
17854 }
17855 
17856 /// Perform marking for a reference to an arbitrary declaration.  It
17857 /// marks the declaration referenced, and performs odr-use checking for
17858 /// functions and variables. This method should not be used when building a
17859 /// normal expression which refers to a variable.
17860 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
17861                                  bool MightBeOdrUse) {
17862   if (MightBeOdrUse) {
17863     if (auto *VD = dyn_cast<VarDecl>(D)) {
17864       MarkVariableReferenced(Loc, VD);
17865       return;
17866     }
17867   }
17868   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
17869     MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
17870     return;
17871   }
17872   D->setReferenced();
17873 }
17874 
17875 namespace {
17876   // Mark all of the declarations used by a type as referenced.
17877   // FIXME: Not fully implemented yet! We need to have a better understanding
17878   // of when we're entering a context we should not recurse into.
17879   // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
17880   // TreeTransforms rebuilding the type in a new context. Rather than
17881   // duplicating the TreeTransform logic, we should consider reusing it here.
17882   // Currently that causes problems when rebuilding LambdaExprs.
17883   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
17884     Sema &S;
17885     SourceLocation Loc;
17886 
17887   public:
17888     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
17889 
17890     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
17891 
17892     bool TraverseTemplateArgument(const TemplateArgument &Arg);
17893   };
17894 }
17895 
17896 bool MarkReferencedDecls::TraverseTemplateArgument(
17897     const TemplateArgument &Arg) {
17898   {
17899     // A non-type template argument is a constant-evaluated context.
17900     EnterExpressionEvaluationContext Evaluated(
17901         S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
17902     if (Arg.getKind() == TemplateArgument::Declaration) {
17903       if (Decl *D = Arg.getAsDecl())
17904         S.MarkAnyDeclReferenced(Loc, D, true);
17905     } else if (Arg.getKind() == TemplateArgument::Expression) {
17906       S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false);
17907     }
17908   }
17909 
17910   return Inherited::TraverseTemplateArgument(Arg);
17911 }
17912 
17913 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
17914   MarkReferencedDecls Marker(*this, Loc);
17915   Marker.TraverseType(T);
17916 }
17917 
17918 namespace {
17919 /// Helper class that marks all of the declarations referenced by
17920 /// potentially-evaluated subexpressions as "referenced".
17921 class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> {
17922 public:
17923   typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited;
17924   bool SkipLocalVariables;
17925 
17926   EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
17927       : Inherited(S), SkipLocalVariables(SkipLocalVariables) {}
17928 
17929   void visitUsedDecl(SourceLocation Loc, Decl *D) {
17930     S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D));
17931   }
17932 
17933   void VisitDeclRefExpr(DeclRefExpr *E) {
17934     // If we were asked not to visit local variables, don't.
17935     if (SkipLocalVariables) {
17936       if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
17937         if (VD->hasLocalStorage())
17938           return;
17939     }
17940     S.MarkDeclRefReferenced(E);
17941   }
17942 
17943   void VisitMemberExpr(MemberExpr *E) {
17944     S.MarkMemberReferenced(E);
17945     Visit(E->getBase());
17946   }
17947 };
17948 } // namespace
17949 
17950 /// Mark any declarations that appear within this expression or any
17951 /// potentially-evaluated subexpressions as "referenced".
17952 ///
17953 /// \param SkipLocalVariables If true, don't mark local variables as
17954 /// 'referenced'.
17955 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
17956                                             bool SkipLocalVariables) {
17957   EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
17958 }
17959 
17960 /// Emit a diagnostic that describes an effect on the run-time behavior
17961 /// of the program being compiled.
17962 ///
17963 /// This routine emits the given diagnostic when the code currently being
17964 /// type-checked is "potentially evaluated", meaning that there is a
17965 /// possibility that the code will actually be executable. Code in sizeof()
17966 /// expressions, code used only during overload resolution, etc., are not
17967 /// potentially evaluated. This routine will suppress such diagnostics or,
17968 /// in the absolutely nutty case of potentially potentially evaluated
17969 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
17970 /// later.
17971 ///
17972 /// This routine should be used for all diagnostics that describe the run-time
17973 /// behavior of a program, such as passing a non-POD value through an ellipsis.
17974 /// Failure to do so will likely result in spurious diagnostics or failures
17975 /// during overload resolution or within sizeof/alignof/typeof/typeid.
17976 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts,
17977                                const PartialDiagnostic &PD) {
17978   switch (ExprEvalContexts.back().Context) {
17979   case ExpressionEvaluationContext::Unevaluated:
17980   case ExpressionEvaluationContext::UnevaluatedList:
17981   case ExpressionEvaluationContext::UnevaluatedAbstract:
17982   case ExpressionEvaluationContext::DiscardedStatement:
17983     // The argument will never be evaluated, so don't complain.
17984     break;
17985 
17986   case ExpressionEvaluationContext::ConstantEvaluated:
17987     // Relevant diagnostics should be produced by constant evaluation.
17988     break;
17989 
17990   case ExpressionEvaluationContext::PotentiallyEvaluated:
17991   case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
17992     if (!Stmts.empty() && getCurFunctionOrMethodDecl()) {
17993       FunctionScopes.back()->PossiblyUnreachableDiags.
17994         push_back(sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
17995       return true;
17996     }
17997 
17998     // The initializer of a constexpr variable or of the first declaration of a
17999     // static data member is not syntactically a constant evaluated constant,
18000     // but nonetheless is always required to be a constant expression, so we
18001     // can skip diagnosing.
18002     // FIXME: Using the mangling context here is a hack.
18003     if (auto *VD = dyn_cast_or_null<VarDecl>(
18004             ExprEvalContexts.back().ManglingContextDecl)) {
18005       if (VD->isConstexpr() ||
18006           (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline()))
18007         break;
18008       // FIXME: For any other kind of variable, we should build a CFG for its
18009       // initializer and check whether the context in question is reachable.
18010     }
18011 
18012     Diag(Loc, PD);
18013     return true;
18014   }
18015 
18016   return false;
18017 }
18018 
18019 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
18020                                const PartialDiagnostic &PD) {
18021   return DiagRuntimeBehavior(
18022       Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD);
18023 }
18024 
18025 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
18026                                CallExpr *CE, FunctionDecl *FD) {
18027   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
18028     return false;
18029 
18030   // If we're inside a decltype's expression, don't check for a valid return
18031   // type or construct temporaries until we know whether this is the last call.
18032   if (ExprEvalContexts.back().ExprContext ==
18033       ExpressionEvaluationContextRecord::EK_Decltype) {
18034     ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
18035     return false;
18036   }
18037 
18038   class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
18039     FunctionDecl *FD;
18040     CallExpr *CE;
18041 
18042   public:
18043     CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
18044       : FD(FD), CE(CE) { }
18045 
18046     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
18047       if (!FD) {
18048         S.Diag(Loc, diag::err_call_incomplete_return)
18049           << T << CE->getSourceRange();
18050         return;
18051       }
18052 
18053       S.Diag(Loc, diag::err_call_function_incomplete_return)
18054         << CE->getSourceRange() << FD->getDeclName() << T;
18055       S.Diag(FD->getLocation(), diag::note_entity_declared_at)
18056           << FD->getDeclName();
18057     }
18058   } Diagnoser(FD, CE);
18059 
18060   if (RequireCompleteType(Loc, ReturnType, Diagnoser))
18061     return true;
18062 
18063   return false;
18064 }
18065 
18066 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
18067 // will prevent this condition from triggering, which is what we want.
18068 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
18069   SourceLocation Loc;
18070 
18071   unsigned diagnostic = diag::warn_condition_is_assignment;
18072   bool IsOrAssign = false;
18073 
18074   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
18075     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
18076       return;
18077 
18078     IsOrAssign = Op->getOpcode() == BO_OrAssign;
18079 
18080     // Greylist some idioms by putting them into a warning subcategory.
18081     if (ObjCMessageExpr *ME
18082           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
18083       Selector Sel = ME->getSelector();
18084 
18085       // self = [<foo> init...]
18086       if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
18087         diagnostic = diag::warn_condition_is_idiomatic_assignment;
18088 
18089       // <foo> = [<bar> nextObject]
18090       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
18091         diagnostic = diag::warn_condition_is_idiomatic_assignment;
18092     }
18093 
18094     Loc = Op->getOperatorLoc();
18095   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
18096     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
18097       return;
18098 
18099     IsOrAssign = Op->getOperator() == OO_PipeEqual;
18100     Loc = Op->getOperatorLoc();
18101   } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
18102     return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
18103   else {
18104     // Not an assignment.
18105     return;
18106   }
18107 
18108   Diag(Loc, diagnostic) << E->getSourceRange();
18109 
18110   SourceLocation Open = E->getBeginLoc();
18111   SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
18112   Diag(Loc, diag::note_condition_assign_silence)
18113         << FixItHint::CreateInsertion(Open, "(")
18114         << FixItHint::CreateInsertion(Close, ")");
18115 
18116   if (IsOrAssign)
18117     Diag(Loc, diag::note_condition_or_assign_to_comparison)
18118       << FixItHint::CreateReplacement(Loc, "!=");
18119   else
18120     Diag(Loc, diag::note_condition_assign_to_comparison)
18121       << FixItHint::CreateReplacement(Loc, "==");
18122 }
18123 
18124 /// Redundant parentheses over an equality comparison can indicate
18125 /// that the user intended an assignment used as condition.
18126 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
18127   // Don't warn if the parens came from a macro.
18128   SourceLocation parenLoc = ParenE->getBeginLoc();
18129   if (parenLoc.isInvalid() || parenLoc.isMacroID())
18130     return;
18131   // Don't warn for dependent expressions.
18132   if (ParenE->isTypeDependent())
18133     return;
18134 
18135   Expr *E = ParenE->IgnoreParens();
18136 
18137   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
18138     if (opE->getOpcode() == BO_EQ &&
18139         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
18140                                                            == Expr::MLV_Valid) {
18141       SourceLocation Loc = opE->getOperatorLoc();
18142 
18143       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
18144       SourceRange ParenERange = ParenE->getSourceRange();
18145       Diag(Loc, diag::note_equality_comparison_silence)
18146         << FixItHint::CreateRemoval(ParenERange.getBegin())
18147         << FixItHint::CreateRemoval(ParenERange.getEnd());
18148       Diag(Loc, diag::note_equality_comparison_to_assign)
18149         << FixItHint::CreateReplacement(Loc, "=");
18150     }
18151 }
18152 
18153 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
18154                                        bool IsConstexpr) {
18155   DiagnoseAssignmentAsCondition(E);
18156   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
18157     DiagnoseEqualityWithExtraParens(parenE);
18158 
18159   ExprResult result = CheckPlaceholderExpr(E);
18160   if (result.isInvalid()) return ExprError();
18161   E = result.get();
18162 
18163   if (!E->isTypeDependent()) {
18164     if (getLangOpts().CPlusPlus)
18165       return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
18166 
18167     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
18168     if (ERes.isInvalid())
18169       return ExprError();
18170     E = ERes.get();
18171 
18172     QualType T = E->getType();
18173     if (!T->isScalarType()) { // C99 6.8.4.1p1
18174       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
18175         << T << E->getSourceRange();
18176       return ExprError();
18177     }
18178     CheckBoolLikeConversion(E, Loc);
18179   }
18180 
18181   return E;
18182 }
18183 
18184 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
18185                                            Expr *SubExpr, ConditionKind CK) {
18186   // Empty conditions are valid in for-statements.
18187   if (!SubExpr)
18188     return ConditionResult();
18189 
18190   ExprResult Cond;
18191   switch (CK) {
18192   case ConditionKind::Boolean:
18193     Cond = CheckBooleanCondition(Loc, SubExpr);
18194     break;
18195 
18196   case ConditionKind::ConstexprIf:
18197     Cond = CheckBooleanCondition(Loc, SubExpr, true);
18198     break;
18199 
18200   case ConditionKind::Switch:
18201     Cond = CheckSwitchCondition(Loc, SubExpr);
18202     break;
18203   }
18204   if (Cond.isInvalid())
18205     return ConditionError();
18206 
18207   // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
18208   FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
18209   if (!FullExpr.get())
18210     return ConditionError();
18211 
18212   return ConditionResult(*this, nullptr, FullExpr,
18213                          CK == ConditionKind::ConstexprIf);
18214 }
18215 
18216 namespace {
18217   /// A visitor for rebuilding a call to an __unknown_any expression
18218   /// to have an appropriate type.
18219   struct RebuildUnknownAnyFunction
18220     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
18221 
18222     Sema &S;
18223 
18224     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
18225 
18226     ExprResult VisitStmt(Stmt *S) {
18227       llvm_unreachable("unexpected statement!");
18228     }
18229 
18230     ExprResult VisitExpr(Expr *E) {
18231       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
18232         << E->getSourceRange();
18233       return ExprError();
18234     }
18235 
18236     /// Rebuild an expression which simply semantically wraps another
18237     /// expression which it shares the type and value kind of.
18238     template <class T> ExprResult rebuildSugarExpr(T *E) {
18239       ExprResult SubResult = Visit(E->getSubExpr());
18240       if (SubResult.isInvalid()) return ExprError();
18241 
18242       Expr *SubExpr = SubResult.get();
18243       E->setSubExpr(SubExpr);
18244       E->setType(SubExpr->getType());
18245       E->setValueKind(SubExpr->getValueKind());
18246       assert(E->getObjectKind() == OK_Ordinary);
18247       return E;
18248     }
18249 
18250     ExprResult VisitParenExpr(ParenExpr *E) {
18251       return rebuildSugarExpr(E);
18252     }
18253 
18254     ExprResult VisitUnaryExtension(UnaryOperator *E) {
18255       return rebuildSugarExpr(E);
18256     }
18257 
18258     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
18259       ExprResult SubResult = Visit(E->getSubExpr());
18260       if (SubResult.isInvalid()) return ExprError();
18261 
18262       Expr *SubExpr = SubResult.get();
18263       E->setSubExpr(SubExpr);
18264       E->setType(S.Context.getPointerType(SubExpr->getType()));
18265       assert(E->getValueKind() == VK_RValue);
18266       assert(E->getObjectKind() == OK_Ordinary);
18267       return E;
18268     }
18269 
18270     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
18271       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
18272 
18273       E->setType(VD->getType());
18274 
18275       assert(E->getValueKind() == VK_RValue);
18276       if (S.getLangOpts().CPlusPlus &&
18277           !(isa<CXXMethodDecl>(VD) &&
18278             cast<CXXMethodDecl>(VD)->isInstance()))
18279         E->setValueKind(VK_LValue);
18280 
18281       return E;
18282     }
18283 
18284     ExprResult VisitMemberExpr(MemberExpr *E) {
18285       return resolveDecl(E, E->getMemberDecl());
18286     }
18287 
18288     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
18289       return resolveDecl(E, E->getDecl());
18290     }
18291   };
18292 }
18293 
18294 /// Given a function expression of unknown-any type, try to rebuild it
18295 /// to have a function type.
18296 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
18297   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
18298   if (Result.isInvalid()) return ExprError();
18299   return S.DefaultFunctionArrayConversion(Result.get());
18300 }
18301 
18302 namespace {
18303   /// A visitor for rebuilding an expression of type __unknown_anytype
18304   /// into one which resolves the type directly on the referring
18305   /// expression.  Strict preservation of the original source
18306   /// structure is not a goal.
18307   struct RebuildUnknownAnyExpr
18308     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
18309 
18310     Sema &S;
18311 
18312     /// The current destination type.
18313     QualType DestType;
18314 
18315     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
18316       : S(S), DestType(CastType) {}
18317 
18318     ExprResult VisitStmt(Stmt *S) {
18319       llvm_unreachable("unexpected statement!");
18320     }
18321 
18322     ExprResult VisitExpr(Expr *E) {
18323       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
18324         << E->getSourceRange();
18325       return ExprError();
18326     }
18327 
18328     ExprResult VisitCallExpr(CallExpr *E);
18329     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
18330 
18331     /// Rebuild an expression which simply semantically wraps another
18332     /// expression which it shares the type and value kind of.
18333     template <class T> ExprResult rebuildSugarExpr(T *E) {
18334       ExprResult SubResult = Visit(E->getSubExpr());
18335       if (SubResult.isInvalid()) return ExprError();
18336       Expr *SubExpr = SubResult.get();
18337       E->setSubExpr(SubExpr);
18338       E->setType(SubExpr->getType());
18339       E->setValueKind(SubExpr->getValueKind());
18340       assert(E->getObjectKind() == OK_Ordinary);
18341       return E;
18342     }
18343 
18344     ExprResult VisitParenExpr(ParenExpr *E) {
18345       return rebuildSugarExpr(E);
18346     }
18347 
18348     ExprResult VisitUnaryExtension(UnaryOperator *E) {
18349       return rebuildSugarExpr(E);
18350     }
18351 
18352     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
18353       const PointerType *Ptr = DestType->getAs<PointerType>();
18354       if (!Ptr) {
18355         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
18356           << E->getSourceRange();
18357         return ExprError();
18358       }
18359 
18360       if (isa<CallExpr>(E->getSubExpr())) {
18361         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
18362           << E->getSourceRange();
18363         return ExprError();
18364       }
18365 
18366       assert(E->getValueKind() == VK_RValue);
18367       assert(E->getObjectKind() == OK_Ordinary);
18368       E->setType(DestType);
18369 
18370       // Build the sub-expression as if it were an object of the pointee type.
18371       DestType = Ptr->getPointeeType();
18372       ExprResult SubResult = Visit(E->getSubExpr());
18373       if (SubResult.isInvalid()) return ExprError();
18374       E->setSubExpr(SubResult.get());
18375       return E;
18376     }
18377 
18378     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
18379 
18380     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
18381 
18382     ExprResult VisitMemberExpr(MemberExpr *E) {
18383       return resolveDecl(E, E->getMemberDecl());
18384     }
18385 
18386     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
18387       return resolveDecl(E, E->getDecl());
18388     }
18389   };
18390 }
18391 
18392 /// Rebuilds a call expression which yielded __unknown_anytype.
18393 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
18394   Expr *CalleeExpr = E->getCallee();
18395 
18396   enum FnKind {
18397     FK_MemberFunction,
18398     FK_FunctionPointer,
18399     FK_BlockPointer
18400   };
18401 
18402   FnKind Kind;
18403   QualType CalleeType = CalleeExpr->getType();
18404   if (CalleeType == S.Context.BoundMemberTy) {
18405     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
18406     Kind = FK_MemberFunction;
18407     CalleeType = Expr::findBoundMemberType(CalleeExpr);
18408   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
18409     CalleeType = Ptr->getPointeeType();
18410     Kind = FK_FunctionPointer;
18411   } else {
18412     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
18413     Kind = FK_BlockPointer;
18414   }
18415   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
18416 
18417   // Verify that this is a legal result type of a function.
18418   if (DestType->isArrayType() || DestType->isFunctionType()) {
18419     unsigned diagID = diag::err_func_returning_array_function;
18420     if (Kind == FK_BlockPointer)
18421       diagID = diag::err_block_returning_array_function;
18422 
18423     S.Diag(E->getExprLoc(), diagID)
18424       << DestType->isFunctionType() << DestType;
18425     return ExprError();
18426   }
18427 
18428   // Otherwise, go ahead and set DestType as the call's result.
18429   E->setType(DestType.getNonLValueExprType(S.Context));
18430   E->setValueKind(Expr::getValueKindForType(DestType));
18431   assert(E->getObjectKind() == OK_Ordinary);
18432 
18433   // Rebuild the function type, replacing the result type with DestType.
18434   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
18435   if (Proto) {
18436     // __unknown_anytype(...) is a special case used by the debugger when
18437     // it has no idea what a function's signature is.
18438     //
18439     // We want to build this call essentially under the K&R
18440     // unprototyped rules, but making a FunctionNoProtoType in C++
18441     // would foul up all sorts of assumptions.  However, we cannot
18442     // simply pass all arguments as variadic arguments, nor can we
18443     // portably just call the function under a non-variadic type; see
18444     // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
18445     // However, it turns out that in practice it is generally safe to
18446     // call a function declared as "A foo(B,C,D);" under the prototype
18447     // "A foo(B,C,D,...);".  The only known exception is with the
18448     // Windows ABI, where any variadic function is implicitly cdecl
18449     // regardless of its normal CC.  Therefore we change the parameter
18450     // types to match the types of the arguments.
18451     //
18452     // This is a hack, but it is far superior to moving the
18453     // corresponding target-specific code from IR-gen to Sema/AST.
18454 
18455     ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
18456     SmallVector<QualType, 8> ArgTypes;
18457     if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
18458       ArgTypes.reserve(E->getNumArgs());
18459       for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
18460         Expr *Arg = E->getArg(i);
18461         QualType ArgType = Arg->getType();
18462         if (E->isLValue()) {
18463           ArgType = S.Context.getLValueReferenceType(ArgType);
18464         } else if (E->isXValue()) {
18465           ArgType = S.Context.getRValueReferenceType(ArgType);
18466         }
18467         ArgTypes.push_back(ArgType);
18468       }
18469       ParamTypes = ArgTypes;
18470     }
18471     DestType = S.Context.getFunctionType(DestType, ParamTypes,
18472                                          Proto->getExtProtoInfo());
18473   } else {
18474     DestType = S.Context.getFunctionNoProtoType(DestType,
18475                                                 FnType->getExtInfo());
18476   }
18477 
18478   // Rebuild the appropriate pointer-to-function type.
18479   switch (Kind) {
18480   case FK_MemberFunction:
18481     // Nothing to do.
18482     break;
18483 
18484   case FK_FunctionPointer:
18485     DestType = S.Context.getPointerType(DestType);
18486     break;
18487 
18488   case FK_BlockPointer:
18489     DestType = S.Context.getBlockPointerType(DestType);
18490     break;
18491   }
18492 
18493   // Finally, we can recurse.
18494   ExprResult CalleeResult = Visit(CalleeExpr);
18495   if (!CalleeResult.isUsable()) return ExprError();
18496   E->setCallee(CalleeResult.get());
18497 
18498   // Bind a temporary if necessary.
18499   return S.MaybeBindToTemporary(E);
18500 }
18501 
18502 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
18503   // Verify that this is a legal result type of a call.
18504   if (DestType->isArrayType() || DestType->isFunctionType()) {
18505     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
18506       << DestType->isFunctionType() << DestType;
18507     return ExprError();
18508   }
18509 
18510   // Rewrite the method result type if available.
18511   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
18512     assert(Method->getReturnType() == S.Context.UnknownAnyTy);
18513     Method->setReturnType(DestType);
18514   }
18515 
18516   // Change the type of the message.
18517   E->setType(DestType.getNonReferenceType());
18518   E->setValueKind(Expr::getValueKindForType(DestType));
18519 
18520   return S.MaybeBindToTemporary(E);
18521 }
18522 
18523 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
18524   // The only case we should ever see here is a function-to-pointer decay.
18525   if (E->getCastKind() == CK_FunctionToPointerDecay) {
18526     assert(E->getValueKind() == VK_RValue);
18527     assert(E->getObjectKind() == OK_Ordinary);
18528 
18529     E->setType(DestType);
18530 
18531     // Rebuild the sub-expression as the pointee (function) type.
18532     DestType = DestType->castAs<PointerType>()->getPointeeType();
18533 
18534     ExprResult Result = Visit(E->getSubExpr());
18535     if (!Result.isUsable()) return ExprError();
18536 
18537     E->setSubExpr(Result.get());
18538     return E;
18539   } else if (E->getCastKind() == CK_LValueToRValue) {
18540     assert(E->getValueKind() == VK_RValue);
18541     assert(E->getObjectKind() == OK_Ordinary);
18542 
18543     assert(isa<BlockPointerType>(E->getType()));
18544 
18545     E->setType(DestType);
18546 
18547     // The sub-expression has to be a lvalue reference, so rebuild it as such.
18548     DestType = S.Context.getLValueReferenceType(DestType);
18549 
18550     ExprResult Result = Visit(E->getSubExpr());
18551     if (!Result.isUsable()) return ExprError();
18552 
18553     E->setSubExpr(Result.get());
18554     return E;
18555   } else {
18556     llvm_unreachable("Unhandled cast type!");
18557   }
18558 }
18559 
18560 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
18561   ExprValueKind ValueKind = VK_LValue;
18562   QualType Type = DestType;
18563 
18564   // We know how to make this work for certain kinds of decls:
18565 
18566   //  - functions
18567   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
18568     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
18569       DestType = Ptr->getPointeeType();
18570       ExprResult Result = resolveDecl(E, VD);
18571       if (Result.isInvalid()) return ExprError();
18572       return S.ImpCastExprToType(Result.get(), Type,
18573                                  CK_FunctionToPointerDecay, VK_RValue);
18574     }
18575 
18576     if (!Type->isFunctionType()) {
18577       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
18578         << VD << E->getSourceRange();
18579       return ExprError();
18580     }
18581     if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
18582       // We must match the FunctionDecl's type to the hack introduced in
18583       // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
18584       // type. See the lengthy commentary in that routine.
18585       QualType FDT = FD->getType();
18586       const FunctionType *FnType = FDT->castAs<FunctionType>();
18587       const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
18588       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
18589       if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
18590         SourceLocation Loc = FD->getLocation();
18591         FunctionDecl *NewFD = FunctionDecl::Create(
18592             S.Context, FD->getDeclContext(), Loc, Loc,
18593             FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(),
18594             SC_None, false /*isInlineSpecified*/, FD->hasPrototype(),
18595             /*ConstexprKind*/ CSK_unspecified);
18596 
18597         if (FD->getQualifier())
18598           NewFD->setQualifierInfo(FD->getQualifierLoc());
18599 
18600         SmallVector<ParmVarDecl*, 16> Params;
18601         for (const auto &AI : FT->param_types()) {
18602           ParmVarDecl *Param =
18603             S.BuildParmVarDeclForTypedef(FD, Loc, AI);
18604           Param->setScopeInfo(0, Params.size());
18605           Params.push_back(Param);
18606         }
18607         NewFD->setParams(Params);
18608         DRE->setDecl(NewFD);
18609         VD = DRE->getDecl();
18610       }
18611     }
18612 
18613     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
18614       if (MD->isInstance()) {
18615         ValueKind = VK_RValue;
18616         Type = S.Context.BoundMemberTy;
18617       }
18618 
18619     // Function references aren't l-values in C.
18620     if (!S.getLangOpts().CPlusPlus)
18621       ValueKind = VK_RValue;
18622 
18623   //  - variables
18624   } else if (isa<VarDecl>(VD)) {
18625     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
18626       Type = RefTy->getPointeeType();
18627     } else if (Type->isFunctionType()) {
18628       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
18629         << VD << E->getSourceRange();
18630       return ExprError();
18631     }
18632 
18633   //  - nothing else
18634   } else {
18635     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
18636       << VD << E->getSourceRange();
18637     return ExprError();
18638   }
18639 
18640   // Modifying the declaration like this is friendly to IR-gen but
18641   // also really dangerous.
18642   VD->setType(DestType);
18643   E->setType(Type);
18644   E->setValueKind(ValueKind);
18645   return E;
18646 }
18647 
18648 /// Check a cast of an unknown-any type.  We intentionally only
18649 /// trigger this for C-style casts.
18650 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
18651                                      Expr *CastExpr, CastKind &CastKind,
18652                                      ExprValueKind &VK, CXXCastPath &Path) {
18653   // The type we're casting to must be either void or complete.
18654   if (!CastType->isVoidType() &&
18655       RequireCompleteType(TypeRange.getBegin(), CastType,
18656                           diag::err_typecheck_cast_to_incomplete))
18657     return ExprError();
18658 
18659   // Rewrite the casted expression from scratch.
18660   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
18661   if (!result.isUsable()) return ExprError();
18662 
18663   CastExpr = result.get();
18664   VK = CastExpr->getValueKind();
18665   CastKind = CK_NoOp;
18666 
18667   return CastExpr;
18668 }
18669 
18670 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
18671   return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
18672 }
18673 
18674 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
18675                                     Expr *arg, QualType &paramType) {
18676   // If the syntactic form of the argument is not an explicit cast of
18677   // any sort, just do default argument promotion.
18678   ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
18679   if (!castArg) {
18680     ExprResult result = DefaultArgumentPromotion(arg);
18681     if (result.isInvalid()) return ExprError();
18682     paramType = result.get()->getType();
18683     return result;
18684   }
18685 
18686   // Otherwise, use the type that was written in the explicit cast.
18687   assert(!arg->hasPlaceholderType());
18688   paramType = castArg->getTypeAsWritten();
18689 
18690   // Copy-initialize a parameter of that type.
18691   InitializedEntity entity =
18692     InitializedEntity::InitializeParameter(Context, paramType,
18693                                            /*consumed*/ false);
18694   return PerformCopyInitialization(entity, callLoc, arg);
18695 }
18696 
18697 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
18698   Expr *orig = E;
18699   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
18700   while (true) {
18701     E = E->IgnoreParenImpCasts();
18702     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
18703       E = call->getCallee();
18704       diagID = diag::err_uncasted_call_of_unknown_any;
18705     } else {
18706       break;
18707     }
18708   }
18709 
18710   SourceLocation loc;
18711   NamedDecl *d;
18712   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
18713     loc = ref->getLocation();
18714     d = ref->getDecl();
18715   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
18716     loc = mem->getMemberLoc();
18717     d = mem->getMemberDecl();
18718   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
18719     diagID = diag::err_uncasted_call_of_unknown_any;
18720     loc = msg->getSelectorStartLoc();
18721     d = msg->getMethodDecl();
18722     if (!d) {
18723       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
18724         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
18725         << orig->getSourceRange();
18726       return ExprError();
18727     }
18728   } else {
18729     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
18730       << E->getSourceRange();
18731     return ExprError();
18732   }
18733 
18734   S.Diag(loc, diagID) << d << orig->getSourceRange();
18735 
18736   // Never recoverable.
18737   return ExprError();
18738 }
18739 
18740 /// Check for operands with placeholder types and complain if found.
18741 /// Returns ExprError() if there was an error and no recovery was possible.
18742 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
18743   if (!getLangOpts().CPlusPlus) {
18744     // C cannot handle TypoExpr nodes on either side of a binop because it
18745     // doesn't handle dependent types properly, so make sure any TypoExprs have
18746     // been dealt with before checking the operands.
18747     ExprResult Result = CorrectDelayedTyposInExpr(E);
18748     if (!Result.isUsable()) return ExprError();
18749     E = Result.get();
18750   }
18751 
18752   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
18753   if (!placeholderType) return E;
18754 
18755   switch (placeholderType->getKind()) {
18756 
18757   // Overloaded expressions.
18758   case BuiltinType::Overload: {
18759     // Try to resolve a single function template specialization.
18760     // This is obligatory.
18761     ExprResult Result = E;
18762     if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
18763       return Result;
18764 
18765     // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
18766     // leaves Result unchanged on failure.
18767     Result = E;
18768     if (resolveAndFixAddressOfSingleOverloadCandidate(Result))
18769       return Result;
18770 
18771     // If that failed, try to recover with a call.
18772     tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
18773                          /*complain*/ true);
18774     return Result;
18775   }
18776 
18777   // Bound member functions.
18778   case BuiltinType::BoundMember: {
18779     ExprResult result = E;
18780     const Expr *BME = E->IgnoreParens();
18781     PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
18782     // Try to give a nicer diagnostic if it is a bound member that we recognize.
18783     if (isa<CXXPseudoDestructorExpr>(BME)) {
18784       PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
18785     } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
18786       if (ME->getMemberNameInfo().getName().getNameKind() ==
18787           DeclarationName::CXXDestructorName)
18788         PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
18789     }
18790     tryToRecoverWithCall(result, PD,
18791                          /*complain*/ true);
18792     return result;
18793   }
18794 
18795   // ARC unbridged casts.
18796   case BuiltinType::ARCUnbridgedCast: {
18797     Expr *realCast = stripARCUnbridgedCast(E);
18798     diagnoseARCUnbridgedCast(realCast);
18799     return realCast;
18800   }
18801 
18802   // Expressions of unknown type.
18803   case BuiltinType::UnknownAny:
18804     return diagnoseUnknownAnyExpr(*this, E);
18805 
18806   // Pseudo-objects.
18807   case BuiltinType::PseudoObject:
18808     return checkPseudoObjectRValue(E);
18809 
18810   case BuiltinType::BuiltinFn: {
18811     // Accept __noop without parens by implicitly converting it to a call expr.
18812     auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
18813     if (DRE) {
18814       auto *FD = cast<FunctionDecl>(DRE->getDecl());
18815       if (FD->getBuiltinID() == Builtin::BI__noop) {
18816         E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
18817                               CK_BuiltinFnToFnPtr)
18818                 .get();
18819         return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy,
18820                                 VK_RValue, SourceLocation());
18821       }
18822     }
18823 
18824     Diag(E->getBeginLoc(), diag::err_builtin_fn_use);
18825     return ExprError();
18826   }
18827 
18828   // Expressions of unknown type.
18829   case BuiltinType::OMPArraySection:
18830     Diag(E->getBeginLoc(), diag::err_omp_array_section_use);
18831     return ExprError();
18832 
18833   // Expressions of unknown type.
18834   case BuiltinType::OMPArrayShaping:
18835     return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use));
18836 
18837   case BuiltinType::OMPIterator:
18838     return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use));
18839 
18840   // Everything else should be impossible.
18841 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
18842   case BuiltinType::Id:
18843 #include "clang/Basic/OpenCLImageTypes.def"
18844 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
18845   case BuiltinType::Id:
18846 #include "clang/Basic/OpenCLExtensionTypes.def"
18847 #define SVE_TYPE(Name, Id, SingletonId) \
18848   case BuiltinType::Id:
18849 #include "clang/Basic/AArch64SVEACLETypes.def"
18850 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
18851 #define PLACEHOLDER_TYPE(Id, SingletonId)
18852 #include "clang/AST/BuiltinTypes.def"
18853     break;
18854   }
18855 
18856   llvm_unreachable("invalid placeholder type!");
18857 }
18858 
18859 bool Sema::CheckCaseExpression(Expr *E) {
18860   if (E->isTypeDependent())
18861     return true;
18862   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
18863     return E->getType()->isIntegralOrEnumerationType();
18864   return false;
18865 }
18866 
18867 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
18868 ExprResult
18869 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
18870   assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
18871          "Unknown Objective-C Boolean value!");
18872   QualType BoolT = Context.ObjCBuiltinBoolTy;
18873   if (!Context.getBOOLDecl()) {
18874     LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
18875                         Sema::LookupOrdinaryName);
18876     if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
18877       NamedDecl *ND = Result.getFoundDecl();
18878       if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
18879         Context.setBOOLDecl(TD);
18880     }
18881   }
18882   if (Context.getBOOLDecl())
18883     BoolT = Context.getBOOLType();
18884   return new (Context)
18885       ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
18886 }
18887 
18888 ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
18889     llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
18890     SourceLocation RParen) {
18891 
18892   StringRef Platform = getASTContext().getTargetInfo().getPlatformName();
18893 
18894   auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) {
18895     return Spec.getPlatform() == Platform;
18896   });
18897 
18898   VersionTuple Version;
18899   if (Spec != AvailSpecs.end())
18900     Version = Spec->getVersion();
18901 
18902   // The use of `@available` in the enclosing function should be analyzed to
18903   // warn when it's used inappropriately (i.e. not if(@available)).
18904   if (getCurFunctionOrMethodDecl())
18905     getEnclosingFunction()->HasPotentialAvailabilityViolations = true;
18906   else if (getCurBlock() || getCurLambda())
18907     getCurFunction()->HasPotentialAvailabilityViolations = true;
18908 
18909   return new (Context)
18910       ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
18911 }
18912 
18913 bool Sema::IsDependentFunctionNameExpr(Expr *E) {
18914   assert(E->isTypeDependent());
18915   return isa<UnresolvedLookupExpr>(E);
18916 }
18917 
18918 ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End,
18919                                     ArrayRef<Expr *> SubExprs) {
18920   // FIXME: enable it for C++, RecoveryExpr is type-dependent to suppress
18921   // bogus diagnostics and this trick does not work in C.
18922   // FIXME: use containsErrors() to suppress unwanted diags in C.
18923   if (!Context.getLangOpts().RecoveryAST)
18924     return ExprError();
18925 
18926   if (isSFINAEContext())
18927     return ExprError();
18928 
18929   return RecoveryExpr::Create(Context, Begin, End, SubExprs);
18930 }
18931